8057 lines
425 KiB
JavaScript
8057 lines
425 KiB
JavaScript
// rmc-files-handler.js
|
|
|
|
// Open-Sourced: https://github.com/muaz-khan/Chrome-Extensions/tree/master/file-sharing
|
|
|
|
//--------------------------------------------------
|
|
// Muaz Khan - www.MuazKhan.com
|
|
// MIT License - www.WebRTC-Experiment.com/licence
|
|
//--------------------------------------------------
|
|
|
|
(function(window) {
|
|
// to get STUN/TURN URIs from xirsys.com
|
|
window.getExternalIceServers = true;
|
|
|
|
// Last time updated: 2016-11-04 7:11:11 AM UTC
|
|
|
|
// ________________
|
|
// FileBufferReader
|
|
;!function(){function FileBufferReader(){function fbrClone(from,to){if(null==from||"object"!=typeof from)return from;if(from.constructor!=Object&&from.constructor!=Array)return from;if(from.constructor==Date||from.constructor==RegExp||from.constructor==Function||from.constructor==String||from.constructor==Number||from.constructor==Boolean)return new from.constructor(from);to=to||new from.constructor;for(var name in from)to[name]="undefined"==typeof to[name]?fbrClone(from[name],null):to[name];return to}var fbr=this,fbrHelper=new FileBufferReaderHelper;fbr.chunks={},fbr.users={},fbr.readAsArrayBuffer=function(file,callback,extra){var options={file:file,earlyCallback:function(chunk){callback(fbrClone(chunk,{currentPosition:-1}))},extra:extra||{userid:0}};fbrHelper.readAsArrayBuffer(fbr,options)},fbr.getNextChunk=function(fileUUID,callback,userid){var currentPosition;"undefined"!=typeof fileUUID.currentPosition&&(currentPosition=fileUUID.currentPosition,fileUUID=fileUUID.uuid);var allFileChunks=fbr.chunks[fileUUID];if(allFileChunks){"undefined"!=typeof userid?(fbr.users[userid+""]||(fbr.users[userid+""]={fileUUID:fileUUID,userid:userid,currentPosition:-1}),"undefined"!=typeof currentPosition&&(fbr.users[userid+""].currentPosition=currentPosition),fbr.users[userid+""].currentPosition++,currentPosition=fbr.users[userid+""].currentPosition):("undefined"!=typeof currentPosition&&(fbr.chunks[fileUUID].currentPosition=currentPosition),fbr.chunks[fileUUID].currentPosition++,currentPosition=fbr.chunks[fileUUID].currentPosition);var nextChunk=allFileChunks[currentPosition];if(!nextChunk)return delete fbr.chunks[fileUUID],void fbr.convertToArrayBuffer({chunkMissing:!0,currentPosition:currentPosition,uuid:fileUUID},callback);nextChunk=fbrClone(nextChunk),"undefined"!=typeof userid&&(nextChunk.remoteUserId=userid+""),nextChunk.start&&fbr.onBegin(nextChunk),nextChunk.end&&fbr.onEnd(nextChunk),fbr.onProgress(nextChunk),fbr.convertToArrayBuffer(nextChunk,function(buffer){return nextChunk.currentPosition==nextChunk.maxChunks?void callback(buffer,!0):void callback(buffer,!1)})}};var fbReceiver=new FileBufferReceiver(fbr);fbr.addChunk=function(chunk,callback){chunk&&fbReceiver.receive(chunk,function(chunk){fbr.convertToArrayBuffer({readyForNextChunk:!0,currentPosition:chunk.currentPosition,uuid:chunk.uuid},callback)})},fbr.chunkMissing=function(chunk){delete fbReceiver.chunks[chunk.uuid],delete fbReceiver.chunksWaiters[chunk.uuid]},fbr.onBegin=function(){},fbr.onEnd=function(){},fbr.onProgress=function(){},fbr.convertToObject=FileConverter.ConvertToObject,fbr.convertToArrayBuffer=FileConverter.ConvertToArrayBuffer,fbr.setMultipleUsers=function(){}}function FileBufferReaderHelper(){function fileReaderWrapper(options,callback){function addChunks(fileName,binarySlice,addChunkCallback){numOfChunksInSlice=Math.ceil(binarySlice.byteLength/chunkSize);for(var i=0;numOfChunksInSlice>i;i++){var start=i*chunkSize;chunks[currentPosition]=binarySlice.slice(start,Math.min(start+chunkSize,binarySlice.byteLength)),callback({uuid:file.uuid,buffer:chunks[currentPosition],currentPosition:currentPosition,maxChunks:maxChunks,size:file.size,name:file.name,lastModifiedDate:file.lastModifiedDate.toString(),type:file.type}),currentPosition++}currentPosition==maxChunks&&(hasEntireFile=!0),addChunkCallback()}callback=callback||function(chunk){postMessage(chunk)};var file=options.file;file.uuid||(file.uuid=(100*Math.random()).toString().replace(/\./g,""));var chunkSize=options.chunkSize||15e3;options.extra&&options.extra.chunkSize&&(chunkSize=options.extra.chunkSize);var sliceId=0,cacheSize=chunkSize,chunksPerSlice=Math.floor(Math.min(1e8,cacheSize)/chunkSize),sliceSize=chunksPerSlice*chunkSize,maxChunks=Math.ceil(file.size/chunkSize);file.maxChunks=maxChunks;var numOfChunksInSlice,hasEntireFile,currentPosition=0,chunks=[];callback({currentPosition:currentPosition,uuid:file.uuid,maxChunks:maxChunks,size:file.size,name:file.name,type:file.type,lastModifiedDate:file.lastModifiedDate.toString(),start:!0});var blob,reader=new FileReader;reader.onloadend=function(evt){evt.target.readyState==FileReader.DONE&&addChunks(file.name,evt.target.result,function(){sliceId++,(sliceId+1)*sliceSize<file.size?(blob=file.slice(sliceId*sliceSize,(sliceId+1)*sliceSize),reader.readAsArrayBuffer(blob)):sliceId*sliceSize<file.size?(blob=file.slice(sliceId*sliceSize,file.size),reader.readAsArrayBuffer(blob)):(file.url=URL.createObjectURL(file),callback({currentPosition:currentPosition,uuid:file.uuid,maxChunks:maxChunks,size:file.size,name:file.name,lastModifiedDate:file.lastModifiedDate.toString(),url:URL.createObjectURL(file),type:file.type,end:!0}))})},currentPosition+=1,blob=file.slice(sliceId*sliceSize,(sliceId+1)*sliceSize),reader.readAsArrayBuffer(blob)}var fbrHelper=this;fbrHelper.readAsArrayBuffer=function(fbr,options){function processChunk(chunk){fbr.chunks[chunk.uuid]||(fbr.chunks[chunk.uuid]={currentPosition:-1}),options.extra=options.extra||{userid:0},chunk.userid=options.userid||options.extra.userid||0,chunk.extra=options.extra,fbr.chunks[chunk.uuid][chunk.currentPosition]=chunk,chunk.end&&earlyCallback&&(earlyCallback(chunk.uuid),earlyCallback=null),chunk.maxChunks>200&&200==chunk.currentPosition&&earlyCallback&&(earlyCallback(chunk.uuid),earlyCallback=null)}var earlyCallback=options.earlyCallback;delete options.earlyCallback;fileReaderWrapper(options,processChunk)}}function FileSelector(){function selectFile(callback,multiple){var file=document.createElement("input");file.type="file",multiple&&(file.multiple=!0),file.accept=selector.accept,file.onchange=function(){return multiple?file.files.length?void callback(file.files):void console.error("No file selected."):file.files[0]?(callback(file.files[0]),void file.parentNode.removeChild(file)):void console.error("No file selected.")},file.style.display="none",(document.body||document.documentElement).appendChild(file),fireClickEvent(file)}function fireClickEvent(element){var evt=new window.MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,button:0,buttons:0,mozInputSource:1});element.dispatchEvent(evt)}var selector=this;selector.selectSingleFile=selectFile,selector.selectMultipleFiles=function(callback){selectFile(callback,!0)},selector.accept="*.*"}function FileBufferReceiver(fbr){function receive(chunk,callback){if(!chunk.uuid)return void fbr.convertToObject(chunk,function(object){receive(object)});if(chunk.start&&!fbReceiver.chunks[chunk.uuid]&&(fbReceiver.chunks[chunk.uuid]={},fbr.onBegin&&fbr.onBegin(chunk)),!chunk.end&&chunk.buffer&&(fbReceiver.chunks[chunk.uuid][chunk.currentPosition]=chunk.buffer),chunk.end){var chunksObject=fbReceiver.chunks[chunk.uuid],chunksArray=[];Object.keys(chunksObject).forEach(function(item,idx){chunksArray.push(chunksObject[item])});var blob=new Blob(chunksArray,{type:chunk.type});blob=merge(blob,chunk),blob.url=URL.createObjectURL(blob),blob.uuid=chunk.uuid,blob.size||console.error("Something went wrong. Blob Size is 0."),fbr.onEnd&&fbr.onEnd(blob),delete fbReceiver.chunks[chunk.uuid],delete fbReceiver.chunksWaiters[chunk.uuid]}chunk.buffer&&fbr.onProgress&&fbr.onProgress(chunk),chunk.end||(callback(chunk),fbReceiver.chunksWaiters[chunk.uuid]=function(){function looper(){chunk.buffer&&fbReceiver.chunks[chunk.uuid]&&(chunk.currentPosition==chunk.maxChunks||fbReceiver.chunks[chunk.uuid][chunk.currentPosition]||(callback(chunk),setTimeout(looper,5e3)))}setTimeout(looper,5e3)},fbReceiver.chunksWaiters[chunk.uuid]())}var fbReceiver=this;fbReceiver.chunks={},fbReceiver.chunksWaiters={},fbReceiver.receive=receive}function merge(mergein,mergeto){if(mergein||(mergein={}),!mergeto)return mergein;for(var item in mergeto)try{mergein[item]=mergeto[item]}catch(e){}return mergein}var FileConverter={ConvertToArrayBuffer:function(object,callback){binarize.pack(object,function(dataView){callback(dataView.buffer)})},ConvertToObject:function(buffer,callback){binarize.unpack(buffer,callback)}},debug=!1,BIG_ENDIAN=!1,LITTLE_ENDIAN=!0,TYPE_LENGTH=Uint8Array.BYTES_PER_ELEMENT,LENGTH_LENGTH=Uint16Array.BYTES_PER_ELEMENT,BYTES_LENGTH=Uint32Array.BYTES_PER_ELEMENT,Types={NULL:0,UNDEFINED:1,STRING:2,NUMBER:3,BOOLEAN:4,ARRAY:5,OBJECT:6,INT8ARRAY:7,INT16ARRAY:8,INT32ARRAY:9,UINT8ARRAY:10,UINT16ARRAY:11,UINT32ARRAY:12,FLOAT32ARRAY:13,FLOAT64ARRAY:14,ARRAYBUFFER:15,BLOB:16,FILE:16,BUFFER:17};if(debug)var TypeNames=["NULL","UNDEFINED","STRING","NUMBER","BOOLEAN","ARRAY","OBJECT","INT8ARRAY","INT16ARRAY","INT32ARRAY","UINT8ARRAY","UINT16ARRAY","UINT32ARRAY","FLOAT32ARRAY","FLOAT64ARRAY","ARRAYBUFFER","BLOB","BUFFER"];var Length=[null,null,"Uint16","Float64","Uint8",null,null,"Int8","Int16","Int32","Uint8","Uint16","Uint32","Float32","Float64","Uint8","Uint8","Uint8"],binary_dump=function(view,start,length){var table=[],endianness=BIG_ENDIAN,ROW_LENGTH=40;table[0]=[];for(var i=0;ROW_LENGTH>i;i++)table[0][i]=10>i?"0"+i.toString(10):i.toString(10);for(i=0;length>i;i++){var code=view.getUint8(start+i,endianness),index=~~(i/ROW_LENGTH)+1;"undefined"==typeof table[index]&&(table[index]=[]),table[index][i%ROW_LENGTH]=16>code?"0"+code.toString(16):code.toString(16)}for(console.log("%c"+table[0].join(" "),"font-weight: bold;"),i=1;i<table.length;i++)console.log(table[i].join(" "))},find_type=function(obj){var type=void 0;if(void 0===obj)type=Types.UNDEFINED;else if(null===obj)type=Types.NULL;else{var const_name=obj.constructor.name;if(void 0!==const_name)type=Types[const_name.toUpperCase()];else switch(typeof obj){case"string":type=Types.STRING;break;case"number":type=Types.NUMBER;break;case"boolean":type=Types.BOOLEAN;break;case"object":obj instanceof Array?type=Types.ARRAY:obj instanceof Int8Array?type=Types.INT8ARRAY:obj instanceof Int16Array?type=Types.INT16ARRAY:obj instanceof Int32Array?type=Types.INT32ARRAY:obj instanceof Uint8Array?type=Types.UINT8ARRAY:obj instanceof Uint16Array?type=Types.UINT16ARRAY:obj instanceof Uint32Array?type=Types.UINT32ARRAY:obj instanceof Float32Array?type=Types.FLOAT32ARRAY:obj instanceof Float64Array?type=Types.FLOAT64ARRAY:obj instanceof ArrayBuffer?type=Types.ARRAYBUFFER:obj instanceof Blob?type=Types.BLOB:obj instanceof Buffer?type=Types.BUFFER:obj instanceof Object&&(type=Types.OBJECT)}}return type},pack=function(serialized){var cursor=0,i=0,j=0,endianness=BIG_ENDIAN,ab=new ArrayBuffer(serialized[0].byte_length+serialized[0].header_size),view=new DataView(ab);for(i=0;i<serialized.length;i++){var start=cursor,header_size=serialized[i].header_size,type=serialized[i].type,length=serialized[i].length,value=serialized[i].value,byte_length=serialized[i].byte_length,type_name=Length[type],unit=null===type_name?0:window[type_name+"Array"].BYTES_PER_ELEMENT;switch(type===Types.BUFFER?view.setUint8(cursor,Types.BLOB,endianness):view.setUint8(cursor,type,endianness),cursor+=TYPE_LENGTH,debug&&console.info("Packing",type,TypeNames[type]),(type===Types.ARRAY||type===Types.OBJECT)&&(view.setUint16(cursor,length,endianness),cursor+=LENGTH_LENGTH,debug&&console.info("Content Length",length)),view.setUint32(cursor,byte_length,endianness),cursor+=BYTES_LENGTH,debug&&(console.info("Header Size",header_size,"bytes"),console.info("Byte Length",byte_length,"bytes")),type){case Types.NULL:case Types.UNDEFINED:break;case Types.STRING:for(debug&&console.info('Actual Content %c"'+value+'"',"font-weight:bold;"),j=0;length>j;j++,cursor+=unit)view.setUint16(cursor,value.charCodeAt(j),endianness);break;case Types.NUMBER:case Types.BOOLEAN:debug&&console.info("%c"+value.toString(),"font-weight:bold;"),view["set"+type_name](cursor,value,endianness),cursor+=unit;break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:var _view=new Uint8Array(view.buffer,cursor,byte_length);_view.set(new Uint8Array(value.buffer)),cursor+=byte_length;break;case Types.ARRAYBUFFER:case Types.BUFFER:var _view=new Uint8Array(view.buffer,cursor,byte_length);_view.set(new Uint8Array(value)),cursor+=byte_length;break;case Types.BLOB:case Types.ARRAY:case Types.OBJECT:break;default:throw"TypeError: Unexpected type found."}debug&&binary_dump(view,start,cursor-start)}return view},unpack=function(view,cursor){var type,length,byte_length,value,elem,i=0,endianness=BIG_ENDIAN,start=cursor;type=view.getUint8(cursor,endianness),cursor+=TYPE_LENGTH,debug&&console.info("Unpacking",type,TypeNames[type]),(type===Types.ARRAY||type===Types.OBJECT)&&(length=view.getUint16(cursor,endianness),cursor+=LENGTH_LENGTH,debug&&console.info("Content Length",length)),byte_length=view.getUint32(cursor,endianness),cursor+=BYTES_LENGTH,debug&&console.info("Byte Length",byte_length,"bytes");var type_name=Length[type],unit=null===type_name?0:window[type_name+"Array"].BYTES_PER_ELEMENT;switch(type){case Types.NULL:case Types.UNDEFINED:debug&&binary_dump(view,start,cursor-start),value=null;break;case Types.STRING:length=byte_length/unit;var string=[];for(i=0;length>i;i++){var code=view.getUint16(cursor,endianness);cursor+=unit,string.push(String.fromCharCode(code))}value=string.join(""),debug&&(console.info('Actual Content %c"'+value+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.NUMBER:value=view.getFloat64(cursor,endianness),cursor+=unit,debug&&(console.info('Actual Content %c"'+value.toString()+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.BOOLEAN:value=1===view.getUint8(cursor,endianness)?!0:!1,cursor+=unit,debug&&(console.info('Actual Content %c"'+value.toString()+'"',"font-weight:bold;"),binary_dump(view,start,cursor-start));break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:case Types.ARRAYBUFFER:elem=view.buffer.slice(cursor,cursor+byte_length),cursor+=byte_length,value=type===Types.ARRAYBUFFER?elem:new window[type_name+"Array"](elem),debug&&binary_dump(view,start,cursor-start);break;case Types.BLOB:if(debug&&binary_dump(view,start,cursor-start),window.Blob){var mime=unpack(view,cursor),buffer=unpack(view,mime.cursor);cursor=buffer.cursor,value=new Blob([buffer.value],{type:mime.value})}else elem=view.buffer.slice(cursor,cursor+byte_length),cursor+=byte_length,value=new Buffer(elem);break;case Types.ARRAY:for(debug&&binary_dump(view,start,cursor-start),value=[],i=0;length>i;i++)elem=unpack(view,cursor),cursor=elem.cursor,value.push(elem.value);break;case Types.OBJECT:for(debug&&binary_dump(view,start,cursor-start),value={},i=0;length>i;i++){var key=unpack(view,cursor),val=unpack(view,key.cursor);cursor=val.cursor,value[key.value]=val.value}break;default:throw"TypeError: Type not supported."}return{value:value,cursor:cursor}},deferredSerialize=function(array,callback){for(var length=array.length,results=[],count=0,byte_length=0,i=0;i<array.length;i++)!function(index){serialize(array[index],function(result){if(results[index]=result,byte_length+=result[0].header_size+result[0].byte_length,++count===length){for(var array=[],j=0;j<results.length;j++)array=array.concat(results[j]);callback(array,byte_length)}})}(i)},serialize=function(obj,callback){var type,subarray=[],unit=1,header_size=TYPE_LENGTH+BYTES_LENGTH,byte_length=0,length=0,value=obj;switch(type=find_type(obj),unit=void 0===Length[type]||null===Length[type]?0:window[Length[type]+"Array"].BYTES_PER_ELEMENT,type){case Types.UNDEFINED:case Types.NULL:break;case Types.NUMBER:case Types.BOOLEAN:byte_length=unit;break;case Types.STRING:length=obj.length,byte_length+=length*unit;break;case Types.INT8ARRAY:case Types.INT16ARRAY:case Types.INT32ARRAY:case Types.UINT8ARRAY:case Types.UINT16ARRAY:case Types.UINT32ARRAY:case Types.FLOAT32ARRAY:case Types.FLOAT64ARRAY:length=obj.length,byte_length+=length*unit;break;case Types.ARRAY:return void deferredSerialize(obj,function(subarray,byte_length){callback([{type:type,length:obj.length,header_size:header_size+LENGTH_LENGTH,byte_length:byte_length,value:null}].concat(subarray))});case Types.OBJECT:var deferred=[];for(var key in obj)obj.hasOwnProperty(key)&&(deferred.push(key),deferred.push(obj[key]),length++);return void deferredSerialize(deferred,function(subarray,byte_length){callback([{type:type,length:length,header_size:header_size+LENGTH_LENGTH,byte_length:byte_length,value:null}].concat(subarray))});case Types.ARRAYBUFFER:byte_length+=obj.byteLength;break;case Types.BLOB:var mime_type=obj.type,reader=new FileReader;return reader.onload=function(e){deferredSerialize([mime_type,e.target.result],function(subarray,byte_length){callback([{type:type,length:length,header_size:header_size,byte_length:byte_length,value:null}].concat(subarray))})},reader.onerror=function(e){throw"FileReader Error: "+e},void reader.readAsArrayBuffer(obj);case Types.BUFFER:byte_length+=obj.length;break;default:throw'TypeError: Type "'+obj.constructor.name+'" not supported.'}callback([{type:type,length:length,header_size:header_size,byte_length:byte_length,value:value}].concat(subarray))},deserialize=function(buffer,callback){var view=buffer instanceof DataView?buffer:new DataView(buffer),result=unpack(view,0);return result.value};debug&&(window.Test={BIG_ENDIAN:BIG_ENDIAN,LITTLE_ENDIAN:LITTLE_ENDIAN,Types:Types,pack:pack,unpack:unpack,serialize:serialize,deserialize:deserialize});var binarize={pack:function(obj,callback){try{debug&&console.info("%cPacking Start","font-weight: bold; color: red;",obj),serialize(obj,function(array){debug&&console.info("Serialized Object",array),callback(pack(array))})}catch(e){throw e}},unpack:function(buffer,callback){try{debug&&console.info("%cUnpacking Start","font-weight: bold; color: red;",buffer);var result=deserialize(buffer);debug&&console.info("Deserialized Object",result),callback(result)}catch(e){throw e}}};window.FileConverter=FileConverter,window.FileSelector=FileSelector,window.FileBufferReader=FileBufferReader}();
|
|
|
|
// _________________________
|
|
// RTCMultiConnection v3.5.3
|
|
|
|
;var RTCMultiConnection=function(roomid,forceOptions){function SocketConnection(connection,connectCallback){function updateExtraBackup(remoteUserId,extra){connection.peersBackup[remoteUserId]||(connection.peersBackup[remoteUserId]={userid:remoteUserId,extra:{}}),connection.peersBackup[remoteUserId].extra=extra}function onMessageEvent(message){if(message.remoteUserId==connection.userid){if(connection.peers[message.sender]&&connection.peers[message.sender].extra!=message.message.extra&&(connection.peers[message.sender].extra=message.extra,connection.onExtraDataUpdated({userid:message.sender,extra:message.extra}),updateExtraBackup(message.sender,message.extra)),message.message.streamSyncNeeded&&connection.peers[message.sender]){var stream=connection.streamEvents[message.message.streamid];if(!stream||!stream.stream)return;var action=message.message.action;if("ended"===action||"inactive"===action||"stream-removed"===action)return connection.peersBackup[stream.userid]&&(stream.extra=connection.peersBackup[stream.userid].extra),void connection.onstreamended(stream);var type="both"!=message.message.type?message.message.type:null;return void("function"==typeof stream.stream[action]&&stream.stream[action](type))}if("dropPeerConnection"===message.message)return void connection.deletePeer(message.sender);if(message.message.allParticipants)return message.message.allParticipants.indexOf(message.sender)===-1&&message.message.allParticipants.push(message.sender),void message.message.allParticipants.forEach(function(participant){mPeer[connection.peers[participant]?"renegotiatePeer":"createNewPeer"](participant,{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})});if(message.message.newParticipant){if(message.message.newParticipant==connection.userid)return;if(connection.peers[message.message.newParticipant])return;return void mPeer.createNewPeer(message.message.newParticipant,message.message.userPreferences||{localPeerSdpConstraints:{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:isData(connection.session)})}if(message.message.readyForOffer&&(connection.attachStreams.length&&(connection.waitingForLocalMedia=!1),connection.waitingForLocalMedia))return void setTimeout(function(){onMessageEvent(message)},1);if(message.message.newParticipationRequest&&message.sender!==connection.userid){connection.peers[message.sender]&&connection.deletePeer(message.sender);var userPreferences={extra:message.extra||{},localPeerSdpConstraints:message.message.remotePeerSdpConstraints||{OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},remotePeerSdpConstraints:message.message.localPeerSdpConstraints||{OfferToReceiveAudio:connection.session.oneway?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.session.oneway?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo},isOneWay:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,isDataOnly:"undefined"!=typeof message.message.isDataOnly?message.message.isDataOnly:isData(connection.session),dontGetRemoteStream:"undefined"!=typeof message.message.isOneWay?message.message.isOneWay:!!connection.session.oneway||"one-way"===connection.direction,dontAttachLocalStream:!!message.message.dontGetRemoteStream,connectionDescription:message,successCallback:function(){}};return void connection.onNewParticipant(message.sender,userPreferences)}return message.message.changedUUID&&connection.peers[message.message.oldUUID]&&(connection.peers[message.message.newUUID]=connection.peers[message.message.oldUUID],delete connection.peers[message.message.oldUUID]),message.message.userLeft?(mPeer.onUserLeft(message.sender),void(message.message.autoCloseEntireSession&&connection.leave())):void mPeer.addNegotiatedMessage(message.message,message.sender)}}var parameters="";parameters+="?userid="+connection.userid,parameters+="&sessionid="+connection.sessionid,parameters+="&msgEvent="+connection.socketMessageEvent,parameters+="&socketCustomEvent="+connection.socketCustomEvent,parameters+="&autoCloseEntireSession="+!!connection.autoCloseEntireSession,connection.session.broadcast===!0&&(parameters+="&oneToMany=true"),parameters+="&maxParticipantsAllowed="+connection.maxParticipantsAllowed,connection.enableScalableBroadcast&&(parameters+="&enableScalableBroadcast=true",parameters+="&maxRelayLimitPerUser="+(connection.maxRelayLimitPerUser||2)),parameters+="&extra="+JSON.stringify(connection.extra||{}),connection.socketCustomParameters&&(parameters+=connection.socketCustomParameters);try{io.sockets={}}catch(e){}if(connection.socketURL||(connection.socketURL="/"),"/"!=connection.socketURL.substr(connection.socketURL.length-1,1))throw'"socketURL" MUST end with a slash.';connection.enableLogs&&("/"==connection.socketURL?console.info("socket.io url is: ",location.origin+"/"):console.info("socket.io url is: ",connection.socketURL));try{connection.socket=io(connection.socketURL+parameters)}catch(e){connection.socket=io.connect(connection.socketURL+parameters,connection.socketOptions)}var mPeer=connection.multiPeersHandler;connection.socket.on("extra-data-updated",function(remoteUserId,extra){connection.peers[remoteUserId]&&(connection.peers[remoteUserId].extra=extra,connection.onExtraDataUpdated({userid:remoteUserId,extra:extra}),updateExtraBackup(remoteUserId,extra))}),connection.socket.on(connection.socketMessageEvent,onMessageEvent);var alreadyConnected=!1;connection.socket.resetProps=function(){alreadyConnected=!1},connection.socket.on("connect",function(){alreadyConnected||(alreadyConnected=!0,connection.enableLogs&&console.info("socket.io connection is opened."),setTimeout(function(){connection.socket.emit("extra-data-updated",connection.extra)},1e3),connectCallback&&connectCallback(connection.socket))}),connection.socket.on("disconnect",function(){connection.enableLogs&&console.warn("socket.io connection is closed")}),connection.socket.on("user-disconnected",function(remoteUserId){remoteUserId!==connection.userid&&(connection.onUserStatusChanged({userid:remoteUserId,status:"offline",extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra||{}:{}}),connection.deletePeer(remoteUserId))}),connection.socket.on("user-connected",function(userid){userid!==connection.userid&&connection.onUserStatusChanged({userid:userid,status:"online",extra:connection.peers[userid]?connection.peers[userid].extra||{}:{}})}),connection.socket.on("closed-entire-session",function(sessionid,extra){connection.leave(),connection.onEntireSessionClosed({sessionid:sessionid,userid:sessionid,extra:extra})}),connection.socket.on("userid-already-taken",function(useridAlreadyTaken,yourNewUserId){connection.isInitiator=!1,connection.userid=yourNewUserId,connection.onUserIdAlreadyTaken(useridAlreadyTaken,yourNewUserId)}),connection.socket.on("logs",function(log){connection.enableLogs&&console.debug("server-logs",log)}),connection.socket.on("number-of-broadcast-viewers-updated",function(data){connection.onNumberOfBroadcastViewersUpdated(data)}),connection.socket.on("set-isInitiator-true",function(sessionid){sessionid==connection.sessionid&&(connection.isInitiator=!0)})}function MultiPeers(connection){function initFileBufferReader(){connection.fbr=new FileBufferReader,connection.fbr.onProgress=function(chunk){connection.onFileProgress(chunk)},connection.fbr.onBegin=function(file){connection.onFileStart(file)},connection.fbr.onEnd=function(file){connection.onFileEnd(file)}}var self=this,skipPeers=["getAllParticipants","getLength","selectFirst","streams","send","forEach"];connection.peers={getLength:function(){var numberOfPeers=0;for(var peer in this)skipPeers.indexOf(peer)==-1&&numberOfPeers++;return numberOfPeers},selectFirst:function(){var firstPeer;for(var peer in this)skipPeers.indexOf(peer)==-1&&(firstPeer=this[peer]);return firstPeer},getAllParticipants:function(sender){var allPeers=[];for(var peer in this)skipPeers.indexOf(peer)==-1&&peer!=sender&&allPeers.push(peer);return allPeers},forEach:function(callbcak){this.getAllParticipants().forEach(function(participant){callbcak(connection.peers[participant])})},send:function(data,remoteUserId){var that=this;if(!isNull(data.size)&&!isNull(data.type))return void self.shareFile(data,remoteUserId);if(!("text"===data.type||data instanceof ArrayBuffer||data instanceof DataView))return void TextSender.send({text:data,channel:this,connection:connection,remoteUserId:remoteUserId});if("text"===data.type&&(data=JSON.stringify(data)),remoteUserId){var remoteUser=connection.peers[remoteUserId];if(remoteUser)return remoteUser.channels.length?void remoteUser.channels.forEach(function(channel){channel.send(data)}):(connection.peers[remoteUserId].createDataChannel(),connection.renegotiate(remoteUserId),void setTimeout(function(){that.send(data,remoteUserId)},3e3))}this.getAllParticipants().forEach(function(participant){return that[participant].channels.length?void that[participant].channels.forEach(function(channel){channel.send(data)}):(connection.peers[participant].createDataChannel(),connection.renegotiate(participant),void setTimeout(function(){that[participant].channels.forEach(function(channel){channel.send(data)})},3e3))})}},this.uuid=connection.userid,this.getLocalConfig=function(remoteSdp,remoteUserId,userPreferences){return userPreferences||(userPreferences={}),{streamsToShare:userPreferences.streamsToShare||{},rtcMultiConnection:connection,connectionDescription:userPreferences.connectionDescription,userid:remoteUserId,localPeerSdpConstraints:userPreferences.localPeerSdpConstraints,remotePeerSdpConstraints:userPreferences.remotePeerSdpConstraints,dontGetRemoteStream:!!userPreferences.dontGetRemoteStream,dontAttachLocalStream:!!userPreferences.dontAttachLocalStream,renegotiatingPeer:!!userPreferences.renegotiatingPeer,peerRef:userPreferences.peerRef,channels:userPreferences.channels||[],onLocalSdp:function(localSdp){self.onNegotiationNeeded(localSdp,remoteUserId)},onLocalCandidate:function(localCandidate){localCandidate=OnIceCandidateHandler.processCandidates(connection,localCandidate),localCandidate&&self.onNegotiationNeeded(localCandidate,remoteUserId)},remoteSdp:remoteSdp,onDataChannelMessage:function(message){if(!connection.fbr&&connection.enableFileSharing&&initFileBufferReader(),"string"==typeof message||!connection.enableFileSharing)return void self.onDataChannelMessage(message,remoteUserId);var that=this;return message instanceof ArrayBuffer||message instanceof DataView?void connection.fbr.convertToObject(message,function(object){that.onDataChannelMessage(object)}):message.readyForNextChunk?void connection.fbr.getNextChunk(message,function(nextChunk,isLastChunk){connection.peers[remoteUserId].channels.forEach(function(channel){channel.send(nextChunk)})},remoteUserId):message.chunkMissing?void connection.fbr.chunkMissing(message):void connection.fbr.addChunk(message,function(promptNextChunk){connection.peers[remoteUserId].peer.channel.send(promptNextChunk)})},onDataChannelError:function(error){self.onDataChannelError(error,remoteUserId)},onDataChannelOpened:function(channel){self.onDataChannelOpened(channel,remoteUserId)},onDataChannelClosed:function(event){self.onDataChannelClosed(event,remoteUserId)},onRemoteStream:function(stream){connection.peers[remoteUserId]&&connection.peers[remoteUserId].streams.push(stream),self.onGettingRemoteMedia(stream,remoteUserId)},onRemoteStreamRemoved:function(stream){self.onRemovingRemoteMedia(stream,remoteUserId)},onPeerStateChanged:function(states){self.onPeerStateChanged(states),"new"===states.iceConnectionState&&self.onNegotiationStarted(remoteUserId,states),"connected"===states.iceConnectionState&&self.onNegotiationCompleted(remoteUserId,states),states.iceConnectionState.search(/closed|failed/gi)!==-1&&(self.onUserLeft(remoteUserId),self.disconnectWith(remoteUserId))}}},this.createNewPeer=function(remoteUserId,userPreferences){if(!(connection.maxParticipantsAllowed<=connection.getAllParticipants().length)){if(userPreferences=userPreferences||{},connection.isInitiator&&connection.session.audio&&"two-way"===connection.session.audio&&!userPreferences.streamsToShare&&(userPreferences.isOneWay=!1,userPreferences.isDataOnly=!1,userPreferences.session=connection.session),!userPreferences.isOneWay&&!userPreferences.isDataOnly)return userPreferences.isOneWay=!0,void this.onNegotiationNeeded({enableMedia:!0,userPreferences:userPreferences},remoteUserId);userPreferences=connection.setUserPreferences(userPreferences,remoteUserId);var localConfig=this.getLocalConfig(null,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)}},this.createAnsweringPeer=function(remoteSdp,remoteUserId,userPreferences){userPreferences=connection.setUserPreferences(userPreferences||{},remoteUserId);var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.renegotiatePeer=function(remoteUserId,userPreferences,remoteSdp){if(!connection.peers[remoteUserId])return void(connection.enableLogs&&console.error("Peer ("+remoteUserId+") does not exist. Renegotiation skipped."));userPreferences||(userPreferences={}),userPreferences.renegotiatingPeer=!0,userPreferences.peerRef=connection.peers[remoteUserId].peer,userPreferences.channels=connection.peers[remoteUserId].channels;var localConfig=this.getLocalConfig(remoteSdp,remoteUserId,userPreferences);connection.peers[remoteUserId]=new PeerInitiator(localConfig)},this.replaceTrack=function(track,remoteUserId,isVideoTrack){if(!connection.peers[remoteUserId])throw"This peer ("+remoteUserId+") does not exist.";var peer=connection.peers[remoteUserId].peer;return peer.getSenders&&"function"==typeof peer.getSenders&&peer.getSenders().length?void peer.getSenders().forEach(function(rtpSender){isVideoTrack&&"video"===rtpSender.track.kind&&(connection.peers[remoteUserId].peer.lastVideoTrack=rtpSender.track,rtpSender.replaceTrack(track)),isVideoTrack||"audio"!==rtpSender.track.kind||(connection.peers[remoteUserId].peer.lastAudioTrack=rtpSender.track,rtpSender.replaceTrack(track))}):(console.warn("RTPSender.replaceTrack is NOT supported."),void this.renegotiatePeer(remoteUserId))},this.onNegotiationNeeded=function(message,remoteUserId){},this.addNegotiatedMessage=function(message,remoteUserId){if(message.type&&message.sdp)return"answer"==message.type&&connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteSdp(message),"offer"==message.type&&(message.renegotiatingPeer?this.renegotiatePeer(remoteUserId,null,message):this.createAnsweringPeer(message,remoteUserId)),void(connection.enableLogs&&console.log("Remote peer's sdp:",message.sdp));if(message.candidate)return connection.peers[remoteUserId]&&connection.peers[remoteUserId].addRemoteCandidate(message),void(connection.enableLogs&&console.log("Remote peer's candidate pairs:",message.candidate));if(message.enableMedia){connection.session=message.userPreferences.session||connection.session,connection.session.oneway&&connection.attachStreams.length&&(connection.attachStreams=[]),message.userPreferences.isDataOnly&&connection.attachStreams.length&&(connection.attachStreams.length=[]);var streamsToShare={};connection.attachStreams.forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),message.userPreferences.streamsToShare=streamsToShare,self.onNegotiationNeeded({readyForOffer:!0,userPreferences:message.userPreferences},remoteUserId)}message.readyForOffer&&connection.onReadyForOffer(remoteUserId,message.userPreferences)},this.onGettingRemoteMedia=function(stream,remoteUserId){},this.onRemovingRemoteMedia=function(stream,remoteUserId){},this.onGettingLocalMedia=function(localStream){},this.onLocalMediaError=function(error,constraints){connection.onMediaError(error,constraints)},this.shareFile=function(file,remoteUserId){if(!connection.enableFileSharing)throw'"connection.enableFileSharing" is false.';initFileBufferReader(),connection.fbr.readAsArrayBuffer(file,function(uuid){var arrayOfUsers=connection.getAllParticipants();remoteUserId&&(arrayOfUsers=[remoteUserId]),arrayOfUsers.forEach(function(participant){connection.fbr.getNextChunk(uuid,function(nextChunk){connection.peers[participant].channels.forEach(function(channel){channel.send(nextChunk)})},participant)})},{userid:connection.userid,chunkSize:"Firefox"===DetectRTC.browser.name?15e3:connection.chunkSize||0})};var textReceiver=new TextReceiver(connection);this.onDataChannelMessage=function(message,remoteUserId){textReceiver.receive(JSON.parse(message),remoteUserId,connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{})},this.onDataChannelClosed=function(event,remoteUserId){event.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onclose(event)},this.onDataChannelError=function(error,remoteUserId){error.userid=remoteUserId,event.extra=connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},connection.onerror(error)},this.onDataChannelOpened=function(channel,remoteUserId){return connection.peers[remoteUserId].channels.length?void(connection.peers[remoteUserId].channels=[channel]):(connection.peers[remoteUserId].channels.push(channel),void connection.onopen({userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},channel:channel}))},this.onPeerStateChanged=function(state){connection.onPeerStateChanged(state)},this.onNegotiationStarted=function(remoteUserId,states){},this.onNegotiationCompleted=function(remoteUserId,states){},this.getRemoteStreams=function(remoteUserId){return remoteUserId=remoteUserId||connection.peers.getAllParticipants()[0],connection.peers[remoteUserId]?connection.peers[remoteUserId].streams:[]}}function fireEvent(obj,eventName,args){if("undefined"!=typeof CustomEvent){var eventDetail={arguments:args,__exposedProps__:args},event=new CustomEvent(eventName,eventDetail);obj.dispatchEvent(event)}}function setHarkEvents(connection,streamEvent){if(streamEvent.stream&&streamEvent.stream.getAudioTracks&&streamEvent.stream.getAudioTracks().length){if(!connection||!streamEvent)throw"Both arguments are required.";if(connection.onspeaking&&connection.onsilence){if("undefined"==typeof hark)throw"hark.js not found.";hark(streamEvent.stream,{onspeaking:function(){connection.onspeaking(streamEvent)},onsilence:function(){connection.onsilence(streamEvent)},onvolumechange:function(volume,threshold){connection.onvolumechange&&connection.onvolumechange(merge({volume:volume,threshold:threshold},streamEvent))}})}}}function setMuteHandlers(connection,streamEvent){streamEvent.stream&&streamEvent.stream&&streamEvent.stream.addEventListener&&(streamEvent.stream.addEventListener("mute",function(event){event=connection.streamEvents[streamEvent.streamid],event.session={audio:"audio"===event.muteType,video:"video"===event.muteType},connection.onmute(event)},!1),streamEvent.stream.addEventListener("unmute",function(event){event=connection.streamEvents[streamEvent.streamid],event.session={audio:"audio"===event.unmuteType,video:"video"===event.unmuteType},connection.onunmute(event)},!1))}function getRandomString(){if(window.crypto&&window.crypto.getRandomValues&&navigator.userAgent.indexOf("Safari")===-1){for(var a=window.crypto.getRandomValues(new Uint32Array(3)),token="",i=0,l=a.length;i<l;i++)token+=a[i].toString(36);return token}return(Math.random()*(new Date).getTime()).toString(36).replace(/\./g,"")}function getRMCMediaElement(stream,callback,connection){if(!connection.autoCreateMediaElement)return void callback({});var isAudioOnly=!1;!stream.getVideoTracks||stream.getVideoTracks().length||stream.isVideo||stream.isScreen||(isAudioOnly=!0),"Firefox"===DetectRTC.browser.name&&(connection.session.video||connection.session.screen)&&(isAudioOnly=!1);var mediaElement=document.createElement(isAudioOnly?"audio":"video");mediaElement.srcObject=stream;try{mediaElement.setAttributeNode(document.createAttribute("autoplay")),mediaElement.setAttributeNode(document.createAttribute("playsinline")),mediaElement.setAttributeNode(document.createAttribute("controls"))}catch(e){mediaElement.setAttribute("autoplay",!0),mediaElement.setAttribute("playsinline",!0),mediaElement.setAttribute("controls",!0)}if("Firefox"===DetectRTC.browser.name){var streamEndedEvent="ended";"oninactive"in mediaElement&&(streamEndedEvent="inactive"),mediaElement.addEventListener(streamEndedEvent,function(){if(currentUserMediaRequest.remove(stream.idInstance),"local"===stream.type){streamEndedEvent="ended","oninactive"in stream&&(streamEndedEvent="inactive"),StreamsHandler.onSyncNeeded(stream.streamid,streamEndedEvent),connection.attachStreams.forEach(function(aStream,idx){stream.streamid===aStream.streamid&&delete connection.attachStreams[idx]});var newStreamsArray=[];connection.attachStreams.forEach(function(aStream){aStream&&newStreamsArray.push(aStream)}),connection.attachStreams=newStreamsArray;var streamEvent=connection.streamEvents[stream.streamid];if(streamEvent)return void connection.onstreamended(streamEvent);this.parentNode&&this.parentNode.removeChild(this)}},!1)}var played=mediaElement.play();if("undefined"!=typeof played){var cbFired=!1;setTimeout(function(){cbFired||(cbFired=!0,callback(mediaElement))},1e3),played.then(function(){cbFired||(cbFired=!0,callback(mediaElement))})["catch"](function(error){cbFired||(cbFired=!0,callback(mediaElement))})}else callback(mediaElement)}function listenEventHandler(eventName,eventHandler){window.removeEventListener(eventName,eventHandler),window.addEventListener(eventName,eventHandler,!1)}function removeNullEntries(array){var newArray=[];return array.forEach(function(item){item&&newArray.push(item)}),newArray}function isData(session){return!session.audio&&!session.video&&!session.screen&&session.data}function isNull(obj){return"undefined"==typeof obj}function isString(obj){return"string"==typeof obj}function isAudioPlusTab(connection,audioPlusTab){return(!connection.session.audio||"two-way"!==connection.session.audio)&&("Firefox"===DetectRTC.browser.name&&audioPlusTab!==!1||!("Chrome"!==DetectRTC.browser.name||DetectRTC.browser.version<50)&&(typeof audioPlusTab===!0||!("undefined"!=typeof audioPlusTab||!connection.session.audio||!connection.session.screen||connection.session.video)&&(audioPlusTab=!0,!0)))}function getAudioScreenConstraints(screen_constraints){return"Firefox"===DetectRTC.browser.name||"Chrome"===DetectRTC.browser.name&&{mandatory:{chromeMediaSource:screen_constraints.mandatory.chromeMediaSource,chromeMediaSourceId:screen_constraints.mandatory.chromeMediaSourceId}}}function setCordovaAPIs(){if("undefined"!=typeof cordova&&"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.iosrtc){var iosrtc=cordova.plugins.iosrtc;window.webkitRTCPeerConnection=iosrtc.RTCPeerConnection,window.RTCSessionDescription=iosrtc.RTCSessionDescription,window.RTCIceCandidate=iosrtc.RTCIceCandidate,window.MediaStream=iosrtc.MediaStream,window.MediaStreamTrack=iosrtc.MediaStreamTrack,navigator.getUserMedia=navigator.webkitGetUserMedia=iosrtc.getUserMedia,iosrtc.debug.enable("iosrtc*"),"function"==typeof iosrtc.selectAudioOutput&&iosrtc.selectAudioOutput(window.iOSDefaultAudioOutputDevice||"speaker"),iosrtc.registerGlobals()}}function setSdpConstraints(config){var sdpConstraints={OfferToReceiveAudio:!!config.OfferToReceiveAudio,OfferToReceiveVideo:!!config.OfferToReceiveVideo},oldBrowser=!window.enableAdapter;return"Chrome"===DetectRTC.browser.name&&DetectRTC.browser.version>=60,"Firefox"===DetectRTC.browser.name&&DetectRTC.browser.version>=54&&(oldBrowser=!1),oldBrowser&&(sdpConstraints={mandatory:sdpConstraints,optional:[{VoiceActivityDetection:!1}]}),sdpConstraints}function PeerInitiator(config){function oldAddRemoteSdp(remoteSdp,cb){cb=cb||function(){},"Safari"!==DetectRTC.browser.name&&(remoteSdp.sdp=connection.processSdp(remoteSdp.sdp)),peer.setRemoteDescription(new RTCSessionDescription(remoteSdp),cb,function(error){connection.enableLogs&&console.error("setRemoteDescription failed","\n",error,"\n",remoteSdp.sdp),cb()})}function setChannelEvents(channel){channel.binaryType="arraybuffer",channel.onmessage=function(event){config.onDataChannelMessage(event.data)},channel.onopen=function(){config.onDataChannelOpened(channel)},channel.onerror=function(error){config.onDataChannelError(error)},channel.onclose=function(event){config.onDataChannelClosed(event)},channel.internalSend=channel.send,channel.send=function(data){"open"===channel.readyState&&channel.internalSend(data)},peer.channel=channel}function oldCreateOfferOrAnswer(_method){peer[_method](function(localSdp){"Safari"!==DetectRTC.browser.name&&(localSdp.sdp=connection.processSdp(localSdp.sdp)),peer.setLocalDescription(localSdp,function(){connection.trickleIce&&(config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:self.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare}),connection.onSettingLocalDescription(self))},function(error){connection.enableLogs&&console.error("setLocalDescription-error",error)})},function(error){connection.enableLogs&&console.error("sdp-"+_method+"-error",error)},defaults.sdpConstraints)}function createOfferOrAnswer(_method){return window.enableAdapter?void peer[_method](defaults.sdpConstraints).then(function(localSdp){"Safari"!==DetectRTC.browser.name&&(localSdp.sdp=connection.processSdp(localSdp.sdp)),peer.setLocalDescription(localSdp).then(function(){connection.trickleIce&&(config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:self.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare}),connection.onSettingLocalDescription(self))},function(error){connection.enableLogs&&console.error("setLocalDescription error",error)})},function(error){connection.enableLogs&&console.error("sdp-error",error)}):oldCreateOfferOrAnswer(_method)}if("undefined"!=typeof window.RTCPeerConnection?RTCPeerConnection=window.RTCPeerConnection:"undefined"!=typeof mozRTCPeerConnection?RTCPeerConnection=mozRTCPeerConnection:"undefined"!=typeof webkitRTCPeerConnection&&(RTCPeerConnection=webkitRTCPeerConnection),RTCSessionDescription=window.RTCSessionDescription||window.mozRTCSessionDescription,RTCIceCandidate=window.RTCIceCandidate||window.mozRTCIceCandidate,MediaStreamTrack=window.MediaStreamTrack,!RTCPeerConnection)throw"WebRTC 1.0 (RTCPeerConnection) API are NOT available in this browser.";var connection=config.rtcMultiConnection;this.extra=config.remoteSdp?config.remoteSdp.extra:connection.extra,this.userid=config.userid,this.streams=[],this.channels=config.channels||[],this.connectionDescription=config.connectionDescription,this.addStream=function(session){connection.addStream(session,self.userid)},this.removeStream=function(streamid){connection.removeStream(streamid,self.userid)};var self=this;config.remoteSdp&&(this.connectionDescription=config.remoteSdp.connectionDescription);var allRemoteStreams={};defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:!0,OfferToReceiveVideo:!0});var peer,renegotiatingPeer=!!config.renegotiatingPeer;config.remoteSdp&&(renegotiatingPeer=!!config.remoteSdp.renegotiatingPeer);var localStreams=[];if(connection.attachStreams.forEach(function(stream){stream&&localStreams.push(stream)}),renegotiatingPeer)peer=config.peerRef;else{var iceTransports="all";(connection.candidates.turn||connection.candidates.relay)&&(connection.candidates.stun||connection.candidates.reflexive||connection.candidates.host||(iceTransports="relay"));try{var params={};"Chrome"!==DetectRTC.browser.name&&(params.iceServers=connection.iceServers),"Chrome"===DetectRTC.browser.name&&(params={iceServers:connection.iceServers,iceTransportPolicy:connection.iceTransportPolicy||iceTransports}),connection.iceServers.length||(params=null,connection.optionalArgument=null),peer=new RTCPeerConnection(params,connection.optionalArgument)}catch(e){try{var params={iceServers:connection.iceServers};peer=new RTCPeerConnection(params)}catch(e){peer=new RTCPeerConnection}}}!peer.getRemoteStreams&&peer.getReceivers&&(peer.getRemoteStreams=function(){var stream=new MediaStream;return peer.getReceivers().forEach(function(receiver){stream.addTrack(receiver.track)}),[stream]}),!peer.getLocalStreams&&peer.getSenders&&(peer.getLocalStreams=function(){var stream=new MediaStream;return peer.getSenders().forEach(function(sender){stream.addTrack(sender.track)}),[stream]}),peer.onicecandidate=function(event){if(event.candidate)connection.trickleIce&&config.onLocalCandidate({candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex});else if(!connection.trickleIce){var localSdp=peer.localDescription;config.onLocalSdp({type:localSdp.type,sdp:localSdp.sdp,remotePeerSdpConstraints:config.remotePeerSdpConstraints||!1,renegotiatingPeer:!!config.renegotiatingPeer||!1,connectionDescription:self.connectionDescription,dontGetRemoteStream:!!config.dontGetRemoteStream,extra:connection?connection.extra:{},streamsToShare:streamsToShare})}},localStreams.forEach(function(localStream){if(!(config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.dontGetRemoteStream)&&!config.dontAttachLocalStream&&(localStream=connection.beforeAddingStream(localStream,self)))if(peer.getLocalStreams().forEach(function(stream){localStream&&stream.id==localStream.id&&(localStream=null)}),localStream&&"function"==typeof peer.addTrack)localStream.getTracks().forEach(function(track){try{peer.addTrack(track,localStream)}catch(e){}});else if(localStream&&"function"==typeof peer.addStream)peer.addStream(localStream);else try{peer.addStream(localStream)}catch(e){localStream&&localStream.getTracks().forEach(function(track){try{peer.addTrack(track,localStream)}catch(e){}})}}),peer.oniceconnectionstatechange=peer.onsignalingstatechange=function(){var extra=self.extra;connection.peers[self.userid]&&(extra=connection.peers[self.userid].extra||extra),peer&&(config.onPeerStateChanged({iceConnectionState:peer.iceConnectionState,iceGatheringState:peer.iceGatheringState,signalingState:peer.signalingState,extra:extra,userid:self.userid}),peer&&peer.iceConnectionState&&peer.iceConnectionState.search(/closed|failed/gi)!==-1&&self.streams instanceof Array&&self.streams.forEach(function(stream){
|
|
var streamEvent=connection.streamEvents[stream.id]||{streamid:stream.id,stream:stream,type:"remote"};connection.onstreamended(streamEvent)}))};var sdpConstraints={OfferToReceiveAudio:!!localStreams.length,OfferToReceiveVideo:!!localStreams.length};config.localPeerSdpConstraints&&(sdpConstraints=config.localPeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints);var dontDuplicate={},incomingStreamEvent="track";window.enableAdapter||(incomingStreamEvent="addstream"),peer.addEventListener(incomingStreamEvent,function(event){if(event&&("track"===incomingStreamEvent&&(event.stream=event.streams[event.streams.length-1]),!dontDuplicate[event.stream.id]||"Safari"===DetectRTC.browser.name)){dontDuplicate[event.stream.id]=event.stream.id;var streamsToShare={};config.remoteSdp&&config.remoteSdp.streamsToShare?streamsToShare=config.remoteSdp.streamsToShare:config.streamsToShare&&(streamsToShare=config.streamsToShare);var streamToShare=streamsToShare[event.stream.id];streamToShare?(event.stream.isAudio=streamToShare.isAudio,event.stream.isVideo=streamToShare.isVideo,event.stream.isScreen=streamToShare.isScreen):(event.stream.isVideo=!!event.stream.getVideoTracks().length,event.stream.isAudio=!event.stream.isVideo,event.stream.isScreen=!1),event.stream.streamid=event.stream.id,"Firefox"!=DetectRTC.browser.name&&event.stream.stop||(event.stream.stop=function(){var streamEndedEvent="ended";"oninactive"in event.stream&&(streamEndedEvent="inactive"),fireEvent(event.stream,streamEndedEvent)}),allRemoteStreams[event.stream.id]=event.stream,config.onRemoteStream(event.stream)}},!1),peer.onremovestream=function(event){event.stream.streamid=event.stream.id,allRemoteStreams[event.stream.id]&&delete allRemoteStreams[event.stream.id],config.onRemoteStreamRemoved(event.stream)},this.addRemoteCandidate=function(remoteCandidate){peer.addIceCandidate(new RTCIceCandidate(remoteCandidate))},this.addRemoteSdp=function(remoteSdp,cb){return cb=cb||function(){},window.enableAdapter?("Safari"!==DetectRTC.browser.name&&(remoteSdp.sdp=connection.processSdp(remoteSdp.sdp)),void peer.setRemoteDescription(new RTCSessionDescription(remoteSdp)).then(cb,function(error){connection.enableLogs&&console.error("setRemoteDescription failed","\n",error,"\n",remoteSdp.sdp),cb()})):oldAddRemoteSdp(remoteSdp,cb)};var isOfferer=!0;config.remoteSdp&&(isOfferer=!1),this.createDataChannel=function(){var channel=peer.createDataChannel("sctp",{});setChannelEvents(channel)},connection.session.data!==!0||renegotiatingPeer||(isOfferer?this.createDataChannel():peer.ondatachannel=function(event){var channel=event.channel;setChannelEvents(channel)}),this.enableDisableVideoEncoding=function(enable){var rtcp;if(peer.getSenders().forEach(function(sender){rtcp||"video"!==sender.track.kind||(rtcp=sender)}),rtcp&&rtcp.getParameters){var parameters=rtcp.getParameters();parameters.encodings[1]&&(parameters.encodings[1].active=!!enable),parameters.encodings[2]&&(parameters.encodings[2].active=!!enable),rtcp.setParameters(parameters)}},config.remoteSdp&&(config.remoteSdp.remotePeerSdpConstraints&&(sdpConstraints=config.remoteSdp.remotePeerSdpConstraints),defaults.sdpConstraints=setSdpConstraints(sdpConstraints),this.addRemoteSdp(config.remoteSdp,function(){createOfferOrAnswer("createAnswer")})),"two-way"!=connection.session.audio&&"two-way"!=connection.session.video&&"two-way"!=connection.session.screen||(defaults.sdpConstraints=setSdpConstraints({OfferToReceiveAudio:"two-way"==connection.session.audio||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio,OfferToReceiveVideo:"two-way"==connection.session.video||"two-way"==connection.session.screen||config.remoteSdp&&config.remoteSdp.remotePeerSdpConstraints&&config.remoteSdp.remotePeerSdpConstraints.OfferToReceiveAudio}));var streamsToShare={};peer.getLocalStreams().forEach(function(stream){streamsToShare[stream.streamid]={isAudio:!!stream.isAudio,isVideo:!!stream.isVideo,isScreen:!!stream.isScreen}}),isOfferer&&createOfferOrAnswer("createOffer"),peer.nativeClose=peer.close,peer.close=function(){if(peer){try{peer.nativeClose!==peer.close&&peer.nativeClose()}catch(e){}peer=null,self.peer=null}},this.peer=peer}function setStreamType(constraints,stream){constraints.mandatory&&constraints.mandatory.chromeMediaSource?stream.isScreen=!0:constraints.mozMediaSource||constraints.mediaSource?stream.isScreen=!0:constraints.video?stream.isVideo=!0:constraints.audio&&(stream.isAudio=!0)}function getUserMediaHandler(options){function streaming(stream,returnBack){setStreamType(options.localMediaConstraints,stream);var streamEndedEvent="ended";"oninactive"in stream&&(streamEndedEvent="inactive"),stream.addEventListener(streamEndedEvent,function(){delete currentUserMediaRequest.streams[idInstance],currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.indexOf(options)&&(delete currentUserMediaRequest.queueRequests[currentUserMediaRequest.queueRequests.indexOf(options)],currentUserMediaRequest.queueRequests=removeNullEntries(currentUserMediaRequest.queueRequests))},!1),currentUserMediaRequest.streams[idInstance]={stream:stream},currentUserMediaRequest.mutex=!1,currentUserMediaRequest.queueRequests.length&&getUserMediaHandler(currentUserMediaRequest.queueRequests.shift()),options.onGettingLocalMedia(stream,returnBack)}if(currentUserMediaRequest.mutex===!0)return void currentUserMediaRequest.queueRequests.push(options);currentUserMediaRequest.mutex=!0;var idInstance=JSON.stringify(options.localMediaConstraints);if(currentUserMediaRequest.streams[idInstance])streaming(currentUserMediaRequest.streams[idInstance].stream,!0);else{var isBlackBerry=!!/BB10|BlackBerry/i.test(navigator.userAgent||"");if(isBlackBerry||"undefined"==typeof navigator.mediaDevices||"function"!=typeof navigator.mediaDevices.getUserMedia)return navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia,void navigator.getUserMedia(options.localMediaConstraints,function(stream){stream.streamid=stream.streamid||stream.id||getRandomString(),stream.idInstance=idInstance,streaming(stream)},function(error){options.onLocalMediaError(error,options.localMediaConstraints)});if("undefined"==typeof navigator.mediaDevices){navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia;var getUserMediaStream,getUserMediaError,getUserMediaSuccess=function(){},getUserMediaFailure=function(){};navigator.mediaDevices={getUserMedia:function(hints){return navigator.getUserMedia(hints,function(getUserMediaSuccess){getUserMediaSuccess(stream),getUserMediaStream=stream},function(error){getUserMediaFailure(error),getUserMediaError=error}),{then:function(successCB){return getUserMediaStream?void successCB(getUserMediaStream):(getUserMediaSuccess=successCB,{then:function(failureCB){return getUserMediaError?void failureCB(getUserMediaError):void(getUserMediaFailure=failureCB)}})}}}}}navigator.mediaDevices.getUserMedia(options.localMediaConstraints).then(function(stream){stream.streamid=stream.streamid||stream.id||getRandomString(),stream.idInstance=idInstance,streaming(stream)})["catch"](function(error){options.onLocalMediaError(error,options.localMediaConstraints)})}}function onMessageCallback(data){if("PermissionDeniedError"==data){if(chromeMediaSource="PermissionDeniedError",screenCallback)return screenCallback("PermissionDeniedError");throw new Error("PermissionDeniedError")}"rtcmulticonnection-extension-loaded"==data&&(chromeMediaSource="desktop"),data.sourceId&&screenCallback&&screenCallback(sourceId=data.sourceId,data.canRequestAudioTrack===!0)}function isChromeExtensionAvailable(callback){if(callback){if("desktop"==chromeMediaSource)return callback(!0);window.postMessage("are-you-there","*"),setTimeout(function(){callback("screen"==chromeMediaSource?!1:!0)},2e3)}}function getSourceId(callback){if(!callback)throw'"callback" parameter is mandatory.';return sourceId?callback(sourceId):(screenCallback=callback,void window.postMessage("get-sourceId","*"))}function getSourceIdWithAudio(callback){if(!callback)throw'"callback" parameter is mandatory.';return sourceId?callback(sourceId):(screenCallback=callback,void window.postMessage("audio-plus-tab","*"))}function getChromeExtensionStatus(extensionid,callback){if(isFirefox)return callback("not-chrome");2!=arguments.length&&(callback=extensionid,extensionid="ajhifddimkapgcifgcodmmfdlknahffk");var image=document.createElement("img");image.src="chrome-extension://"+extensionid+"/icon.png",image.onload=function(){chromeMediaSource="screen",window.postMessage("are-you-there","*"),setTimeout(function(){callback("screen"==chromeMediaSource?"installed-disabled":"installed-enabled")},2e3)},image.onerror=function(){callback("not-installed")}}function getScreenConstraints(callback,captureSourceIdWithAudio){var firefoxScreenConstraints={mozMediaSource:"window",mediaSource:"window"};if(isFirefox)return callback(null,firefoxScreenConstraints);var screen_constraints={mandatory:{chromeMediaSource:chromeMediaSource,maxWidth:screen.width>1920?screen.width:1920,maxHeight:screen.height>1080?screen.height:1080},optional:[]};return"desktop"!=chromeMediaSource||sourceId?("desktop"==chromeMediaSource&&(screen_constraints.mandatory.chromeMediaSourceId=sourceId),void callback(null,screen_constraints)):void(captureSourceIdWithAudio?getSourceIdWithAudio(function(sourceId,canRequestAudioTrack){screen_constraints.mandatory.chromeMediaSourceId=sourceId,canRequestAudioTrack&&(screen_constraints.canRequestAudioTrack=!0),callback("PermissionDeniedError"==sourceId?sourceId:null,screen_constraints)}):getSourceId(function(sourceId){screen_constraints.mandatory.chromeMediaSourceId=sourceId,callback("PermissionDeniedError"==sourceId?sourceId:null,screen_constraints)}))}function TextReceiver(connection){function receive(data,userid,extra){var uuid=data.uuid;if(content[uuid]||(content[uuid]=[]),content[uuid].push(data.message),data.last){var message=content[uuid].join("");data.isobject&&(message=JSON.parse(message));var receivingTime=(new Date).getTime(),latency=receivingTime-data.sendingTime,e={data:message,userid:userid,extra:extra,latency:latency};connection.autoTranslateText?(e.original=e.data,connection.Translator.TranslateText(e.data,function(translatedText){e.data=translatedText,connection.onmessage(e)})):connection.onmessage(e),delete content[uuid]}}var content={};return{receive:receive}}var browserFakeUserAgent="Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45";!function(that){that&&"undefined"==typeof window&&"undefined"!=typeof global&&(global.navigator={userAgent:browserFakeUserAgent,getUserMedia:function(){}},global.console||(global.console={}),"undefined"==typeof global.console.debug&&(global.console.debug=global.console.info=global.console.error=global.console.log=global.console.log||function(){console.log(arguments)}),"undefined"==typeof document&&(that.document={},document.createElement=document.captureStream=document.mozCaptureStream=function(){var obj={getContext:function(){return obj},play:function(){},pause:function(){},drawImage:function(){},toDataURL:function(){return""}};return obj},document.addEventListener=document.removeEventListener=that.addEventListener=that.removeEventListener=function(){},that.HTMLVideoElement=that.HTMLMediaElement=function(){}),"undefined"==typeof io&&(that.io=function(){return{on:function(eventName,callback){callback=callback||function(){},"connect"===eventName&&callback()},emit:function(eventName,data,callback){callback=callback||function(){},"open-room"!==eventName&&"join-room"!==eventName||callback(!0,data.sessionid,null)}}}),"undefined"==typeof location&&(that.location={protocol:"file:",href:"",hash:"",origin:"self"}),"undefined"==typeof screen&&(that.screen={width:0,height:0}),"undefined"==typeof URL&&(that.URL={createObjectURL:function(){return""},revokeObjectURL:function(){return""}}),that.window=global)}("undefined"!=typeof global?global:null),function(){function getBrowserInfo(){var nameOffset,verOffset,ix,nAgt=(navigator.appVersion,navigator.userAgent),browserName=navigator.appName,fullVersion=""+parseFloat(navigator.appVersion),majorVersion=parseInt(navigator.appVersion,10);if(isSafari&&!isChrome&&nAgt.indexOf("CriOS")!==-1&&(isSafari=!1,isChrome=!0),isOpera){browserName="Opera";try{fullVersion=navigator.userAgent.split("OPR/")[1].split(" ")[0],majorVersion=fullVersion.split(".")[0]}catch(e){fullVersion="0.0.0.0",majorVersion=0}}else isIE?(verOffset=nAgt.indexOf("rv:"),verOffset>0?fullVersion=nAgt.substring(verOffset+3):(verOffset=nAgt.indexOf("MSIE"),fullVersion=nAgt.substring(verOffset+5)),browserName="IE"):isChrome?(verOffset=nAgt.indexOf("Chrome"),browserName="Chrome",fullVersion=nAgt.substring(verOffset+7)):isSafari?(verOffset=nAgt.indexOf("Safari"),browserName="Safari",fullVersion=nAgt.substring(verOffset+7),(verOffset=nAgt.indexOf("Version"))!==-1&&(fullVersion=nAgt.substring(verOffset+8)),navigator.userAgent.indexOf("Version/")!==-1&&(fullVersion=navigator.userAgent.split("Version/")[1].split(" ")[0])):isFirefox?(verOffset=nAgt.indexOf("Firefox"),browserName="Firefox",fullVersion=nAgt.substring(verOffset+8)):(nameOffset=nAgt.lastIndexOf(" ")+1)<(verOffset=nAgt.lastIndexOf("/"))&&(browserName=nAgt.substring(nameOffset,verOffset),fullVersion=nAgt.substring(verOffset+1),browserName.toLowerCase()===browserName.toUpperCase()&&(browserName=navigator.appName));return isEdge&&(browserName="Edge",fullVersion=navigator.userAgent.split("Edge/")[1]),(ix=fullVersion.search(/[; \)]/))!==-1&&(fullVersion=fullVersion.substring(0,ix)),majorVersion=parseInt(""+fullVersion,10),isNaN(majorVersion)&&(fullVersion=""+parseFloat(navigator.appVersion),majorVersion=parseInt(navigator.appVersion,10)),{fullVersion:fullVersion,version:majorVersion,name:browserName,isPrivateBrowsing:!1}}function retry(isDone,next){var currentTrial=0,maxRetry=50,isTimeout=!1,id=window.setInterval(function(){isDone()&&(window.clearInterval(id),next(isTimeout)),currentTrial++>maxRetry&&(window.clearInterval(id),isTimeout=!0,next(isTimeout))},10)}function isIE10OrLater(userAgent){var ua=userAgent.toLowerCase();if(0===ua.indexOf("msie")&&0===ua.indexOf("trident"))return!1;var match=/(?:msie|rv:)\s?([\d\.]+)/.exec(ua);return!!(match&&parseInt(match[1],10)>=10)}function detectPrivateMode(callback){var isPrivate;try{if(window.webkitRequestFileSystem)window.webkitRequestFileSystem(window.TEMPORARY,1,function(){isPrivate=!1},function(e){isPrivate=!0});else if(window.indexedDB&&/Firefox/.test(window.navigator.userAgent)){var db;try{db=window.indexedDB.open("test"),db.onerror=function(){return!0}}catch(e){isPrivate=!0}"undefined"==typeof isPrivate&&retry(function(){return"done"===db.readyState},function(isTimeout){isTimeout||(isPrivate=!db.result)})}else if(isIE10OrLater(window.navigator.userAgent)){isPrivate=!1;try{window.indexedDB||(isPrivate=!0)}catch(e){isPrivate=!0}}else if(window.localStorage&&/Safari/.test(window.navigator.userAgent)){try{window.localStorage.setItem("test",1)}catch(e){isPrivate=!0}"undefined"==typeof isPrivate&&(isPrivate=!1,window.localStorage.removeItem("test"))}}catch(e){isPrivate=!1}retry(function(){return"undefined"!=typeof isPrivate},function(isTimeout){callback(isPrivate)})}function detectDesktopOS(){for(var cs,unknown="-",nVer=navigator.appVersion,nAgt=navigator.userAgent,os=unknown,clientStrings=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Linux",r:/(Linux|X11)/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}],i=0;cs=clientStrings[i];i++)if(cs.r.test(nAgt)){os=cs.s;break}var osVersion=unknown;switch(/Windows/.test(os)&&(/Windows (.*)/.test(os)&&(osVersion=/Windows (.*)/.exec(os)[1]),os="Windows"),os){case"Mac OS X":/Mac OS X (10[\.\_\d]+)/.test(nAgt)&&(osVersion=/Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1]);break;case"Android":/Android ([\.\_\d]+)/.test(nAgt)&&(osVersion=/Android ([\.\_\d]+)/.exec(nAgt)[1]);break;case"iOS":/OS (\d+)_(\d+)_?(\d+)?/.test(nAgt)&&(osVersion=/OS (\d+)_(\d+)_?(\d+)?/.exec(nVer),osVersion=osVersion[1]+"."+osVersion[2]+"."+(0|osVersion[3]))}return{osName:os,osVersion:osVersion}}function getAndroidVersion(ua){ua=(ua||navigator.userAgent).toLowerCase();var match=ua.match(/android\s([0-9\.]*)/);return!!match&&match[1]}function DetectLocalIPAddress(callback,stream){if(DetectRTC.isWebRTCSupported){var isPublic=!0,isIpv4=!0;getIPs(function(ip){ip.match(regexIpv4Local)?(isPublic=!1,callback("Local: "+ip,isPublic,isIpv4)):ip.match(regexIpv6)?(isIpv4=!1,callback("Public: "+ip,isPublic,isIpv4)):callback("Public: "+ip,isPublic,isIpv4)},stream)}}function getIPs(callback,stream){function handleCandidate(candidate){var match=regexIpv4.exec(candidate);if(match){var ipAddress=match[1];const isPublic=candidate.match(regexIpv4Local),isIpv4=!0;void 0===ipDuplicates[ipAddress]&&callback(ipAddress,isPublic,isIpv4),ipDuplicates[ipAddress]=!0}}function afterCreateOffer(){var lines=pc.localDescription.sdp.split("\n");lines.forEach(function(line){0===line.indexOf("a=candidate:")&&handleCandidate(line)})}if("undefined"!=typeof document&&"function"==typeof document.getElementById){var ipDuplicates={},RTCPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection;if(!RTCPeerConnection){var iframe=document.getElementById("iframe");if(!iframe)return;var win=iframe.contentWindow;RTCPeerConnection=win.RTCPeerConnection||win.mozRTCPeerConnection||win.webkitRTCPeerConnection}if(RTCPeerConnection){var peerConfig=null;"Chrome"===DetectRTC.browser&&DetectRTC.browser.version<58&&(peerConfig={optional:[{RtpDataChannels:!0}]});var servers={iceServers:[{urls:"stun:stun.l.google.com:19302"}]},pc=new RTCPeerConnection(servers,peerConfig);if(stream&&(pc.addStream?pc.addStream(stream):pc.addTrack&&stream.getTracks()[0]&&pc.addTrack(stream.getTracks()[0],stream)),pc.onicecandidate=function(ice){ice.candidate&&handleCandidate(ice.candidate.candidate)},!stream)try{pc.createDataChannel("sctp",{})}catch(e){}DetectRTC.isPromisesSupported?pc.createOffer().then(function(result){pc.setLocalDescription(result).then(afterCreateOffer)}):pc.createOffer(function(result){pc.setLocalDescription(result,afterCreateOffer,function(){})},function(){})}}}function checkDeviceSupport(callback){if(!canEnumerate)return void(callback&&callback());if(!navigator.enumerateDevices&&window.MediaStreamTrack&&window.MediaStreamTrack.getSources&&(navigator.enumerateDevices=window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack)),!navigator.enumerateDevices&&navigator.enumerateDevices&&(navigator.enumerateDevices=navigator.enumerateDevices.bind(navigator)),!navigator.enumerateDevices)return void(callback&&callback());MediaDevices=[],audioInputDevices=[],audioOutputDevices=[],videoInputDevices=[],hasMicrophone=!1,hasSpeakers=!1,hasWebcam=!1,isWebsiteHasMicrophonePermissions=!1,isWebsiteHasWebcamPermissions=!1;var alreadyUsedDevices={};navigator.enumerateDevices(function(devices){devices.forEach(function(_device){var device={};for(var d in _device)try{"function"!=typeof _device[d]&&(device[d]=_device[d])}catch(e){}alreadyUsedDevices[device.deviceId+device.label+device.kind]||("audio"===device.kind&&(device.kind="audioinput"),"video"===device.kind&&(device.kind="videoinput"),device.deviceId||(device.deviceId=device.id),device.id||(device.id=device.deviceId),device.label?("videoinput"!==device.kind||isWebsiteHasWebcamPermissions||(isWebsiteHasWebcamPermissions=!0),"audioinput"!==device.kind||isWebsiteHasMicrophonePermissions||(isWebsiteHasMicrophonePermissions=!0)):(device.isCustomLabel=!0,"videoinput"===device.kind?device.label="Camera "+(videoInputDevices.length+1):"audioinput"===device.kind?device.label="Microphone "+(audioInputDevices.length+1):"audiooutput"===device.kind?device.label="Speaker "+(audioOutputDevices.length+1):device.label="Please invoke getUserMedia once.","undefined"!=typeof DetectRTC&&DetectRTC.browser.isChrome&&DetectRTC.browser.version>=46&&!/^(https:|chrome-extension:)$/g.test(location.protocol||"")&&"undefined"!=typeof document&&"string"==typeof document.domain&&document.domain.search&&document.domain.search(/localhost|127.0./g)===-1&&(device.label="HTTPs is required to get label of this "+device.kind+" device.")),"audioinput"===device.kind&&(hasMicrophone=!0,audioInputDevices.indexOf(device)===-1&&audioInputDevices.push(device)),"audiooutput"===device.kind&&(hasSpeakers=!0,audioOutputDevices.indexOf(device)===-1&&audioOutputDevices.push(device)),"videoinput"===device.kind&&(hasWebcam=!0,videoInputDevices.indexOf(device)===-1&&videoInputDevices.push(device)),MediaDevices.push(device),alreadyUsedDevices[device.deviceId+device.label+device.kind]=device)}),"undefined"!=typeof DetectRTC&&(DetectRTC.MediaDevices=MediaDevices,DetectRTC.hasMicrophone=hasMicrophone,DetectRTC.hasSpeakers=hasSpeakers,DetectRTC.hasWebcam=hasWebcam,DetectRTC.isWebsiteHasWebcamPermissions=isWebsiteHasWebcamPermissions,DetectRTC.isWebsiteHasMicrophonePermissions=isWebsiteHasMicrophonePermissions,DetectRTC.audioInputDevices=audioInputDevices,DetectRTC.audioOutputDevices=audioOutputDevices,DetectRTC.videoInputDevices=videoInputDevices),callback&&callback()})}function getAspectRatio(w,h){function gcd(a,b){return 0==b?a:gcd(b,a%b)}var r=gcd(w,h);return w/r/(h/r)}var browserFakeUserAgent="Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45",isNodejs="object"==typeof process&&"object"==typeof process.versions&&process.versions.node&&!process.browser;if(isNodejs){var version=process.versions.node.toString().replace("v","");browserFakeUserAgent="Nodejs/"+version+" (NodeOS) AppleWebKit/"+version+" (KHTML, like Gecko) Nodejs/"+version+" Nodejs/"+version}!function(that){"undefined"==typeof window&&("undefined"==typeof window&&"undefined"!=typeof global?(global.navigator={userAgent:browserFakeUserAgent,getUserMedia:function(){}},that.window=global):"undefined"==typeof window,"undefined"==typeof location&&(that.location={protocol:"file:",href:"",hash:""}),"undefined"==typeof screen&&(that.screen={width:0,height:0}))}("undefined"!=typeof global?global:window);var navigator=window.navigator;"undefined"!=typeof navigator?("undefined"!=typeof navigator.webkitGetUserMedia&&(navigator.getUserMedia=navigator.webkitGetUserMedia),"undefined"!=typeof navigator.mozGetUserMedia&&(navigator.getUserMedia=navigator.mozGetUserMedia)):navigator={getUserMedia:function(){},userAgent:browserFakeUserAgent};var isMobileDevice=!!/Android|webOS|iPhone|iPad|iPod|BB10|BlackBerry|IEMobile|Opera Mini|Mobile|mobile/i.test(navigator.userAgent||""),isEdge=!(navigator.userAgent.indexOf("Edge")===-1||!navigator.msSaveOrOpenBlob&&!navigator.msSaveBlob),isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,isFirefox="undefined"!=typeof window.InstallTrigger,isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),isChrome=!!window.chrome&&!isOpera,isIE="undefined"!=typeof document&&!!document.documentMode&&!isEdge,isMobile={Android:function(){return navigator.userAgent.match(/Android/i)},BlackBerry:function(){return navigator.userAgent.match(/BlackBerry|BB10/i)},iOS:function(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)},Opera:function(){return navigator.userAgent.match(/Opera Mini/i)},Windows:function(){return navigator.userAgent.match(/IEMobile/i)},any:function(){return isMobile.Android()||isMobile.BlackBerry()||isMobile.iOS()||isMobile.Opera()||isMobile.Windows()},getOsName:function(){var osName="Unknown OS";return isMobile.Android()&&(osName="Android"),isMobile.BlackBerry()&&(osName="BlackBerry"),isMobile.iOS()&&(osName="iOS"),isMobile.Opera()&&(osName="Opera Mini"),isMobile.Windows()&&(osName="Windows"),osName}},osName="Unknown OS",osVersion="Unknown OS Version",osInfo=detectDesktopOS();osInfo&&osInfo.osName&&"-"!=osInfo.osName?(osName=osInfo.osName,osVersion=osInfo.osVersion):isMobile.any()&&(osName=isMobile.getOsName(),"Android"==osName&&(osVersion=getAndroidVersion()));var isNodejs="object"==typeof process&&"object"==typeof process.versions&&process.versions.node;"Unknown OS"===osName&&isNodejs&&(osName="Nodejs",osVersion=process.versions.node.toString().replace("v",""));var isCanvasSupportsStreamCapturing=!1,isVideoSupportsStreamCapturing=!1;["captureStream","mozCaptureStream","webkitCaptureStream"].forEach(function(item){"undefined"!=typeof document&&"function"==typeof document.createElement&&(!isCanvasSupportsStreamCapturing&&item in document.createElement("canvas")&&(isCanvasSupportsStreamCapturing=!0),!isVideoSupportsStreamCapturing&&item in document.createElement("video")&&(isVideoSupportsStreamCapturing=!0))});const regexIpv4Local=/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/,regexIpv4=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,regexIpv6=/[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}/;var MediaDevices=[],audioInputDevices=[],audioOutputDevices=[],videoInputDevices=[];navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&(navigator.enumerateDevices=function(callback){var enumerateDevices=navigator.mediaDevices.enumerateDevices();enumerateDevices&&enumerateDevices.then?navigator.mediaDevices.enumerateDevices().then(callback)["catch"](function(){callback([])}):callback([])});var canEnumerate=!1;"undefined"!=typeof MediaStreamTrack&&"getSources"in MediaStreamTrack?canEnumerate=!0:navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&(canEnumerate=!0);var hasMicrophone=!1,hasSpeakers=!1,hasWebcam=!1,isWebsiteHasMicrophonePermissions=!1,isWebsiteHasWebcamPermissions=!1,DetectRTC=window.DetectRTC||{};DetectRTC.browser=getBrowserInfo(),detectPrivateMode(function(isPrivateBrowsing){DetectRTC.browser.isPrivateBrowsing=!!isPrivateBrowsing}),DetectRTC.browser["is"+DetectRTC.browser.name]=!0,DetectRTC.osName=osName,DetectRTC.osVersion=osVersion;var isWebRTCSupported=("object"==typeof process&&"object"==typeof process.versions&&process.versions["node-webkit"],!1);["RTCPeerConnection","webkitRTCPeerConnection","mozRTCPeerConnection","RTCIceGatherer"].forEach(function(item){isWebRTCSupported||item in window&&(isWebRTCSupported=!0)}),DetectRTC.isWebRTCSupported=isWebRTCSupported,DetectRTC.isORTCSupported="undefined"!=typeof RTCIceGatherer;var isScreenCapturingSupported=!1;if(DetectRTC.browser.isChrome&&DetectRTC.browser.version>=35?isScreenCapturingSupported=!0:DetectRTC.browser.isFirefox&&DetectRTC.browser.version>=34?isScreenCapturingSupported=!0:DetectRTC.browser.isEdge&&DetectRTC.browser.version>=17?isScreenCapturingSupported=!0:"Android"===DetectRTC.osName&&DetectRTC.browser.isChrome&&(isScreenCapturingSupported=!0),!/^(https:|chrome-extension:)$/g.test(location.protocol||"")){var isNonLocalHost="undefined"!=typeof document&&"string"==typeof document.domain&&document.domain.search&&document.domain.search(/localhost|127.0./g)===-1;isNonLocalHost&&(DetectRTC.browser.isChrome||DetectRTC.browser.isEdge||DetectRTC.browser.isOpera)?isScreenCapturingSupported=!1:DetectRTC.browser.isFirefox&&(isScreenCapturingSupported=!1)}DetectRTC.isScreenCapturingSupported=isScreenCapturingSupported;var webAudio={isSupported:!1,isCreateMediaStreamSourceSupported:!1};["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"].forEach(function(item){webAudio.isSupported||item in window&&(webAudio.isSupported=!0,window[item]&&"createMediaStreamSource"in window[item].prototype&&(webAudio.isCreateMediaStreamSourceSupported=!0))}),DetectRTC.isAudioContextSupported=webAudio.isSupported,DetectRTC.isCreateMediaStreamSourceSupported=webAudio.isCreateMediaStreamSourceSupported;var isRtpDataChannelsSupported=!1;DetectRTC.browser.isChrome&&DetectRTC.browser.version>31&&(isRtpDataChannelsSupported=!0),DetectRTC.isRtpDataChannelsSupported=isRtpDataChannelsSupported;var isSCTPSupportd=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>28?isSCTPSupportd=!0:DetectRTC.browser.isChrome&&DetectRTC.browser.version>25?isSCTPSupportd=!0:DetectRTC.browser.isOpera&&DetectRTC.browser.version>=11&&(isSCTPSupportd=!0),DetectRTC.isSctpDataChannelsSupported=isSCTPSupportd,DetectRTC.isMobileDevice=isMobileDevice;var isGetUserMediaSupported=!1;navigator.getUserMedia?isGetUserMediaSupported=!0:navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(isGetUserMediaSupported=!0),DetectRTC.browser.isChrome&&DetectRTC.browser.version>=46&&!/^(https:|chrome-extension:)$/g.test(location.protocol||"")&&"undefined"!=typeof document&&"string"==typeof document.domain&&document.domain.search&&document.domain.search(/localhost|127.0./g)===-1&&(isGetUserMediaSupported="Requires HTTPs"),"Nodejs"===DetectRTC.osName&&(isGetUserMediaSupported=!1),DetectRTC.isGetUserMediaSupported=isGetUserMediaSupported;var displayResolution="";if(screen.width){var width=screen.width?screen.width:"",height=screen.height?screen.height:"";displayResolution+=""+width+" x "+height}DetectRTC.displayResolution=displayResolution,DetectRTC.displayAspectRatio=getAspectRatio(screen.width,screen.height).toFixed(2),DetectRTC.isCanvasSupportsStreamCapturing=isCanvasSupportsStreamCapturing,DetectRTC.isVideoSupportsStreamCapturing=isVideoSupportsStreamCapturing,"Chrome"==DetectRTC.browser.name&&DetectRTC.browser.version>=53&&(DetectRTC.isCanvasSupportsStreamCapturing||(DetectRTC.isCanvasSupportsStreamCapturing="Requires chrome flag: enable-experimental-web-platform-features"),DetectRTC.isVideoSupportsStreamCapturing||(DetectRTC.isVideoSupportsStreamCapturing="Requires chrome flag: enable-experimental-web-platform-features")),DetectRTC.DetectLocalIPAddress=DetectLocalIPAddress,DetectRTC.isWebSocketsSupported="WebSocket"in window&&2===window.WebSocket.CLOSING,DetectRTC.isWebSocketsBlocked=!DetectRTC.isWebSocketsSupported,"Nodejs"===DetectRTC.osName&&(DetectRTC.isWebSocketsSupported=!0,DetectRTC.isWebSocketsBlocked=!1),DetectRTC.checkWebSocketsSupport=function(callback){callback=callback||function(){};try{var starttime,websocket=new WebSocket("wss://echo.websocket.org:443/");websocket.onopen=function(){DetectRTC.isWebSocketsBlocked=!1,starttime=(new Date).getTime(),websocket.send("ping")},websocket.onmessage=function(){DetectRTC.WebsocketLatency=(new Date).getTime()-starttime+"ms",callback(),websocket.close(),websocket=null},websocket.onerror=function(){DetectRTC.isWebSocketsBlocked=!0,callback()}}catch(e){DetectRTC.isWebSocketsBlocked=!0,callback()}},DetectRTC.load=function(callback){callback=callback||function(){},checkDeviceSupport(callback)},"undefined"!=typeof MediaDevices?DetectRTC.MediaDevices=MediaDevices:DetectRTC.MediaDevices=[],DetectRTC.hasMicrophone=hasMicrophone,DetectRTC.hasSpeakers=hasSpeakers,DetectRTC.hasWebcam=hasWebcam,DetectRTC.isWebsiteHasWebcamPermissions=isWebsiteHasWebcamPermissions,DetectRTC.isWebsiteHasMicrophonePermissions=isWebsiteHasMicrophonePermissions,DetectRTC.audioInputDevices=audioInputDevices,DetectRTC.audioOutputDevices=audioOutputDevices,DetectRTC.videoInputDevices=videoInputDevices;var isSetSinkIdSupported=!1;"undefined"!=typeof document&&"function"==typeof document.createElement&&"setSinkId"in document.createElement("video")&&(isSetSinkIdSupported=!0),
|
|
DetectRTC.isSetSinkIdSupported=isSetSinkIdSupported;var isRTPSenderReplaceTracksSupported=!1;DetectRTC.browser.isFirefox&&"undefined"!=typeof mozRTCPeerConnection?"getSenders"in mozRTCPeerConnection.prototype&&(isRTPSenderReplaceTracksSupported=!0):DetectRTC.browser.isChrome&&"undefined"!=typeof webkitRTCPeerConnection&&"getSenders"in webkitRTCPeerConnection.prototype&&(isRTPSenderReplaceTracksSupported=!0),DetectRTC.isRTPSenderReplaceTracksSupported=isRTPSenderReplaceTracksSupported;var isRemoteStreamProcessingSupported=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>38&&(isRemoteStreamProcessingSupported=!0),DetectRTC.isRemoteStreamProcessingSupported=isRemoteStreamProcessingSupported;var isApplyConstraintsSupported=!1;"undefined"!=typeof MediaStreamTrack&&"applyConstraints"in MediaStreamTrack.prototype&&(isApplyConstraintsSupported=!0),DetectRTC.isApplyConstraintsSupported=isApplyConstraintsSupported;var isMultiMonitorScreenCapturingSupported=!1;DetectRTC.browser.isFirefox&&DetectRTC.browser.version>=43&&(isMultiMonitorScreenCapturingSupported=!0),DetectRTC.isMultiMonitorScreenCapturingSupported=isMultiMonitorScreenCapturingSupported,DetectRTC.isPromisesSupported=!!("Promise"in window),DetectRTC.version="1.3.7","undefined"==typeof DetectRTC&&(window.DetectRTC={});var MediaStream=window.MediaStream;"undefined"==typeof MediaStream&&"undefined"!=typeof webkitMediaStream&&(MediaStream=webkitMediaStream),"undefined"!=typeof MediaStream&&"function"==typeof MediaStream?DetectRTC.MediaStream=Object.keys(MediaStream.prototype):DetectRTC.MediaStream=!1,"undefined"!=typeof MediaStreamTrack?DetectRTC.MediaStreamTrack=Object.keys(MediaStreamTrack.prototype):DetectRTC.MediaStreamTrack=!1;var RTCPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection;"undefined"!=typeof RTCPeerConnection?DetectRTC.RTCPeerConnection=Object.keys(RTCPeerConnection.prototype):DetectRTC.RTCPeerConnection=!1,window.DetectRTC=DetectRTC,"undefined"!=typeof module&&(module.exports=DetectRTC),"function"==typeof define&&define.amd&&define("DetectRTC",[],function(){return DetectRTC})}(),"undefined"!=typeof cordova&&(DetectRTC.isMobileDevice=!0,DetectRTC.browser.name="Chrome"),navigator&&navigator.userAgent&&navigator.userAgent.indexOf("Crosswalk")!==-1&&(DetectRTC.isMobileDevice=!0,DetectRTC.browser.name="Chrome"),window.addEventListener||(window.addEventListener=function(el,eventName,eventHandler){el.attachEvent&&el.attachEvent("on"+eventName,eventHandler)}),window.attachEventListener=function(video,type,listener,useCapture){video.addEventListener(type,listener,useCapture)};var MediaStream=window.MediaStream;"undefined"==typeof MediaStream&&"undefined"!=typeof webkitMediaStream&&(MediaStream=webkitMediaStream),"undefined"!=typeof MediaStream&&("stop"in MediaStream.prototype||(MediaStream.prototype.stop=function(){this.getTracks().forEach(function(track){track.stop()})})),window.iOSDefaultAudioOutputDevice=window.iOSDefaultAudioOutputDevice||"speaker","undefined"==typeof window.enableAdapter&&("Firefox"===DetectRTC.browser.name&&DetectRTC.browser.version>=54&&(window.enableAdapter=!0),"Chrome"===DetectRTC.browser.name&&DetectRTC.browser.version>=60,"undefined"!=typeof adapter&&adapter.browserDetails&&"string"==typeof adapter.browserDetails.browser&&(window.enableAdapter=!0)),window.enableAdapter||("undefined"==typeof URL.createObjectURL&&(URL.createObjectURL=function(stream){return"blob:https://"+document.domain+"/"+getRandomString()}),"srcObject"in HTMLMediaElement.prototype||(HTMLMediaElement.prototype.srcObject=function(stream){return"mozSrcObject"in this?void(this.mozSrcObject=stream):void(this.src=URL.createObjectURL(stream))})),document.addEventListener("deviceready",setCordovaAPIs,!1),setCordovaAPIs();var RTCPeerConnection,defaults={};"undefined"!=typeof window.RTCPeerConnection?RTCPeerConnection=window.RTCPeerConnection:"undefined"!=typeof mozRTCPeerConnection?RTCPeerConnection=mozRTCPeerConnection:"undefined"!=typeof webkitRTCPeerConnection&&(RTCPeerConnection=webkitRTCPeerConnection);var RTCSessionDescription=window.RTCSessionDescription||window.mozRTCSessionDescription,RTCIceCandidate=window.RTCIceCandidate||window.mozRTCIceCandidate,MediaStreamTrack=window.MediaStreamTrack,CodecsHandler=function(){function preferCodec(sdp,codecName){var info=splitLines(sdp);return info.videoCodecNumbers?"vp8"===codecName&&info.vp8LineNumber===info.videoCodecNumbers[0]?sdp:"vp9"===codecName&&info.vp9LineNumber===info.videoCodecNumbers[0]?sdp:"h264"===codecName&&info.h264LineNumber===info.videoCodecNumbers[0]?sdp:sdp=preferCodecHelper(sdp,codecName,info):sdp}function preferCodecHelper(sdp,codec,info,ignore){var preferCodecNumber="";if("vp8"===codec){if(!info.vp8LineNumber)return sdp;preferCodecNumber=info.vp8LineNumber}if("vp9"===codec){if(!info.vp9LineNumber)return sdp;preferCodecNumber=info.vp9LineNumber}if("h264"===codec){if(!info.h264LineNumber)return sdp;preferCodecNumber=info.h264LineNumber}var newLine=info.videoCodecNumbersOriginal.split("SAVPF")[0]+"SAVPF ",newOrder=[preferCodecNumber];return ignore&&(newOrder=[]),info.videoCodecNumbers.forEach(function(codecNumber){codecNumber!==preferCodecNumber&&newOrder.push(codecNumber)}),newLine+=newOrder.join(" "),sdp=sdp.replace(info.videoCodecNumbersOriginal,newLine)}function splitLines(sdp){var info={};return sdp.split("\n").forEach(function(line){0===line.indexOf("m=video")&&(info.videoCodecNumbers=[],line.split("SAVPF")[1].split(" ").forEach(function(codecNumber){codecNumber=codecNumber.trim(),codecNumber&&codecNumber.length&&(info.videoCodecNumbers.push(codecNumber),info.videoCodecNumbersOriginal=line)})),line.indexOf("VP8/90000")===-1||info.vp8LineNumber||(info.vp8LineNumber=line.replace("a=rtpmap:","").split(" ")[0]),line.indexOf("VP9/90000")===-1||info.vp9LineNumber||(info.vp9LineNumber=line.replace("a=rtpmap:","").split(" ")[0]),line.indexOf("H264/90000")===-1||info.h264LineNumber||(info.h264LineNumber=line.replace("a=rtpmap:","").split(" ")[0])}),info}function removeVPX(sdp){var info=splitLines(sdp);return sdp=preferCodecHelper(sdp,"vp9",info,!0),sdp=preferCodecHelper(sdp,"vp8",info,!0)}function disableNACK(sdp){if(!sdp||"string"!=typeof sdp)throw"Invalid arguments.";return sdp=sdp.replace("a=rtcp-fb:126 nack\r\n",""),sdp=sdp.replace("a=rtcp-fb:126 nack pli\r\n","a=rtcp-fb:126 pli\r\n"),sdp=sdp.replace("a=rtcp-fb:97 nack\r\n",""),sdp=sdp.replace("a=rtcp-fb:97 nack pli\r\n","a=rtcp-fb:97 pli\r\n")}function prioritize(codecMimeType,peer){if(peer&&peer.getSenders&&peer.getSenders().length){if(!codecMimeType||"string"!=typeof codecMimeType)throw"Invalid arguments.";peer.getSenders().forEach(function(sender){for(var params=sender.getParameters(),i=0;i<params.codecs.length;i++)if(params.codecs[i].mimeType==codecMimeType){params.codecs.unshift(params.codecs.splice(i,1));break}sender.setParameters(params)})}}function removeNonG722(sdp){return sdp.replace(/m=audio ([0-9]+) RTP\/SAVPF ([0-9 ]*)/g,"m=audio $1 RTP/SAVPF 9")}function setBAS(sdp,bandwidth,isScreen){return bandwidth?"undefined"!=typeof isFirefox&&isFirefox?sdp:(isScreen&&(bandwidth.screen?bandwidth.screen<300&&console.warn("It seems that you are using wrong bandwidth value for screen. Screen sharing is expected to fail."):console.warn("It seems that you are not using bandwidth for screen. Screen sharing is expected to fail.")),bandwidth.screen&&isScreen&&(sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,""),sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+bandwidth.screen+"\r\n")),(bandwidth.audio||bandwidth.video)&&(sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,"")),bandwidth.audio&&(sdp=sdp.replace(/a=mid:audio\r\n/g,"a=mid:audio\r\nb=AS:"+bandwidth.audio+"\r\n")),bandwidth.screen?sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+bandwidth.screen+"\r\n"):bandwidth.video&&(sdp=sdp.replace(/a=mid:video\r\n/g,"a=mid:video\r\nb=AS:"+bandwidth.video+"\r\n")),sdp):sdp}function findLine(sdpLines,prefix,substr){return findLineInRange(sdpLines,0,-1,prefix,substr)}function findLineInRange(sdpLines,startLine,endLine,prefix,substr){for(var realEndLine=endLine!==-1?endLine:sdpLines.length,i=startLine;i<realEndLine;++i)if(0===sdpLines[i].indexOf(prefix)&&(!substr||sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())!==-1))return i;return null}function getCodecPayloadType(sdpLine){var pattern=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),result=sdpLine.match(pattern);return result&&2===result.length?result[1]:null}function setVideoBitrates(sdp,params){params=params||{};var vp8Payload,xgoogle_min_bitrate=params.min,xgoogle_max_bitrate=params.max,sdpLines=sdp.split("\r\n"),vp8Index=findLine(sdpLines,"a=rtpmap","VP8/90000");if(vp8Index&&(vp8Payload=getCodecPayloadType(sdpLines[vp8Index])),!vp8Payload)return sdp;var rtxPayload,rtxIndex=findLine(sdpLines,"a=rtpmap","rtx/90000");if(rtxIndex&&(rtxPayload=getCodecPayloadType(sdpLines[rtxIndex])),!rtxIndex)return sdp;var rtxFmtpLineIndex=findLine(sdpLines,"a=fmtp:"+rtxPayload.toString());if(null!==rtxFmtpLineIndex){var appendrtxNext="\r\n";appendrtxNext+="a=fmtp:"+vp8Payload+" x-google-min-bitrate="+(xgoogle_min_bitrate||"228")+"; x-google-max-bitrate="+(xgoogle_max_bitrate||"228"),sdpLines[rtxFmtpLineIndex]=sdpLines[rtxFmtpLineIndex].concat(appendrtxNext),sdp=sdpLines.join("\r\n")}return sdp}function setOpusAttributes(sdp,params){params=params||{};var opusPayload,sdpLines=sdp.split("\r\n"),opusIndex=findLine(sdpLines,"a=rtpmap","opus/48000");if(opusIndex&&(opusPayload=getCodecPayloadType(sdpLines[opusIndex])),!opusPayload)return sdp;var opusFmtpLineIndex=findLine(sdpLines,"a=fmtp:"+opusPayload.toString());if(null===opusFmtpLineIndex)return sdp;var appendOpusNext="";return appendOpusNext+="; stereo="+("undefined"!=typeof params.stereo?params.stereo:"1"),appendOpusNext+="; sprop-stereo="+("undefined"!=typeof params["sprop-stereo"]?params["sprop-stereo"]:"1"),"undefined"!=typeof params.maxaveragebitrate&&(appendOpusNext+="; maxaveragebitrate="+(params.maxaveragebitrate||1048576)),"undefined"!=typeof params.maxplaybackrate&&(appendOpusNext+="; maxplaybackrate="+(params.maxplaybackrate||1048576)),"undefined"!=typeof params.cbr&&(appendOpusNext+="; cbr="+("undefined"!=typeof params.cbr?params.cbr:"1")),"undefined"!=typeof params.useinbandfec&&(appendOpusNext+="; useinbandfec="+params.useinbandfec),"undefined"!=typeof params.usedtx&&(appendOpusNext+="; usedtx="+params.usedtx),"undefined"!=typeof params.maxptime&&(appendOpusNext+="\r\na=maxptime:"+params.maxptime),sdpLines[opusFmtpLineIndex]=sdpLines[opusFmtpLineIndex].concat(appendOpusNext),sdp=sdpLines.join("\r\n")}function forceStereoAudio(sdp){for(var sdpLines=sdp.split("\r\n"),fmtpLineIndex=null,i=0;i<sdpLines.length;i++)if(sdpLines[i].search("opus/48000")!==-1){var opusPayload=extractSdp(sdpLines[i],/:(\d+) opus\/48000/i);break}for(var i=0;i<sdpLines.length;i++)if(sdpLines[i].search("a=fmtp")!==-1){var payload=extractSdp(sdpLines[i],/a=fmtp:(\d+)/);if(payload===opusPayload){fmtpLineIndex=i;break}}return null===fmtpLineIndex?sdp:(sdpLines[fmtpLineIndex]=sdpLines[fmtpLineIndex].concat("; stereo=1; sprop-stereo=1"),sdp=sdpLines.join("\r\n"))}return{removeVPX:removeVPX,disableNACK:disableNACK,prioritize:prioritize,removeNonG722:removeNonG722,setApplicationSpecificBandwidth:function(sdp,bandwidth,isScreen){return setBAS(sdp,bandwidth,isScreen)},setVideoBitrates:function(sdp,params){return setVideoBitrates(sdp,params)},setOpusAttributes:function(sdp,params){return setOpusAttributes(sdp,params)},preferVP9:function(sdp){return preferCodec(sdp,"vp9")},preferCodec:preferCodec,forceStereoAudio:forceStereoAudio}}();window.BandwidthHandler=CodecsHandler;var OnIceCandidateHandler=function(){function processCandidates(connection,icePair){var candidate=icePair.candidate,iceRestrictions=connection.candidates,stun=iceRestrictions.stun,turn=iceRestrictions.turn;if(isNull(iceRestrictions.reflexive)||(stun=iceRestrictions.reflexive),isNull(iceRestrictions.relay)||(turn=iceRestrictions.relay),(iceRestrictions.host||!candidate.match(/typ host/g))&&(turn||!candidate.match(/typ relay/g))&&(stun||!candidate.match(/typ srflx/g))){var protocol=connection.iceProtocols;if((protocol.udp||!candidate.match(/ udp /g))&&(protocol.tcp||!candidate.match(/ tcp /g)))return connection.enableLogs&&console.debug("Your candidate pairs:",candidate),{candidate:candidate,sdpMid:icePair.sdpMid,sdpMLineIndex:icePair.sdpMLineIndex}}}return{processCandidates:processCandidates}}(),IceServersHandler=function(){function getIceServers(connection){var iceServers=[{urls:["stun:webrtcweb.com:7788","stun:webrtcweb.com:7788?transport=udp"],username:"muazkh",credential:"muazkh"},{urls:["turn:webrtcweb.com:7788","turn:webrtcweb.com:4455?transport=udp","turn:webrtcweb.com:8877?transport=udp","turn:webrtcweb.com:8877?transport=tcp"],username:"muazkh",credential:"muazkh"},{urls:["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302","stun:stun.l.google.com:19302?transport=udp"]}];return"undefined"!=typeof window.InstallTrigger&&(iceServers[0].urls=iceServers[0].urls.pop(),iceServers[1].urls=iceServers[1].urls.pop()),iceServers}return{getIceServers:getIceServers}}();window.currentUserMediaRequest={streams:[],mutex:!1,queueRequests:[],remove:function(idInstance){this.mutex=!1;var stream=this.streams[idInstance];if(stream){stream=stream.stream;var options=stream.currentUserMediaRequestOptions;this.queueRequests.indexOf(options)&&(delete this.queueRequests[this.queueRequests.indexOf(options)],this.queueRequests=removeNullEntries(this.queueRequests)),this.streams[idInstance].stream=null,delete this.streams[idInstance]}}};var StreamsHandler=function(){function handleType(type){if(type)return"string"==typeof type||"undefined"==typeof type?type:type.audio&&type.video?null:type.audio?"audio":type.video?"video":void 0}function setHandlers(stream,syncAction,connection){function graduallyIncreaseVolume(){if(connection.streamEvents[stream.streamid].mediaElement){var mediaElement=connection.streamEvents[stream.streamid].mediaElement;mediaElement.volume=0,afterEach(200,5,function(){try{mediaElement.volume+=.2}catch(e){mediaElement.volume=1}})}}if(stream&&stream.addEventListener){if("undefined"==typeof syncAction||1==syncAction){var streamEndedEvent="ended";"oninactive"in stream&&(streamEndedEvent="inactive"),stream.addEventListener(streamEndedEvent,function(){StreamsHandler.onSyncNeeded(this.streamid,streamEndedEvent)},!1)}stream.mute=function(type,isSyncAction){type=handleType(type),"undefined"!=typeof isSyncAction&&(syncAction=isSyncAction),"undefined"!=typeof type&&"audio"!=type||stream.getAudioTracks().forEach(function(track){track.enabled=!1,connection.streamEvents[stream.streamid].isAudioMuted=!0}),"undefined"!=typeof type&&"video"!=type||stream.getVideoTracks().forEach(function(track){track.enabled=!1}),"undefined"!=typeof syncAction&&1!=syncAction||StreamsHandler.onSyncNeeded(stream.streamid,"mute",type),connection.streamEvents[stream.streamid].muteType=type||"both",fireEvent(stream,"mute",type)},stream.unmute=function(type,isSyncAction){type=handleType(type),"undefined"!=typeof isSyncAction&&(syncAction=isSyncAction),graduallyIncreaseVolume(),"undefined"!=typeof type&&"audio"!=type||stream.getAudioTracks().forEach(function(track){track.enabled=!0,connection.streamEvents[stream.streamid].isAudioMuted=!1}),"undefined"!=typeof type&&"video"!=type||(stream.getVideoTracks().forEach(function(track){track.enabled=!0}),"undefined"!=typeof type&&"video"==type&&connection.streamEvents[stream.streamid].isAudioMuted&&!function looper(times){times||(times=0),times++,times<100&&connection.streamEvents[stream.streamid].isAudioMuted&&(stream.mute("audio"),setTimeout(function(){looper(times)},50))}()),"undefined"!=typeof syncAction&&1!=syncAction||StreamsHandler.onSyncNeeded(stream.streamid,"unmute",type),connection.streamEvents[stream.streamid].unmuteType=type||"both",fireEvent(stream,"unmute",type)}}}function afterEach(setTimeoutInteval,numberOfTimes,callback,startedTimes){startedTimes=(startedTimes||0)+1,startedTimes>=numberOfTimes||setTimeout(function(){callback(),afterEach(setTimeoutInteval,numberOfTimes,callback,startedTimes)},setTimeoutInteval)}return{setHandlers:setHandlers,onSyncNeeded:function(streamid,action,type){}}}();window.addEventListener("message",function(event){event.origin==window.location.origin&&onMessageCallback(event.data)});var sourceId,screenCallback,chromeMediaSource="screen",isFirefox="undefined"!=typeof window.InstallTrigger,isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,TextSender=(!!window.chrome&&!isOpera,{send:function(config){function sendText(textMessage,text){var data={type:"text",uuid:uuid,sendingTime:sendingTime};textMessage&&(text=textMessage,data.packets=parseInt(text.length/packetSize)),text.length>packetSize?data.message=text.slice(0,packetSize):(data.message=text,data.last=!0,data.isobject=isobject),channel.send(data,remoteUserId),textToTransfer=text.slice(data.message.length),textToTransfer.length&&setTimeout(function(){sendText(null,textToTransfer)},connection.chunkInterval||100)}var connection=config.connection,channel=config.channel,remoteUserId=config.remoteUserId,initialText=config.text,packetSize=connection.chunkSize||1e3,textToTransfer="",isobject=!1;isString(initialText)||(isobject=!0,initialText=JSON.stringify(initialText));var uuid=getRandomString(),sendingTime=(new Date).getTime();sendText(initialText)}}),FileProgressBarHandler=function(){function handle(connection){function updateLabel(progress,label){if(progress.position!==-1){var position=+progress.position.toFixed(2).split(".")[1]||100;label.innerHTML=position+"%"}}var progressHelper={};connection.onFileStart=function(file){var div=document.createElement("div");return div.title=file.name,div.innerHTML="<label>0%</label> <progress></progress>",file.remoteUserId&&(div.innerHTML+=" (Sharing with:"+file.remoteUserId+")"),connection.filesContainer||(connection.filesContainer=document.body||document.documentElement),connection.filesContainer.insertBefore(div,connection.filesContainer.firstChild),file.remoteUserId?(progressHelper[file.uuid]||(progressHelper[file.uuid]={}),progressHelper[file.uuid][file.remoteUserId]={div:div,progress:div.querySelector("progress"),label:div.querySelector("label")},void(progressHelper[file.uuid][file.remoteUserId].progress.max=file.maxChunks)):(progressHelper[file.uuid]={div:div,progress:div.querySelector("progress"),label:div.querySelector("label")},void(progressHelper[file.uuid].progress.max=file.maxChunks))},connection.onFileProgress=function(chunk){var helper=progressHelper[chunk.uuid];helper&&(chunk.remoteUserId&&!(helper=progressHelper[chunk.uuid][chunk.remoteUserId])||(helper.progress.value=chunk.currentPosition||chunk.maxChunks||helper.progress.max,updateLabel(helper.progress,helper.label)))},connection.onFileEnd=function(file){var helper=progressHelper[file.uuid];if(!helper)return void console.error("No such progress-helper element exist.",file);if(!file.remoteUserId||(helper=progressHelper[file.uuid][file.remoteUserId])){var div=helper.div;file.type.indexOf("image")!=-1?div.innerHTML='<a href="'+file.url+'" download="'+file.name+'">Download <strong style="color:red;">'+file.name+'</strong> </a><br /><img src="'+file.url+'" title="'+file.name+'" style="max-width: 80%;">':div.innerHTML='<a href="'+file.url+'" download="'+file.name+'">Download <strong style="color:red;">'+file.name+'</strong> </a><br /><iframe src="'+file.url+'" title="'+file.name+'" style="width: 80%;border: 0;height: inherit;margin-top:1em;"></iframe>'}}}return{handle:handle}}(),TranslationHandler=function(){function handle(connection){connection.autoTranslateText=!1,connection.language="en",connection.googKey="AIzaSyCgB5hmFY74WYB-EoWkhr9cAGr6TiTHrEE",connection.Translator={TranslateText:function(text,callback){var newScript=document.createElement("script");newScript.type="text/javascript";var sourceText=encodeURIComponent(text),randomNumber="method"+connection.token();window[randomNumber]=function(response){return response.data&&response.data.translations[0]&&callback?void callback(response.data.translations[0].translatedText):response.error&&"Daily Limit Exceeded"===response.error.message?void console.error('Text translation failed. Error message: "Daily Limit Exceeded."'):response.error?void console.error(response.error.message):void console.error(response)};var source="https://www.googleapis.com/language/translate/v2?key="+connection.googKey+"&target="+(connection.language||"en-US")+"&callback=window."+randomNumber+"&q="+sourceText;newScript.src=source,document.getElementsByTagName("head")[0].appendChild(newScript)},getListOfLanguages:function(callback){var xhr=new XMLHttpRequest;xhr.onreadystatechange=function(){if(xhr.readyState==XMLHttpRequest.DONE){var response=JSON.parse(xhr.responseText);if(response&&response.data&&response.data.languages)return void callback(response.data.languages);if(response.error&&"Daily Limit Exceeded"===response.error.message)return void console.error('Text translation failed. Error message: "Daily Limit Exceeded."');if(response.error)return void console.error(response.error.message);console.error(response)}};var url="https://www.googleapis.com/language/translate/v2/languages?key="+connection.googKey+"&target=en";xhr.open("GET",url,!0),xhr.send(null)}}}return{handle:handle}}();!function(connection){function onUserLeft(remoteUserId){connection.deletePeer(remoteUserId)}function connectSocket(connectCallback){if(connection.socketAutoReConnect=!0,connection.socket)return void(connectCallback&&connectCallback(connection.socket));if("undefined"==typeof SocketConnection)if("undefined"!=typeof FirebaseConnection)window.SocketConnection=FirebaseConnection;else{if("undefined"==typeof PubNubConnection)throw"SocketConnection.js seems missed.";window.SocketConnection=PubNubConnection}new SocketConnection(connection,function(s){connectCallback&&connectCallback(connection.socket)})}function joinRoom(connectionDescription,cb){connection.socket.emit("join-room",{sessionid:connection.sessionid,session:connection.session,mediaConstraints:connection.mediaConstraints,sdpConstraints:connection.sdpConstraints,streams:getStreamInfoForAdmin(),extra:connection.extra,password:"undefined"!=typeof connection.password&&"object"!=typeof connection.password?connection.password:""},function(isRoomJoined,error){if(isRoomJoined===!0){if(connection.enableLogs&&console.log("isRoomJoined: ",isRoomJoined," roomid: ",connection.sessionid),connection.peers[connection.sessionid])return;mPeer.onNegotiationNeeded(connectionDescription)}isRoomJoined===!1&&connection.enableLogs&&console.warn("isRoomJoined: ",error," roomid: ",connection.sessionid),cb(isRoomJoined,connection.sessionid,error)})}function openRoom(callback){connection.enableLogs&&console.log("Sending open-room signal to socket.io"),connection.waitingForLocalMedia=!1,connection.socket.emit("open-room",{sessionid:connection.sessionid,session:connection.session,mediaConstraints:connection.mediaConstraints,sdpConstraints:connection.sdpConstraints,streams:getStreamInfoForAdmin(),extra:connection.extra,identifier:connection.publicRoomIdentifier,password:"undefined"!=typeof connection.password&&"object"!=typeof connection.password?connection.password:""},function(isRoomOpened,error){isRoomOpened===!0&&(connection.enableLogs&&console.log("isRoomOpened: ",isRoomOpened," roomid: ",connection.sessionid),callback(isRoomOpened,connection.sessionid)),isRoomOpened===!1&&(connection.enableLogs&&console.warn("isRoomOpened: ",error," roomid: ",connection.sessionid),callback(isRoomOpened,connection.sessionid,error))})}function getStreamInfoForAdmin(){try{return connection.streamEvents.selectAll("local").map(function(event){return{streamid:event.streamid,tracks:event.stream.getTracks().length}})}catch(e){return[]}}function beforeJoin(userPreferences,callback){if(connection.dontCaptureUserMedia||userPreferences.isDataOnly)return void callback();var localMediaConstraints={};userPreferences.localPeerSdpConstraints.OfferToReceiveAudio&&(localMediaConstraints.audio=connection.mediaConstraints.audio),userPreferences.localPeerSdpConstraints.OfferToReceiveVideo&&(localMediaConstraints.video=connection.mediaConstraints.video);var session=userPreferences.session||connection.session;return session.oneway&&"two-way"!==session.audio&&"two-way"!==session.video&&"two-way"!==session.screen?void callback():(session.oneway&&session.audio&&"two-way"===session.audio&&(session={audio:!0}),void((session.audio||session.video||session.screen)&&(session.screen?"Edge"===DetectRTC.browser.name?navigator.getDisplayMedia({video:!0,audio:isAudioPlusTab(connection)}).then(function(screen){screen.isScreen=!0,mPeer.onGettingLocalMedia(screen),!session.audio&&!session.video||isAudioPlusTab(connection)?callback(screen):connection.invokeGetUserMedia(null,callback)},function(error){console.error("Unable to capture screen on Edge. HTTPs and version 17+ is required.")}):connection.getScreenConstraints(function(error,screen_constraints){connection.invokeGetUserMedia({audio:!!isAudioPlusTab(connection)&&getAudioScreenConstraints(screen_constraints),video:screen_constraints,isScreen:!0},!session.audio&&!session.video||isAudioPlusTab(connection)?callback:connection.invokeGetUserMedia(null,callback))}):(session.audio||session.video)&&connection.invokeGetUserMedia(null,callback,session))))}function applyConstraints(stream,mediaConstraints){return stream?(mediaConstraints.audio&&stream.getAudioTracks().forEach(function(track){track.applyConstraints(mediaConstraints.audio)}),void(mediaConstraints.video&&stream.getVideoTracks().forEach(function(track){track.applyConstraints(mediaConstraints.video)}))):void(connection.enableLogs&&console.error("No stream to applyConstraints."))}function replaceTrack(track,remoteUserId,isVideoTrack){return remoteUserId?void mPeer.replaceTrack(track,remoteUserId,isVideoTrack):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.replaceTrack(track,participant,isVideoTrack)})}forceOptions=forceOptions||{useDefaultDevices:!0},connection.channel=connection.sessionid=(roomid||location.href.replace(/\/|:|#|\?|\$|\^|%|\.|`|~|!|\+|@|\[|\||]|\|*. /g,"").split("\n").join("").split("\r").join(""))+"";var mPeer=new MultiPeers(connection),preventDuplicateOnStreamEvents={};mPeer.onGettingLocalMedia=function(stream,callback){if(callback=callback||function(){},preventDuplicateOnStreamEvents[stream.streamid])return void callback();preventDuplicateOnStreamEvents[stream.streamid]=!0;try{stream.type="local"}catch(e){}connection.setStreamEndHandler(stream),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,mediaElement.muted=!0,mediaElement.volume=0,connection.attachStreams.indexOf(stream)===-1&&connection.attachStreams.push(stream),"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!0,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"local",mediaElement:mediaElement,userid:connection.userid,extra:connection.extra,streamid:stream.streamid,isAudioMuted:!0};try{setHarkEvents(connection,connection.streamEvents[stream.streamid]),setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])}catch(e){}callback()},connection)},mPeer.onGettingRemoteMedia=function(stream,remoteUserId){try{stream.type="remote"}catch(e){}connection.setStreamEndHandler(stream,"remote-stream"),getRMCMediaElement(stream,function(mediaElement){mediaElement.id=stream.streamid,"undefined"!=typeof StreamsHandler&&StreamsHandler.setHandlers(stream,!1,connection),connection.streamEvents[stream.streamid]={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},mediaElement:mediaElement,streamid:stream.streamid},setMuteHandlers(connection,connection.streamEvents[stream.streamid]),connection.onstream(connection.streamEvents[stream.streamid])},connection)},mPeer.onRemovingRemoteMedia=function(stream,remoteUserId){var streamEvent=connection.streamEvents[stream.streamid];streamEvent||(streamEvent={stream:stream,type:"remote",userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{},streamid:stream.streamid,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),connection.peersBackup[streamEvent.userid]&&(streamEvent.extra=connection.peersBackup[streamEvent.userid].extra),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid]},mPeer.onNegotiationNeeded=function(message,remoteUserId,callback){callback=callback||function(){},remoteUserId=remoteUserId||message.remoteUserId,message=message||"";var messageToDeliver={remoteUserId:remoteUserId,message:message,sender:connection.userid};message.remoteUserId&&message.message&&message.sender&&(messageToDeliver=message),connectSocket(function(){connection.socket.emit(connection.socketMessageEvent,messageToDeliver,callback)})},mPeer.onUserLeft=onUserLeft,mPeer.disconnectWith=function(remoteUserId,callback){connection.socket&&connection.socket.emit("disconnect-with",remoteUserId,callback||function(){}),connection.deletePeer(remoteUserId)},connection.socketOptions={transport:"polling"},connection.openOrJoin=function(roomid,callback){callback=callback||function(){},connection.checkPresence(roomid,function(isRoomExist,roomid){if(isRoomExist){connection.sessionid=roomid;var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!!connection.session.oneway,isDataOnly=isData(connection.session);remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo};var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid};return void beforeJoin(connectionDescription.message,function(){joinRoom(connectionDescription,callback)})}return connection.waitingForLocalMedia=!0,connection.isInitiator=!0,connection.sessionid=roomid||connection.sessionid,isData(connection.session)?void openRoom(callback):void connection.captureUserMedia(function(){openRoom(callback)})})},connection.waitingForLocalMedia=!1,connection.open=function(roomid,callback){callback=callback||function(){},connection.waitingForLocalMedia=!0,connection.isInitiator=!0,connection.sessionid=roomid||connection.sessionid,connectSocket(function(){return isData(connection.session)?void openRoom(callback):void connection.captureUserMedia(function(){openRoom(callback)})})},connection.peersBackup={},connection.deletePeer=function(remoteUserId){if(remoteUserId&&connection.peers[remoteUserId]){var eventObject={userid:remoteUserId,extra:connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{}};if(connection.peersBackup[eventObject.userid]&&(eventObject.extra=connection.peersBackup[eventObject.userid].extra),connection.onleave(eventObject),connection.peers[remoteUserId]){connection.peers[remoteUserId].streams.forEach(function(stream){stream.stop()});var peer=connection.peers[remoteUserId].peer;if(peer&&"closed"!==peer.iceConnectionState)try{peer.close()}catch(e){}connection.peers[remoteUserId]&&(connection.peers[remoteUserId].peer=null,delete connection.peers[remoteUserId])}}},connection.rejoin=function(connectionDescription){if(!connection.isInitiator&&connectionDescription&&Object.keys(connectionDescription).length){var extra={};
|
|
connection.peers[connectionDescription.remoteUserId]&&(extra=connection.peers[connectionDescription.remoteUserId].extra,connection.deletePeer(connectionDescription.remoteUserId)),connectionDescription&&connectionDescription.remoteUserId&&(connection.join(connectionDescription.remoteUserId),connection.onReConnecting({userid:connectionDescription.remoteUserId,extra:extra}))}},connection.join=function(remoteUserId,options){connection.sessionid=!!remoteUserId&&(remoteUserId.sessionid||remoteUserId.remoteUserId||remoteUserId)||connection.sessionid,connection.sessionid+="";var localPeerSdpConstraints=!1,remotePeerSdpConstraints=!1,isOneWay=!1,isDataOnly=!1;if(remoteUserId&&remoteUserId.session||!remoteUserId||"string"==typeof remoteUserId){var session=remoteUserId?remoteUserId.session||connection.session:connection.session;isOneWay=!!session.oneway,isDataOnly=isData(session),remotePeerSdpConstraints={OfferToReceiveAudio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:connection.sdpConstraints.mandatory.OfferToReceiveVideo},localPeerSdpConstraints={OfferToReceiveAudio:isOneWay?!!connection.session.audio:connection.sdpConstraints.mandatory.OfferToReceiveAudio,OfferToReceiveVideo:isOneWay?!!connection.session.video||!!connection.session.screen:connection.sdpConstraints.mandatory.OfferToReceiveVideo}}options=options||{};var cb=function(){};"function"==typeof options&&(cb=options,options={}),"undefined"!=typeof options.localPeerSdpConstraints&&(localPeerSdpConstraints=options.localPeerSdpConstraints),"undefined"!=typeof options.remotePeerSdpConstraints&&(remotePeerSdpConstraints=options.remotePeerSdpConstraints),"undefined"!=typeof options.isOneWay&&(isOneWay=options.isOneWay),"undefined"!=typeof options.isDataOnly&&(isDataOnly=options.isDataOnly);var connectionDescription={remoteUserId:connection.sessionid,message:{newParticipationRequest:!0,isOneWay:isOneWay,isDataOnly:isDataOnly,localPeerSdpConstraints:localPeerSdpConstraints,remotePeerSdpConstraints:remotePeerSdpConstraints},sender:connection.userid};return beforeJoin(connectionDescription.message,function(){connectSocket(function(){joinRoom(connectionDescription,cb)})}),connectionDescription},connection.publicRoomIdentifier="",connection.getUserMedia=connection.captureUserMedia=function(callback,sessionForced){callback=callback||function(){};var session=sessionForced||connection.session;return connection.dontCaptureUserMedia||isData(session)?void callback():void((session.audio||session.video||session.screen)&&(session.screen?"Edge"===DetectRTC.browser.name?navigator.getDisplayMedia({video:!0,audio:isAudioPlusTab(connection)}).then(function(screen){if(screen.isScreen=!0,mPeer.onGettingLocalMedia(screen),(session.audio||session.video)&&!isAudioPlusTab(connection)){var nonScreenSession={};for(var s in session)"screen"!==s&&(nonScreenSession[s]=session[s]);return void connection.invokeGetUserMedia(sessionForced,callback,nonScreenSession)}callback(screen)},function(error){console.error("Unable to capture screen on Edge. HTTPs and version 17+ is required.")}):connection.getScreenConstraints(function(error,screen_constraints){if(error)throw error;connection.invokeGetUserMedia({audio:!!isAudioPlusTab(connection)&&getAudioScreenConstraints(screen_constraints),video:screen_constraints,isScreen:!0},function(stream){if((session.audio||session.video)&&!isAudioPlusTab(connection)){var nonScreenSession={};for(var s in session)"screen"!==s&&(nonScreenSession[s]=session[s]);return void connection.invokeGetUserMedia(sessionForced,callback,nonScreenSession)}callback(stream)})}):(session.audio||session.video)&&connection.invokeGetUserMedia(sessionForced,callback,session)))},connection.onbeforeunload=function(arg1,dontCloseSocket){connection.closeBeforeUnload&&(connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({userLeft:!0},participant),connection.peers[participant]&&connection.peers[participant].peer&&connection.peers[participant].peer.close(),delete connection.peers[participant]}),dontCloseSocket||connection.closeSocket(),connection.isInitiator=!1)},window.ignoreBeforeUnload?connection.closeBeforeUnload=!1:(connection.closeBeforeUnload=!0,window.addEventListener("beforeunload",connection.onbeforeunload,!1)),connection.userid=getRandomString(),connection.changeUserId=function(newUserId,callback){callback=callback||function(){},connection.userid=newUserId||getRandomString(),connection.socket.emit("changed-uuid",connection.userid,callback)},connection.extra={},connection.attachStreams=[],connection.session={audio:!0,video:!0},connection.enableFileSharing=!1,connection.bandwidth={screen:!1,audio:!1,video:!1},connection.codecs={audio:"opus",video:"VP9"},connection.processSdp=function(sdp){return"Safari"===DetectRTC.browser.name?sdp:("VP8"===connection.codecs.video.toUpperCase()&&(sdp=CodecsHandler.preferCodec(sdp,"vp8")),"VP9"===connection.codecs.video.toUpperCase()&&(sdp=CodecsHandler.preferCodec(sdp,"vp9")),"H264"===connection.codecs.video.toUpperCase()&&(sdp=CodecsHandler.preferCodec(sdp,"h264")),"G722"===connection.codecs.audio&&(sdp=CodecsHandler.removeNonG722(sdp)),"Firefox"===DetectRTC.browser.name?sdp:((connection.bandwidth.video||connection.bandwidth.screen)&&(sdp=CodecsHandler.setApplicationSpecificBandwidth(sdp,connection.bandwidth,!!connection.session.screen)),connection.bandwidth.video&&(sdp=CodecsHandler.setVideoBitrates(sdp,{min:8*connection.bandwidth.video*1024,max:8*connection.bandwidth.video*1024})),connection.bandwidth.audio&&(sdp=CodecsHandler.setOpusAttributes(sdp,{maxaveragebitrate:8*connection.bandwidth.audio*1024,maxplaybackrate:8*connection.bandwidth.audio*1024,stereo:1,maxptime:3})),sdp))},"undefined"!=typeof CodecsHandler&&(connection.BandwidthHandler=connection.CodecsHandler=CodecsHandler),connection.mediaConstraints={audio:{mandatory:{},optional:connection.bandwidth.audio?[{bandwidth:8*connection.bandwidth.audio*1024||1048576}]:[]},video:{mandatory:{},optional:connection.bandwidth.video?[{bandwidth:8*connection.bandwidth.video*1024||1048576},{facingMode:"user"}]:[{facingMode:"user"}]}},"Firefox"===DetectRTC.browser.name&&(connection.mediaConstraints={audio:!0,video:!0}),forceOptions.useDefaultDevices||DetectRTC.isMobileDevice||DetectRTC.load(function(){var lastAudioDevice,lastVideoDevice;if(DetectRTC.MediaDevices.forEach(function(device){"audioinput"===device.kind&&connection.mediaConstraints.audio!==!1&&(lastAudioDevice=device),"videoinput"===device.kind&&connection.mediaConstraints.video!==!1&&(lastVideoDevice=device)}),lastAudioDevice){if("Firefox"===DetectRTC.browser.name)return void(connection.mediaConstraints.audio!==!0?connection.mediaConstraints.audio.deviceId=lastAudioDevice.id:connection.mediaConstraints.audio={deviceId:lastAudioDevice.id});1==connection.mediaConstraints.audio&&(connection.mediaConstraints.audio={mandatory:{},optional:[]}),connection.mediaConstraints.audio.optional||(connection.mediaConstraints.audio.optional=[]);var optional=[{sourceId:lastAudioDevice.id}];connection.mediaConstraints.audio.optional=optional.concat(connection.mediaConstraints.audio.optional)}if(lastVideoDevice){if("Firefox"===DetectRTC.browser.name)return void(connection.mediaConstraints.video!==!0?connection.mediaConstraints.video.deviceId=lastVideoDevice.id:connection.mediaConstraints.video={deviceId:lastVideoDevice.id});1==connection.mediaConstraints.video&&(connection.mediaConstraints.video={mandatory:{},optional:[]}),connection.mediaConstraints.video.optional||(connection.mediaConstraints.video.optional=[]);var optional=[{sourceId:lastVideoDevice.id}];connection.mediaConstraints.video.optional=optional.concat(connection.mediaConstraints.video.optional)}}),connection.sdpConstraints={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:!0},optional:[{VoiceActivityDetection:!1}]},connection.rtcpMuxPolicy="require",connection.iceTransportPolicy=null,connection.optionalArgument={optional:[{DtlsSrtpKeyAgreement:!0},{googImprovedWifiBwe:!0},{googScreencastMinBitrate:300},{googIPv6:!0},{googDscp:!0},{googCpuUnderuseThreshold:55},{googCpuOveruseThreshold:85},{googSuspendBelowMinBitrate:!0},{googCpuOveruseDetection:!0}],mandatory:{}},connection.iceServers=IceServersHandler.getIceServers(connection),connection.candidates={host:!0,stun:!0,turn:!0},connection.iceProtocols={tcp:!0,udp:!0},connection.onopen=function(event){connection.enableLogs&&console.info("Data connection has been opened between you & ",event.userid)},connection.onclose=function(event){connection.enableLogs&&console.warn("Data connection has been closed between you & ",event.userid)},connection.onerror=function(error){connection.enableLogs&&console.error(error.userid,"data-error",error)},connection.onmessage=function(event){connection.enableLogs&&console.debug("data-message",event.userid,event.data)},connection.send=function(data,remoteUserId){connection.peers.send(data,remoteUserId)},connection.close=connection.disconnect=connection.leave=function(){connection.onbeforeunload(!1,!0)},connection.closeEntireSession=function(callback){callback=callback||function(){},connection.socket.emit("close-entire-session",function looper(){return connection.getAllParticipants().length?void setTimeout(looper,100):(connection.onEntireSessionClosed({sessionid:connection.sessionid,userid:connection.userid,extra:connection.extra}),void connection.changeUserId(null,function(){connection.close(),callback()}))})},connection.onEntireSessionClosed=function(event){connection.enableLogs&&console.info("Entire session is closed: ",event.sessionid,event.extra)},connection.onstream=function(e){var parentNode=connection.videosContainer;parentNode.insertBefore(e.mediaElement,parentNode.firstChild);var played=e.mediaElement.play();return"undefined"!=typeof played?void played["catch"](function(){}).then(function(){setTimeout(function(){e.mediaElement.play()},2e3)}):void setTimeout(function(){e.mediaElement.play()},2e3)},connection.onstreamended=function(e){e.mediaElement||(e.mediaElement=document.getElementById(e.streamid)),e.mediaElement&&e.mediaElement.parentNode&&e.mediaElement.parentNode.removeChild(e.mediaElement)},connection.direction="many-to-many",connection.removeStream=function(streamid,remoteUserId){var stream;return connection.attachStreams.forEach(function(localStream){localStream.id===streamid&&(stream=localStream)}),stream?(connection.peers.getAllParticipants().forEach(function(participant){if(!remoteUserId||participant===remoteUserId){var user=connection.peers[participant];try{user.peer.removeStream(stream)}catch(e){}}}),void connection.renegotiate()):void console.warn("No such stream exist.",streamid)},connection.addStream=function(session,remoteUserId){function gumCallback(stream){session.streamCallback&&session.streamCallback(stream),connection.renegotiate(remoteUserId)}return session.getAudioTracks?(connection.attachStreams.indexOf(session)===-1&&(session.streamid||(session.streamid=session.id),connection.attachStreams.push(session)),void connection.renegotiate(remoteUserId)):isData(session)?void connection.renegotiate(remoteUserId):void((session.audio||session.video||session.screen)&&(session.screen?"Edge"===DetectRTC.browser.name?navigator.getDisplayMedia({video:!0,audio:isAudioPlusTab(connection)}).then(function(screen){screen.isScreen=!0,mPeer.onGettingLocalMedia(screen),!session.audio&&!session.video||isAudioPlusTab(connection)?gumCallback(screen):connection.invokeGetUserMedia(null,function(stream){gumCallback(stream)})},function(error){console.error("Unable to capture screen on Edge. HTTPs and version 17+ is required.")}):connection.getScreenConstraints(function(error,screen_constraints){return error?"PermissionDeniedError"===error?(session.streamCallback&&session.streamCallback(null),void(connection.enableLogs&&console.error("User rejected to share his screen."))):alert(error):void connection.invokeGetUserMedia({audio:!!isAudioPlusTab(connection)&&getAudioScreenConstraints(screen_constraints),video:screen_constraints,isScreen:!0},function(stream){!session.audio&&!session.video||isAudioPlusTab(connection)?gumCallback(stream):connection.invokeGetUserMedia(null,function(stream){gumCallback(stream)})})}):(session.audio||session.video)&&connection.invokeGetUserMedia(null,gumCallback)))},connection.invokeGetUserMedia=function(localMediaConstraints,callback,session){session||(session=connection.session),localMediaConstraints||(localMediaConstraints=connection.mediaConstraints),getUserMediaHandler({onGettingLocalMedia:function(stream){var videoConstraints=localMediaConstraints.video;videoConstraints&&(videoConstraints.mediaSource||videoConstraints.mozMediaSource?stream.isScreen=!0:videoConstraints.mandatory&&videoConstraints.mandatory.chromeMediaSource&&(stream.isScreen=!0)),stream.isScreen||(stream.isVideo=stream.getVideoTracks().length,stream.isAudio=!stream.isVideo&&stream.getAudioTracks().length),mPeer.onGettingLocalMedia(stream,function(){"function"==typeof callback&&callback(stream)})},onLocalMediaError:function(error,constraints){mPeer.onLocalMediaError(error,constraints)},localMediaConstraints:localMediaConstraints||{audio:!!session.audio&&localMediaConstraints.audio,video:!!session.video&&localMediaConstraints.video}})},connection.applyConstraints=function(mediaConstraints,streamid){if(!MediaStreamTrack||!MediaStreamTrack.prototype.applyConstraints)return void alert("track.applyConstraints is NOT supported in your browser.");if(streamid){var stream;return connection.streamEvents[streamid]&&(stream=connection.streamEvents[streamid].stream),void applyConstraints(stream,mediaConstraints)}connection.attachStreams.forEach(function(stream){applyConstraints(stream,mediaConstraints)})},connection.replaceTrack=function(session,remoteUserId,isVideoTrack){function gumCallback(stream){connection.replaceTrack(stream,remoteUserId,isVideoTrack||session.video||session.screen)}if(session=session||{},!RTCPeerConnection.prototype.getSenders)return void connection.addStream(session);if(session instanceof MediaStreamTrack)return void replaceTrack(session,remoteUserId,isVideoTrack);if(session instanceof MediaStream)return session.getVideoTracks().length&&replaceTrack(session.getVideoTracks()[0],remoteUserId,!0),void(session.getAudioTracks().length&&replaceTrack(session.getAudioTracks()[0],remoteUserId,!1));if(isData(session))throw"connection.replaceTrack requires audio and/or video and/or screen.";(session.audio||session.video||session.screen)&&(session.screen?"Edge"===DetectRTC.browser.name?navigator.getDisplayMedia({video:!0,audio:isAudioPlusTab(connection)}).then(function(screen){screen.isScreen=!0,mPeer.onGettingLocalMedia(screen),!session.audio&&!session.video||isAudioPlusTab(connection)?gumCallback(screen):connection.invokeGetUserMedia(null,gumCallback)},function(error){console.error("Unable to capture screen on Edge. HTTPs and version 17+ is required.")}):connection.getScreenConstraints(function(error,screen_constraints){return error?alert(error):void connection.invokeGetUserMedia({audio:!!isAudioPlusTab(connection)&&getAudioScreenConstraints(screen_constraints),video:screen_constraints,isScreen:!0},!session.audio&&!session.video||isAudioPlusTab(connection)?gumCallback:connection.invokeGetUserMedia(null,gumCallback))}):(session.audio||session.video)&&connection.invokeGetUserMedia(null,gumCallback))},connection.resetTrack=function(remoteUsersIds,isVideoTrack){remoteUsersIds||(remoteUsersIds=connection.getAllParticipants()),"string"==typeof remoteUsersIds&&(remoteUsersIds=[remoteUsersIds]),remoteUsersIds.forEach(function(participant){var peer=connection.peers[participant].peer;"undefined"!=typeof isVideoTrack&&isVideoTrack!==!0||!peer.lastVideoTrack||connection.replaceTrack(peer.lastVideoTrack,participant,!0),"undefined"!=typeof isVideoTrack&&isVideoTrack!==!1||!peer.lastAudioTrack||connection.replaceTrack(peer.lastAudioTrack,participant,!1)})},connection.renegotiate=function(remoteUserId){return remoteUserId?void mPeer.renegotiatePeer(remoteUserId):void connection.peers.getAllParticipants().forEach(function(participant){mPeer.renegotiatePeer(participant)})},connection.setStreamEndHandler=function(stream,isRemote){if(stream&&stream.addEventListener&&(isRemote=!!isRemote,!stream.alreadySetEndHandler)){stream.alreadySetEndHandler=!0;var streamEndedEvent="ended";"oninactive"in stream&&(streamEndedEvent="inactive"),stream.addEventListener(streamEndedEvent,function(){if(stream.idInstance&¤tUserMediaRequest.remove(stream.idInstance),!isRemote){var streams=[];connection.attachStreams.forEach(function(s){s.id!=stream.id&&streams.push(s)}),connection.attachStreams=streams}var streamEvent=connection.streamEvents[stream.streamid];if(streamEvent||(streamEvent={stream:stream,streamid:stream.streamid,type:isRemote?"remote":"local",userid:connection.userid,extra:connection.extra,mediaElement:connection.streamEvents[stream.streamid]?connection.streamEvents[stream.streamid].mediaElement:null}),isRemote&&connection.peers[streamEvent.userid]){var peer=connection.peers[streamEvent.userid].peer,streams=[];peer.getRemoteStreams().forEach(function(s){s.id!=stream.id&&streams.push(s)}),connection.peers[streamEvent.userid].streams=streams}streamEvent.userid===connection.userid&&"remote"===streamEvent.type||(connection.peersBackup[streamEvent.userid]&&(streamEvent.extra=connection.peersBackup[streamEvent.userid].extra),connection.onstreamended(streamEvent),delete connection.streamEvents[stream.streamid])},!1)}},connection.onMediaError=function(error,constraints){connection.enableLogs&&console.error(error,constraints)},connection.autoCloseEntireSession=!1,connection.filesContainer=connection.videosContainer=document.body||document.documentElement,connection.isInitiator=!1,connection.shareFile=mPeer.shareFile,"undefined"!=typeof FileProgressBarHandler&&FileProgressBarHandler.handle(connection),"undefined"!=typeof TranslationHandler&&TranslationHandler.handle(connection),connection.token=getRandomString,connection.onNewParticipant=function(participantId,userPreferences){connection.acceptParticipationRequest(participantId,userPreferences)},connection.acceptParticipationRequest=function(participantId,userPreferences){userPreferences.successCallback&&(userPreferences.successCallback(),delete userPreferences.successCallback),mPeer.createNewPeer(participantId,userPreferences)},"undefined"!=typeof StreamsHandler&&(connection.StreamsHandler=StreamsHandler),connection.onleave=function(userid){},connection.invokeSelectFileDialog=function(callback){var selector=new FileSelector;selector.accept="*.*",selector.selectSingleFile(callback)},connection.onmute=function(e){if(e&&e.mediaElement)if("both"===e.muteType||"video"===e.muteType){e.mediaElement.src=null;var paused=e.mediaElement.pause();"undefined"!=typeof paused?paused.then(function(){e.mediaElement.poster=e.snapshot||"https://cdn.webrtc-experiment.com/images/muted.png"}):e.mediaElement.poster=e.snapshot||"https://cdn.webrtc-experiment.com/images/muted.png"}else"audio"===e.muteType&&(e.mediaElement.muted=!0)},connection.onunmute=function(e){e&&e.mediaElement&&e.stream&&("both"===e.unmuteType||"video"===e.unmuteType?(e.mediaElement.poster=null,e.mediaElement.srcObject=e.stream,e.mediaElement.play()):"audio"===e.unmuteType&&(e.mediaElement.muted=!1))},connection.onExtraDataUpdated=function(event){event.status="online",connection.onUserStatusChanged(event,!0)},connection.getAllParticipants=function(sender){return connection.peers.getAllParticipants(sender)},"undefined"!=typeof StreamsHandler&&(StreamsHandler.onSyncNeeded=function(streamid,action,type){connection.peers.getAllParticipants().forEach(function(participant){mPeer.onNegotiationNeeded({streamid:streamid,action:action,streamSyncNeeded:!0,type:type||"both"},participant)})}),connection.connectSocket=function(callback){connectSocket(callback)},connection.closeSocket=function(){try{io.sockets={}}catch(e){}connection.socket&&("function"==typeof connection.socket.disconnect&&connection.socket.disconnect(),"function"==typeof connection.socket.resetProps&&connection.socket.resetProps(),connection.socket=null)},connection.getSocket=function(callback){return!callback&&connection.enableLogs&&console.warn("getSocket.callback paramter is required."),callback=callback||function(){},connection.socket?callback(connection.socket):connectSocket(function(){callback(connection.socket)}),connection.socket},connection.getRemoteStreams=mPeer.getRemoteStreams;var skipStreams=["selectFirst","selectAll","forEach"];if(connection.streamEvents={selectFirst:function(options){return connection.streamEvents.selectAll(options)[0]},selectAll:function(options){options||(options={local:!0,remote:!0,isScreen:!0,isAudio:!0,isVideo:!0}),"local"==options&&(options={local:!0}),"remote"==options&&(options={remote:!0}),"screen"==options&&(options={isScreen:!0}),"audio"==options&&(options={isAudio:!0}),"video"==options&&(options={isVideo:!0});var streams=[];return Object.keys(connection.streamEvents).forEach(function(key){var event=connection.streamEvents[key];if(skipStreams.indexOf(key)===-1){var ignore=!0;options.local&&"local"===event.type&&(ignore=!1),options.remote&&"remote"===event.type&&(ignore=!1),options.isScreen&&event.stream.isScreen&&(ignore=!1),options.isVideo&&event.stream.isVideo&&(ignore=!1),options.isAudio&&event.stream.isAudio&&(ignore=!1),options.userid&&event.userid===options.userid&&(ignore=!1),ignore===!1&&streams.push(event)}}),streams}},connection.socketURL="/",connection.socketMessageEvent="RTCMultiConnection-Message",connection.socketCustomEvent="RTCMultiConnection-Custom-Message",connection.DetectRTC=DetectRTC,connection.setCustomSocketEvent=function(customEvent){customEvent&&(connection.socketCustomEvent=customEvent),connection.socket&&connection.socket.emit("set-custom-socket-event-listener",connection.socketCustomEvent)},connection.getNumberOfBroadcastViewers=function(broadcastId,callback){connection.socket&&broadcastId&&callback&&connection.socket.emit("get-number-of-users-in-specific-broadcast",broadcastId,callback)},connection.onNumberOfBroadcastViewersUpdated=function(event){connection.enableLogs&&connection.isInitiator&&console.info("Number of broadcast (",event.broadcastId,") viewers",event.numberOfBroadcastViewers)},connection.onUserStatusChanged=function(event,dontWriteLogs){connection.enableLogs&&!dontWriteLogs&&console.info(event.userid,event.status)},connection.getUserMediaHandler=getUserMediaHandler,connection.multiPeersHandler=mPeer,connection.enableLogs=!0,connection.setCustomSocketHandler=function(customSocketHandler){"undefined"!=typeof SocketConnection&&(SocketConnection=customSocketHandler)},connection.chunkSize=65e3,connection.maxParticipantsAllowed=1e3,connection.disconnectWith=mPeer.disconnectWith,connection.checkPresence=function(roomid,callback){return roomid=roomid||connection.sessionid,"SSEConnection"===SocketConnection.name?void SSEConnection.checkPresence(roomid,function(isRoomExist,_roomid,extra){return connection.socket?void callback(isRoomExist,_roomid):(isRoomExist||(connection.userid=_roomid),void connection.connectSocket(function(){callback(isRoomExist,_roomid,extra)}))}):connection.socket?void connection.socket.emit("check-presence",roomid+"",function(isRoomExist,_roomid,extra){connection.enableLogs&&console.log("checkPresence.isRoomExist: ",isRoomExist," roomid: ",_roomid),callback(isRoomExist,_roomid,extra)}):void connection.connectSocket(function(){connection.checkPresence(roomid,callback)})},connection.onReadyForOffer=function(remoteUserId,userPreferences){connection.multiPeersHandler.createNewPeer(remoteUserId,userPreferences)},connection.setUserPreferences=function(userPreferences){return connection.dontAttachStream&&(userPreferences.dontAttachLocalStream=!0),connection.dontGetRemoteStream&&(userPreferences.dontGetRemoteStream=!0),userPreferences},connection.updateExtraData=function(){connection.socket.emit("extra-data-updated",connection.extra)},connection.enableScalableBroadcast=!1,connection.maxRelayLimitPerUser=3,connection.dontCaptureUserMedia=!1,connection.dontAttachStream=!1,connection.dontGetRemoteStream=!1,connection.onReConnecting=function(event){connection.enableLogs&&console.info("ReConnecting with",event.userid,"...")},connection.beforeAddingStream=function(stream){return stream},connection.beforeRemovingStream=function(stream){return stream},"undefined"!=typeof isChromeExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isChromeExtensionAvailable),"undefined"!=typeof isFirefoxExtensionAvailable&&(connection.checkIfChromeExtensionAvailable=isFirefoxExtensionAvailable),"undefined"!=typeof getChromeExtensionStatus&&(connection.getChromeExtensionStatus=getChromeExtensionStatus),connection.getScreenConstraints=function(callback,audioPlusTab){isAudioPlusTab(connection,audioPlusTab)&&(audioPlusTab=!0),getScreenConstraints(function(error,screen_constraints){error||(screen_constraints=connection.modifyScreenConstraints(screen_constraints),callback(error,screen_constraints))},audioPlusTab)},connection.modifyScreenConstraints=function(screen_constraints){return screen_constraints},connection.onPeerStateChanged=function(state){connection.enableLogs&&state.iceConnectionState.search(/closed|failed/gi)!==-1&&console.error("Peer connection is closed between you & ",state.userid,state.extra,"state:",state.iceConnectionState)},connection.isOnline=!0,listenEventHandler("online",function(){connection.isOnline=!0}),listenEventHandler("offline",function(){connection.isOnline=!1}),connection.isLowBandwidth=!1,navigator&&navigator.connection&&navigator.connection.type&&(connection.isLowBandwidth=navigator.connection.type.toString().toLowerCase().search(/wifi|cell/g)!==-1,connection.isLowBandwidth)){if(connection.bandwidth={audio:!1,video:!1,screen:!1},connection.mediaConstraints.audio&&connection.mediaConstraints.audio.optional&&connection.mediaConstraints.audio.optional.length){var newArray=[];connection.mediaConstraints.audio.optional.forEach(function(opt){"undefined"==typeof opt.bandwidth&&newArray.push(opt)}),connection.mediaConstraints.audio.optional=newArray}if(connection.mediaConstraints.video&&connection.mediaConstraints.video.optional&&connection.mediaConstraints.video.optional.length){var newArray=[];connection.mediaConstraints.video.optional.forEach(function(opt){"undefined"==typeof opt.bandwidth&&newArray.push(opt)}),connection.mediaConstraints.video.optional=newArray}}connection.getExtraData=function(remoteUserId){if(!remoteUserId)throw"remoteUserId is required.";return connection.peers[remoteUserId]?connection.peers[remoteUserId].extra:{}},forceOptions.autoOpenOrJoin&&connection.openOrJoin(connection.sessionid),connection.onUserIdAlreadyTaken=function(useridAlreadyTaken,yourNewUserId){connection.enableLogs&&console.warn("Userid already taken.",useridAlreadyTaken,"Your new userid:",yourNewUserId),connection.userid=connection.token(),connection.join(connection.sessionid)},connection.trickleIce=!0,connection.version="3.5.3",connection.onSettingLocalDescription=function(event){connection.enableLogs&&console.info("Set local description for remote user",event.userid)},connection.resetScreen=function(){sourceId=null,DetectRTC&&DetectRTC.screen&&delete DetectRTC.screen.sourceId,currentUserMediaRequest={streams:[],mutex:!1,queueRequests:[]}},connection.autoCreateMediaElement=!0,connection.password=null,connection.setPassword=function(password,callback){callback=callback||function(){},connection.socket?connection.socket.emit("set-password",password,callback):(connection.password=password,callback(!0,connection.sessionid,null))},connection.errors={ROOM_NOT_AVAILABLE:"Room not available",INVALID_PASSWORD:"Invalid password",USERID_NOT_AVAILABLE:"User ID does not exist",ROOM_PERMISSION_DENIED:"Room permission denied",ROOM_FULL:"Room full",DID_NOT_JOIN_ANY_ROOM:"Did not join any room yet",INVALID_SOCKET:"Invalid socket",PUBLIC_IDENTIFIER_MISSING:"publicRoomIdentifier is required",INVALID_ADMIN_CREDENTIAL:"Invalid username or password attempted"}}(this)};"undefined"!=typeof module&&(module.exports=exports=RTCMultiConnection),"function"==typeof define&&define.amd&&define("RTCMultiConnection",[],function(){return RTCMultiConnection});
|
|
|
|
/*! jQuery v2.2.2 | (c) jQuery Foundation | jquery.org/license */
|
|
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.2",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c;
|
|
}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ea.test(f)?this.mouseHooks:da.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==ia()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===ia()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ga:ha):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ha,isPropagationStopped:ha,isImmediatePropagationStopped:ha,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ga,a&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ga,a&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ga,a&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ja(this,a,b,c,d)},one:function(a,b,c,d){return ja(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ha),this.each(function(){n.event.remove(this,a,c,b)})}});var ka=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,la=/<script|<style|<link/i,ma=/checked\s*(?:[^=]|=\s*.checked.)/i,na=/^true\/(.*)/,oa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=wa[0].contentDocument,b.write(),b.close(),c=ya(a,b),wa.detach()),xa[a]=c),c}var Aa=/^margin/,Ba=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ca=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Ea=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");if(h.style){h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h);function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Ea.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Ea.removeChild(g)}n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Ea.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Ea.removeChild(g),h.removeChild(c),b}})}}();function Fa(a,b,c){var d,e,f,g,h=a.style;return c=c||Ca(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Ba.test(g)&&Aa.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0!==g?g+"":g}function Ga(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ha=/^(none|table(?!-c[ea]).+)/,Ia={position:"absolute",visibility:"hidden",display:"block"},Ja={letterSpacing:"0",fontWeight:"400"},Ka=["Webkit","O","Moz","ms"],La=d.createElement("div").style;function Ma(a){if(a in La)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ka.length;while(c--)if(a=Ka[c]+b,a in La)return a}function Na(a,b,c){var d=T.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Oa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Pa(b,c,e){var f=!0,g="width"===c?b.offsetWidth:b.offsetHeight,h=Ca(b),i="border-box"===n.css(b,"boxSizing",!1,h);if(d.msFullscreenElement&&a.top!==a&&b.getClientRects().length&&(g=Math.round(100*b.getBoundingClientRect()[c])),0>=g||null==g){if(g=Fa(b,c,h),(0>g||null==g)&&(g=b.style[c]),Ba.test(g))return g;f=i&&(l.boxSizingReliable()||g===b.style[c]),g=parseFloat(g)||0}return g+Oa(b,c,e||(i?"border":"content"),f,h)+"px"}function Qa(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=N.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=N.access(d,"olddisplay",za(d.nodeName)))):(e=V(d),"none"===c&&e||N.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Fa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=T.exec(c))&&e[1]&&(c=W(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Fa(a,b,d)),"normal"===e&&b in Ja&&(e=Ja[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Ha.test(n.css(a,"display"))&&0===a.offsetWidth?Da(a,Ia,function(){return Pa(a,b,d)}):Pa(a,b,d):void 0},set:function(a,c,d){var e,f=d&&Ca(a),g=d&&Oa(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=T.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Na(a,c,g)}}}),n.cssHooks.marginLeft=Ga(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Fa(a,"marginLeft"))||a.getBoundingClientRect().left-Da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),n.cssHooks.marginRight=Ga(l.reliableMarginRight,function(a,b){return b?Da(a,{display:"inline-block"},Fa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Aa.test(a)||(n.cssHooks[a+b].set=Na)}),n.fn.extend({css:function(a,b){return K(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ca(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Qa(this,!0)},hide:function(){return Qa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function Ra(a,b,c,d,e){return new Ra.prototype.init(a,b,c,d,e)}n.Tween=Ra,Ra.prototype={constructor:Ra,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ra.propHooks[this.prop];return a&&a.get?a.get(this):Ra.propHooks._default.get(this)},run:function(a){var b,c=Ra.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ra.propHooks._default.set(this),this}},Ra.prototype.init.prototype=Ra.prototype,Ra.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Ra.propHooks.scrollTop=Ra.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Ra.prototype.init,n.fx.step={};var Sa,Ta,Ua=/^(?:toggle|show|hide)$/,Va=/queueHooks$/;function Wa(){return a.setTimeout(function(){Sa=void 0}),Sa=n.now()}function Xa(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=U[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ya(a,b,c){for(var d,e=(_a.tweeners[b]||[]).concat(_a.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Za(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&V(a),q=N.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?N.get(a,"olddisplay")||za(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ua.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?za(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=N.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;N.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ya(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function $a(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function _a(a,b,c){var d,e,f=0,g=_a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sa||Wa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Sa||Wa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for($a(k,j.opts.specialEasing);g>f;f++)if(d=_a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Ya,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(_a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return W(c.elem,a,T.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],_a.tweeners[c]=_a.tweeners[c]||[],_a.tweeners[c].unshift(b)},prefilters:[Za],prefilter:function(a,b){b?_a.prefilters.unshift(a):_a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=_a(this,n.extend({},a),f);(e||N.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=N.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Va.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=N.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Xa(b,!0),a,d,e)}}),n.each({slideDown:Xa("show"),slideUp:Xa("hide"),slideToggle:Xa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Sa=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Sa=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ta||(Ta=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Ta),Ta=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var ab,bb=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return K(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ab:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),ab={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=bb[b]||n.find.attr;bb[b]=function(a,b,d){var e,f;return d||(f=bb[b],bb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,bb[b]=f),e}});var cb=/^(?:input|select|textarea|button)$/i,db=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return K(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,
|
|
e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!L(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=N.access(d,b);e||d.addEventListener(a,c,!0),N.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=N.access(d,b)-1;e?N.access(d,b,e):(d.removeEventListener(a,c,!0),N.remove(d,b))}}});var jb=a.location,kb=n.now(),lb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var mb=/#.*$/,nb=/([?&])_=[^&]*/,ob=/^(.*?):[ \t]*([^\r\n]*)$/gm,pb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qb=/^(?:GET|HEAD)$/,rb=/^\/\//,sb={},tb={},ub="*/".concat("*"),vb=d.createElement("a");vb.href=jb.href;function wb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function xb(a,b,c,d){var e={},f=a===tb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function yb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function zb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Ab(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:jb.href,type:"GET",isLocal:pb.test(jb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":ub,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?yb(yb(a,n.ajaxSettings),b):yb(n.ajaxSettings,a)},ajaxPrefilter:wb(sb),ajaxTransport:wb(tb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=ob.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>v)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),z(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||jb.href)+"").replace(mb,"").replace(rb,jb.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(G)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=vb.protocol+"//"+vb.host!=j.protocol+"//"+j.host}catch(y){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),xb(sb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0===n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!qb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(lb.test(f)?"&":"?")+m.data,delete m.data),m.cache===!1&&(m.url=nb.test(f)?f.replace(nb,"$1_="+kb++):f+(lb.test(f)?"&":"?")+"_="+kb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+ub+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(o,x,m)===!1||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=xb(tb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,z)}catch(y){if(!(2>v))throw y;z(-1,y)}}else z(-1,"No Transport");function z(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(u=zb(m,x,d)),u=Ab(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Bb=/%20/g,Cb=/\[\]$/,Db=/\r?\n/g,Eb=/^(?:submit|button|image|reset|file)$/i,Fb=/^(?:input|select|textarea|keygen)/i;function Gb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Cb.test(a)?d(a,e):Gb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Gb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Gb(c,a[c],b,e);return d.join("&").replace(Bb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Fb.test(this.nodeName)&&!Eb.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Db,"\r\n")}}):{name:b.name,value:c.replace(Db,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Hb={0:200,1223:204},Ib=n.ajaxSettings.xhr();l.cors=!!Ib&&"withCredentials"in Ib,l.ajax=Ib=!!Ib,n.ajaxTransport(function(b){var c,d;return l.cors||Ib&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Hb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Jb=[],Kb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Jb.pop()||n.expando+"_"+kb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Kb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Kb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Kb,"$1"+e):b.jsonp!==!1&&(b.url+=(lb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Jb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ca([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Lb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Lb)return Lb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(g,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Mb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Mb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ea})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return K(this,function(a,d,e){var f=Mb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ga(l.pixelPosition,function(a,c){return c?(c=Fa(a,b),Ba.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return K(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Nb=a.jQuery,Ob=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Ob),b&&a.jQuery===n&&(a.jQuery=Nb),n},b||(a.jQuery=a.$=n),n});
|
|
|
|
var connection;
|
|
var lastSelectedFile;
|
|
|
|
var room_id = '';
|
|
|
|
// 60k -- assuming receiving client is chrome
|
|
var chunk_size = 60 * 1000;
|
|
|
|
var rmcMessageLogs = [];
|
|
|
|
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
|
|
if (message == 'rmc-select-file') {
|
|
var selector = new FileSelector();
|
|
selector.selectSingleFile(function(file) {
|
|
if (!file) return;
|
|
onFileSelected(file);
|
|
});
|
|
return;
|
|
}
|
|
|
|
if(message === 'close-and-rejoin') {
|
|
if(connection) {
|
|
connection.close();
|
|
connection.closeSocket();
|
|
}
|
|
connection = null;
|
|
|
|
callback([{
|
|
isRMCDisConnected: true
|
|
}]);
|
|
return;
|
|
}
|
|
|
|
if (message.downloadFile) {
|
|
if (connection.fileReceived[message.fileSize + message.fileName]) {
|
|
invokeSaveAsDialog(connection.fileReceived[message.fileSize + message.fileName]);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (message !== 'rmc-ping-pong') {
|
|
return;
|
|
}
|
|
|
|
if (rmcMessageLogs.length) {
|
|
callback(rmcMessageLogs);
|
|
if(rmcMessageLogs.length > 30) {
|
|
rmcMessageLogs = rmcMessageLogs.slice(rmcMessageLogs.length - 30, rmcMessageLogs.length);
|
|
}
|
|
}
|
|
|
|
if (connection && connection.isConnected) {
|
|
var index;
|
|
rmcMessageLogs.forEach(function(item, idx) {
|
|
if(item.isRMCConnected) {
|
|
index = idx;
|
|
}
|
|
});
|
|
|
|
var obj = {
|
|
isRMCConnected: true,
|
|
sessionid: connection.channel,
|
|
isRoomExists: !connection.isInitiator,
|
|
numberOfConnectedUsers: connection.getAllParticipants().length
|
|
};
|
|
|
|
if(index) {
|
|
rmcMessageLogs[index] = obj;
|
|
}
|
|
else rmcMessageLogs.push(obj);
|
|
|
|
return;
|
|
}
|
|
|
|
if (connection) {
|
|
return;
|
|
}
|
|
|
|
chrome.storage.sync.get(null, function(items) {
|
|
if (items['room_id']) {
|
|
room_id = items['room_id'];
|
|
}
|
|
|
|
if (items['chunk_size']) {
|
|
chunk_size = parseInt(items['chunk_size']);
|
|
}
|
|
|
|
setupWebRTCConnection();
|
|
});
|
|
});
|
|
|
|
function bytesToSize(bytes) {
|
|
var k = 1000;
|
|
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
|
if (bytes === 0) {
|
|
return '0 Bytes';
|
|
}
|
|
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
|
|
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
|
|
}
|
|
|
|
function onFileSelected(file) {
|
|
rmcMessageLogs.push({
|
|
fileSelected: true,
|
|
fileName: file.name,
|
|
fileSize: bytesToSize(file.size),
|
|
fileOriginalSize: file.size,
|
|
});
|
|
|
|
lastSelectedFile = file;
|
|
|
|
if (connection) {
|
|
connection.send({
|
|
doYouWannaReceiveThisFile: true,
|
|
fileName: file.size + file.name
|
|
});
|
|
}
|
|
}
|
|
|
|
function setupWebRTCConnection() {
|
|
if (connection) {
|
|
return;
|
|
}
|
|
|
|
// www.RTCMultiConnection.org/docs/
|
|
connection = new RTCMultiConnection();
|
|
|
|
connection.autoCloseEntireSession = true;
|
|
|
|
// to make sure, "connection-reconnect" doesn't sends files again
|
|
connection.fileReceived = {};
|
|
|
|
// by default, socket.io server is assumed to be deployed on your own URL
|
|
// connection.socketURL = '/';
|
|
|
|
// comment-out below line if you do not have your own socket.io server
|
|
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
|
|
|
|
connection.socketMessageEvent = 'file-sharing-demo';
|
|
|
|
connection.chunkSize = chunk_size;
|
|
|
|
connection.sdpConstraints.mandatory = {
|
|
OfferToReceiveAudio: false,
|
|
OfferToReceiveVideo: false
|
|
};
|
|
|
|
connection.enableFileSharing = true;
|
|
connection.enableLogs = false;
|
|
|
|
if (room_id && room_id.length) {
|
|
connection.userid = room_id;
|
|
}
|
|
|
|
if (!room_id) {
|
|
room_id = connection.token();
|
|
}
|
|
|
|
connection.channel = connection.sessionid = room_id;
|
|
|
|
connection.session = {
|
|
data: true
|
|
};
|
|
|
|
connection.connectedWith = {};
|
|
|
|
connection.onmessage = function(event) {
|
|
if (event.data.doYouWannaReceiveThisFile) {
|
|
if (!connection.fileReceived[event.data.fileName]) {
|
|
connection.send({
|
|
yesIWannaReceive: true,
|
|
fileName: event.data.fileName
|
|
});
|
|
}
|
|
}
|
|
|
|
if (event.data.yesIWannaReceive && !!lastSelectedFile) {
|
|
connection.shareFile(lastSelectedFile, event.userid);
|
|
}
|
|
};
|
|
|
|
connection.onopen = function(e) {
|
|
if (connection.connectedWith[e.userid]) return;
|
|
connection.connectedWith[e.userid] = true;
|
|
|
|
if (!lastSelectedFile) return;
|
|
|
|
var file = lastSelectedFile;
|
|
setTimeout(function() {
|
|
connection.send({
|
|
doYouWannaReceiveThisFile: true,
|
|
fileName: file.size + file.name
|
|
});
|
|
}, 500);
|
|
};
|
|
|
|
setFileProgressBarHandlers(connection);
|
|
|
|
rmcMessageLogs.push({
|
|
rmcConnecting: true,
|
|
sessionid: connection.channel
|
|
});
|
|
|
|
connection.openOrJoin(connection.channel, function(isRoomExists) {
|
|
connection.isConnected = true;
|
|
|
|
rmcPort.postMessage({
|
|
changeIcon: true,
|
|
connected: true,
|
|
color: [0, 128, 0, 255]
|
|
});
|
|
});
|
|
}
|
|
|
|
function setFileProgressBarHandlers(connection) {
|
|
var progressHelper = {};
|
|
|
|
// www.RTCMultiConnection.org/docs/onFileStart/
|
|
connection.onFileStart = function(file) {
|
|
if (connection.fileReceived[file.size + file.name]) return;
|
|
|
|
rmcMessageLogs.push({
|
|
receivingFile: file.userid !== connection.userid,
|
|
fileName: file.name,
|
|
fileSize: bytesToSize(file.size),
|
|
fileOriginalSize: file.size,
|
|
senderId: file.userid
|
|
});
|
|
};
|
|
|
|
// www.RTCMultiConnection.org/docs/onFileProgress/
|
|
connection.onFileProgress = function(chunk) {
|
|
if (connection.fileReceived[chunk.size + chunk.name]) return;
|
|
|
|
rmcMessageLogs.push({
|
|
receivingFile: chunk.userid !== connection.userid,
|
|
fileName: chunk.name,
|
|
fileSize: bytesToSize(chunk.size),
|
|
fileOriginalSize: chunk.size,
|
|
senderId: chunk.userid,
|
|
fileProgress: {
|
|
currentPosition: chunk.currentPosition,
|
|
maxChunks: chunk.maxChunks
|
|
}
|
|
});
|
|
|
|
var percentage = parseInt((chunk.currentPosition/chunk.maxChunks) * 100);
|
|
changeIcon(percentage + '%');
|
|
if(percentage >= 99) {
|
|
changeIcon('');
|
|
}
|
|
};
|
|
|
|
// www.RTCMultiConnection.org/docs/onFileEnd/
|
|
connection.onFileEnd = function(file) {
|
|
if (connection.fileReceived[file.size + file.name]) return;
|
|
|
|
connection.fileReceived[file.size + file.name] = file;
|
|
|
|
rmcMessageLogs.push({
|
|
receivingFile: file.userid !== connection.userid,
|
|
fileName: file.name,
|
|
fileSize: bytesToSize(file.size),
|
|
fileOriginalSize: file.size,
|
|
senderId: file.userid,
|
|
ended: true
|
|
});
|
|
|
|
rmcPort.postMessage({
|
|
changeIcon: true,
|
|
defaultIcon: true
|
|
});
|
|
};
|
|
}
|
|
|
|
function invokeSaveAsDialog(file, fileName) {
|
|
if (!file) {
|
|
throw 'Blob object is required.';
|
|
}
|
|
|
|
if (!file.type) {
|
|
try {
|
|
file.type = 'video/webm';
|
|
} catch (e) {}
|
|
}
|
|
|
|
var fileExtension = (file.type || 'video/webm').split('/')[1];
|
|
|
|
if (fileName && fileName.indexOf('.') !== -1) {
|
|
var splitted = fileName.split('.');
|
|
fileName = splitted[0];
|
|
fileExtension = splitted[1];
|
|
}
|
|
|
|
var fileFullName = (fileName || (Math.round(Math.random() * 9999999999) + 888888888)) + '.' + fileExtension;
|
|
|
|
if (typeof navigator.msSaveOrOpenBlob !== 'undefined') {
|
|
return navigator.msSaveOrOpenBlob(file, fileFullName);
|
|
} else if (typeof navigator.msSaveBlob !== 'undefined') {
|
|
return navigator.msSaveBlob(file, fileFullName);
|
|
}
|
|
|
|
var hyperlink = document.createElement('a');
|
|
hyperlink.href = URL.createObjectURL(file);
|
|
hyperlink.target = '_blank';
|
|
hyperlink.download = fileFullName;
|
|
|
|
if (!!navigator.mozGetUserMedia) {
|
|
hyperlink.onclick = function() {
|
|
(document.body || document.documentElement).removeChild(hyperlink);
|
|
};
|
|
(document.body || document.documentElement).appendChild(hyperlink);
|
|
}
|
|
|
|
var evt = new MouseEvent('click', {
|
|
view: window,
|
|
bubbles: true,
|
|
cancelable: true
|
|
});
|
|
|
|
hyperlink.dispatchEvent(evt);
|
|
|
|
if (!navigator.mozGetUserMedia) {
|
|
URL.revokeObjectURL(hyperlink.href);
|
|
}
|
|
}
|
|
|
|
var rmcPort = chrome.runtime.connect({name:'mycontentscript'});
|
|
|
|
function changeIcon(percentage) {
|
|
rmcPort.postMessage({
|
|
changeIcon: true,
|
|
path: true,
|
|
percentage: percentage
|
|
});
|
|
}
|
|
|
|
// socket.io.js
|
|
(function webpackUniversalModuleDefinition(root, factory) {
|
|
if(typeof exports === 'object' && typeof module === 'object')
|
|
module.exports = factory();
|
|
else if(typeof define === 'function' && define.amd)
|
|
define([], factory);
|
|
else if(typeof exports === 'object')
|
|
exports["io"] = factory();
|
|
else
|
|
root["io"] = factory();
|
|
})(this, function() {
|
|
return /******/ (function(modules) { // webpackBootstrap
|
|
/******/ // The module cache
|
|
/******/ var installedModules = {};
|
|
|
|
/******/ // The require function
|
|
/******/ function __webpack_require__(moduleId) {
|
|
|
|
/******/ // Check if module is in cache
|
|
/******/ if(installedModules[moduleId])
|
|
/******/ return installedModules[moduleId].exports;
|
|
|
|
/******/ // Create a new module (and put it into the cache)
|
|
/******/ var module = installedModules[moduleId] = {
|
|
/******/ exports: {},
|
|
/******/ id: moduleId,
|
|
/******/ loaded: false
|
|
/******/ };
|
|
|
|
/******/ // Execute the module function
|
|
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
|
|
|
|
/******/ // Flag the module as loaded
|
|
/******/ module.loaded = true;
|
|
|
|
/******/ // Return the exports of the module
|
|
/******/ return module.exports;
|
|
/******/ }
|
|
|
|
|
|
/******/ // expose the modules object (__webpack_modules__)
|
|
/******/ __webpack_require__.m = modules;
|
|
|
|
/******/ // expose the module cache
|
|
/******/ __webpack_require__.c = installedModules;
|
|
|
|
/******/ // __webpack_public_path__
|
|
/******/ __webpack_require__.p = "";
|
|
|
|
/******/ // Load entry module and return exports
|
|
/******/ return __webpack_require__(0);
|
|
/******/ })
|
|
/************************************************************************/
|
|
/******/ ([
|
|
/* 0 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var url = __webpack_require__(1);
|
|
var parser = __webpack_require__(6);
|
|
var Manager = __webpack_require__(13);
|
|
var debug = __webpack_require__(3)('socket.io-client');
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = exports = lookup;
|
|
|
|
/**
|
|
* Managers cache.
|
|
*/
|
|
|
|
var cache = exports.managers = {};
|
|
|
|
/**
|
|
* Looks up an existing `Manager` for multiplexing.
|
|
* If the user summons:
|
|
*
|
|
* `io('http://localhost/a');`
|
|
* `io('http://localhost/b');`
|
|
*
|
|
* We reuse the existing instance based on same scheme/port/host,
|
|
* and we initialize sockets for each namespace.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function lookup(uri, opts) {
|
|
if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') {
|
|
opts = uri;
|
|
uri = undefined;
|
|
}
|
|
|
|
opts = opts || {};
|
|
|
|
var parsed = url(uri);
|
|
var source = parsed.source;
|
|
var id = parsed.id;
|
|
var path = parsed.path;
|
|
var sameNamespace = cache[id] && path in cache[id].nsps;
|
|
var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace;
|
|
|
|
var io;
|
|
|
|
if (newConnection) {
|
|
debug('ignoring socket cache for %s', source);
|
|
io = Manager(source, opts);
|
|
} else {
|
|
if (!cache[id]) {
|
|
debug('new io instance for %s', source);
|
|
cache[id] = Manager(source, opts);
|
|
}
|
|
io = cache[id];
|
|
}
|
|
if (parsed.query && !opts.query) {
|
|
opts.query = parsed.query;
|
|
} else if (opts && 'object' === _typeof(opts.query)) {
|
|
opts.query = encodeQueryString(opts.query);
|
|
}
|
|
return io.socket(parsed.path, opts);
|
|
}
|
|
/**
|
|
* Helper method to parse query objects to string.
|
|
* @param {object} query
|
|
* @returns {string}
|
|
*/
|
|
function encodeQueryString(obj) {
|
|
var str = [];
|
|
for (var p in obj) {
|
|
if (obj.hasOwnProperty(p)) {
|
|
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
|
|
}
|
|
}
|
|
return str.join('&');
|
|
}
|
|
/**
|
|
* Protocol version.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.protocol = parser.protocol;
|
|
|
|
/**
|
|
* `connect`.
|
|
*
|
|
* @param {String} uri
|
|
* @api public
|
|
*/
|
|
|
|
exports.connect = lookup;
|
|
|
|
/**
|
|
* Expose constructors for standalone build.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.Manager = __webpack_require__(13);
|
|
exports.Socket = __webpack_require__(40);
|
|
|
|
/***/ },
|
|
/* 1 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {'use strict';
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var parseuri = __webpack_require__(2);
|
|
var debug = __webpack_require__(3)('socket.io-client:url');
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = url;
|
|
|
|
/**
|
|
* URL parser.
|
|
*
|
|
* @param {String} url
|
|
* @param {Object} An object meant to mimic window.location.
|
|
* Defaults to window.location.
|
|
* @api public
|
|
*/
|
|
|
|
function url(uri, loc) {
|
|
var obj = uri;
|
|
|
|
// default to window.location
|
|
loc = loc || global.location;
|
|
if (null == uri) uri = loc.protocol + '//' + loc.host;
|
|
|
|
// relative path support
|
|
if ('string' === typeof uri) {
|
|
if ('/' === uri.charAt(0)) {
|
|
if ('/' === uri.charAt(1)) {
|
|
uri = loc.protocol + uri;
|
|
} else {
|
|
uri = loc.host + uri;
|
|
}
|
|
}
|
|
|
|
if (!/^(https?|wss?):\/\//.test(uri)) {
|
|
debug('protocol-less url %s', uri);
|
|
if ('undefined' !== typeof loc) {
|
|
uri = loc.protocol + '//' + uri;
|
|
} else {
|
|
uri = 'https://' + uri;
|
|
}
|
|
}
|
|
|
|
// parse
|
|
debug('parse %s', uri);
|
|
obj = parseuri(uri);
|
|
}
|
|
|
|
// make sure we treat `localhost:80` and `localhost` equally
|
|
if (!obj.port) {
|
|
if (/^(http|ws)$/.test(obj.protocol)) {
|
|
obj.port = '80';
|
|
} else if (/^(http|ws)s$/.test(obj.protocol)) {
|
|
obj.port = '443';
|
|
}
|
|
}
|
|
|
|
obj.path = obj.path || '/';
|
|
|
|
var ipv6 = obj.host.indexOf(':') !== -1;
|
|
var host = ipv6 ? '[' + obj.host + ']' : obj.host;
|
|
|
|
// define unique id
|
|
obj.id = obj.protocol + '://' + host + ':' + obj.port;
|
|
// define href
|
|
obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : ':' + obj.port);
|
|
|
|
return obj;
|
|
}
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 2 */
|
|
/***/ function(module, exports) {
|
|
|
|
/**
|
|
* Parses an URI
|
|
*
|
|
* @author Steven Levithan <stevenlevithan.com> (MIT license)
|
|
* @api private
|
|
*/
|
|
|
|
var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
|
|
|
|
var parts = [
|
|
'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
|
|
];
|
|
|
|
module.exports = function parseuri(str) {
|
|
var src = str,
|
|
b = str.indexOf('['),
|
|
e = str.indexOf(']');
|
|
|
|
if (b != -1 && e != -1) {
|
|
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
|
|
}
|
|
|
|
var m = re.exec(str || ''),
|
|
uri = {},
|
|
i = 14;
|
|
|
|
while (i--) {
|
|
uri[parts[i]] = m[i] || '';
|
|
}
|
|
|
|
if (b != -1 && e != -1) {
|
|
uri.source = src;
|
|
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
|
|
uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
|
|
uri.ipv6uri = true;
|
|
}
|
|
|
|
return uri;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 3 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
|
|
/**
|
|
* This is the web browser implementation of `debug()`.
|
|
*
|
|
* Expose `debug()` as the module.
|
|
*/
|
|
|
|
exports = module.exports = __webpack_require__(4);
|
|
exports.log = log;
|
|
exports.formatArgs = formatArgs;
|
|
exports.save = save;
|
|
exports.load = load;
|
|
exports.useColors = useColors;
|
|
exports.storage = 'undefined' != typeof chrome
|
|
&& 'undefined' != typeof chrome.storage
|
|
? chrome.storage.local
|
|
: localstorage();
|
|
|
|
/**
|
|
* Colors.
|
|
*/
|
|
|
|
exports.colors = [
|
|
'lightseagreen',
|
|
'forestgreen',
|
|
'goldenrod',
|
|
'dodgerblue',
|
|
'darkorchid',
|
|
'crimson'
|
|
];
|
|
|
|
/**
|
|
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
|
|
* and the Firebug extension (any Firefox version) are known
|
|
* to support "%c" CSS customizations.
|
|
*
|
|
* TODO: add a `localStorage` variable to explicitly enable/disable colors
|
|
*/
|
|
|
|
function useColors() {
|
|
// is webkit? http://stackoverflow.com/a/16459606/376773
|
|
return ('WebkitAppearance' in document.documentElement.style) ||
|
|
// is firebug? http://stackoverflow.com/a/398120/376773
|
|
(window.console && (console.firebug || (console.exception && console.table))) ||
|
|
// is firefox >= v31?
|
|
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
|
|
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
|
|
}
|
|
|
|
/**
|
|
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
|
|
*/
|
|
|
|
exports.formatters.j = function(v) {
|
|
return JSON.stringify(v);
|
|
};
|
|
|
|
|
|
/**
|
|
* Colorize log arguments if enabled.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function formatArgs() {
|
|
var args = arguments;
|
|
var useColors = this.useColors;
|
|
|
|
args[0] = (useColors ? '%c' : '')
|
|
+ this.namespace
|
|
+ (useColors ? ' %c' : ' ')
|
|
+ args[0]
|
|
+ (useColors ? '%c ' : ' ')
|
|
+ '+' + exports.humanize(this.diff);
|
|
|
|
if (!useColors) return args;
|
|
|
|
var c = 'color: ' + this.color;
|
|
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
|
|
|
|
// the final "%c" is somewhat tricky, because there could be other
|
|
// arguments passed either before or after the %c, so we need to
|
|
// figure out the correct index to insert the CSS into
|
|
var index = 0;
|
|
var lastC = 0;
|
|
args[0].replace(/%[a-z%]/g, function(match) {
|
|
if ('%%' === match) return;
|
|
index++;
|
|
if ('%c' === match) {
|
|
// we only are interested in the *last* %c
|
|
// (the user may have provided their own)
|
|
lastC = index;
|
|
}
|
|
});
|
|
|
|
args.splice(lastC, 0, c);
|
|
return args;
|
|
}
|
|
|
|
/**
|
|
* Invokes `console.log()` when available.
|
|
* No-op when `console.log` is not a "function".
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function log() {
|
|
// this hackery is required for IE8/9, where
|
|
// the `console.log` function doesn't have 'apply'
|
|
return 'object' === typeof console
|
|
&& console.log
|
|
&& Function.prototype.apply.call(console.log, console, arguments);
|
|
}
|
|
|
|
/**
|
|
* Save `namespaces`.
|
|
*
|
|
* @param {String} namespaces
|
|
* @api private
|
|
*/
|
|
|
|
function save(namespaces) {
|
|
try {
|
|
if (null == namespaces) {
|
|
exports.storage.removeItem('debug');
|
|
} else {
|
|
exports.storage.debug = namespaces;
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
|
|
/**
|
|
* Load `namespaces`.
|
|
*
|
|
* @return {String} returns the previously persisted debug modes
|
|
* @api private
|
|
*/
|
|
|
|
function load() {
|
|
var r;
|
|
try {
|
|
r = exports.storage.debug;
|
|
} catch(e) {}
|
|
return r;
|
|
}
|
|
|
|
/**
|
|
* Enable namespaces listed in `localStorage.debug` initially.
|
|
*/
|
|
|
|
exports.enable(load());
|
|
|
|
/**
|
|
* Localstorage attempts to return the localstorage.
|
|
*
|
|
* This is necessary because safari throws
|
|
* when a user disables cookies/localstorage
|
|
* and you attempt to access it.
|
|
*
|
|
* @return {LocalStorage}
|
|
* @api private
|
|
*/
|
|
|
|
function localstorage(){
|
|
try {
|
|
return window.localStorage;
|
|
} catch (e) {}
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 4 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
|
|
/**
|
|
* This is the common logic for both the Node.js and web browser
|
|
* implementations of `debug()`.
|
|
*
|
|
* Expose `debug()` as the module.
|
|
*/
|
|
|
|
exports = module.exports = debug;
|
|
exports.coerce = coerce;
|
|
exports.disable = disable;
|
|
exports.enable = enable;
|
|
exports.enabled = enabled;
|
|
exports.humanize = __webpack_require__(5);
|
|
|
|
/**
|
|
* The currently active debug mode names, and names to skip.
|
|
*/
|
|
|
|
exports.names = [];
|
|
exports.skips = [];
|
|
|
|
/**
|
|
* Map of special "%n" handling functions, for the debug "format" argument.
|
|
*
|
|
* Valid key names are a single, lowercased letter, i.e. "n".
|
|
*/
|
|
|
|
exports.formatters = {};
|
|
|
|
/**
|
|
* Previously assigned color.
|
|
*/
|
|
|
|
var prevColor = 0;
|
|
|
|
/**
|
|
* Previous log timestamp.
|
|
*/
|
|
|
|
var prevTime;
|
|
|
|
/**
|
|
* Select a color.
|
|
*
|
|
* @return {Number}
|
|
* @api private
|
|
*/
|
|
|
|
function selectColor() {
|
|
return exports.colors[prevColor++ % exports.colors.length];
|
|
}
|
|
|
|
/**
|
|
* Create a debugger with the given `namespace`.
|
|
*
|
|
* @param {String} namespace
|
|
* @return {Function}
|
|
* @api public
|
|
*/
|
|
|
|
function debug(namespace) {
|
|
|
|
// define the `disabled` version
|
|
function disabled() {
|
|
}
|
|
disabled.enabled = false;
|
|
|
|
// define the `enabled` version
|
|
function enabled() {
|
|
|
|
var self = enabled;
|
|
|
|
// set `diff` timestamp
|
|
var curr = +new Date();
|
|
var ms = curr - (prevTime || curr);
|
|
self.diff = ms;
|
|
self.prev = prevTime;
|
|
self.curr = curr;
|
|
prevTime = curr;
|
|
|
|
// add the `color` if not set
|
|
if (null == self.useColors) self.useColors = exports.useColors();
|
|
if (null == self.color && self.useColors) self.color = selectColor();
|
|
|
|
var args = Array.prototype.slice.call(arguments);
|
|
|
|
args[0] = exports.coerce(args[0]);
|
|
|
|
if ('string' !== typeof args[0]) {
|
|
// anything else let's inspect with %o
|
|
args = ['%o'].concat(args);
|
|
}
|
|
|
|
// apply any `formatters` transformations
|
|
var index = 0;
|
|
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
|
|
// if we encounter an escaped % then don't increase the array index
|
|
if (match === '%%') return match;
|
|
index++;
|
|
var formatter = exports.formatters[format];
|
|
if ('function' === typeof formatter) {
|
|
var val = args[index];
|
|
match = formatter.call(self, val);
|
|
|
|
// now we need to remove `args[index]` since it's inlined in the `format`
|
|
args.splice(index, 1);
|
|
index--;
|
|
}
|
|
return match;
|
|
});
|
|
|
|
if ('function' === typeof exports.formatArgs) {
|
|
args = exports.formatArgs.apply(self, args);
|
|
}
|
|
var logFn = enabled.log || exports.log || console.log.bind(console);
|
|
logFn.apply(self, args);
|
|
}
|
|
enabled.enabled = true;
|
|
|
|
var fn = exports.enabled(namespace) ? enabled : disabled;
|
|
|
|
fn.namespace = namespace;
|
|
|
|
return fn;
|
|
}
|
|
|
|
/**
|
|
* Enables a debug mode by namespaces. This can include modes
|
|
* separated by a colon and wildcards.
|
|
*
|
|
* @param {String} namespaces
|
|
* @api public
|
|
*/
|
|
|
|
function enable(namespaces) {
|
|
exports.save(namespaces);
|
|
|
|
var split = (namespaces || '').split(/[\s,]+/);
|
|
var len = split.length;
|
|
|
|
for (var i = 0; i < len; i++) {
|
|
if (!split[i]) continue; // ignore empty strings
|
|
namespaces = split[i].replace(/\*/g, '.*?');
|
|
if (namespaces[0] === '-') {
|
|
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
|
|
} else {
|
|
exports.names.push(new RegExp('^' + namespaces + '$'));
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Disable debug output.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function disable() {
|
|
exports.enable('');
|
|
}
|
|
|
|
/**
|
|
* Returns true if the given mode name is enabled, false otherwise.
|
|
*
|
|
* @param {String} name
|
|
* @return {Boolean}
|
|
* @api public
|
|
*/
|
|
|
|
function enabled(name) {
|
|
var i, len;
|
|
for (i = 0, len = exports.skips.length; i < len; i++) {
|
|
if (exports.skips[i].test(name)) {
|
|
return false;
|
|
}
|
|
}
|
|
for (i = 0, len = exports.names.length; i < len; i++) {
|
|
if (exports.names[i].test(name)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Coerce `val`.
|
|
*
|
|
* @param {Mixed} val
|
|
* @return {Mixed}
|
|
* @api private
|
|
*/
|
|
|
|
function coerce(val) {
|
|
if (val instanceof Error) return val.stack || val.message;
|
|
return val;
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 5 */
|
|
/***/ function(module, exports) {
|
|
|
|
/**
|
|
* Helpers.
|
|
*/
|
|
|
|
var s = 1000;
|
|
var m = s * 60;
|
|
var h = m * 60;
|
|
var d = h * 24;
|
|
var y = d * 365.25;
|
|
|
|
/**
|
|
* Parse or format the given `val`.
|
|
*
|
|
* Options:
|
|
*
|
|
* - `long` verbose formatting [false]
|
|
*
|
|
* @param {String|Number} val
|
|
* @param {Object} options
|
|
* @return {String|Number}
|
|
* @api public
|
|
*/
|
|
|
|
module.exports = function(val, options){
|
|
options = options || {};
|
|
if ('string' == typeof val) return parse(val);
|
|
return options.long
|
|
? long(val)
|
|
: short(val);
|
|
};
|
|
|
|
/**
|
|
* Parse the given `str` and return milliseconds.
|
|
*
|
|
* @param {String} str
|
|
* @return {Number}
|
|
* @api private
|
|
*/
|
|
|
|
function parse(str) {
|
|
str = '' + str;
|
|
if (str.length > 10000) return;
|
|
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
|
|
if (!match) return;
|
|
var n = parseFloat(match[1]);
|
|
var type = (match[2] || 'ms').toLowerCase();
|
|
switch (type) {
|
|
case 'years':
|
|
case 'year':
|
|
case 'yrs':
|
|
case 'yr':
|
|
case 'y':
|
|
return n * y;
|
|
case 'days':
|
|
case 'day':
|
|
case 'd':
|
|
return n * d;
|
|
case 'hours':
|
|
case 'hour':
|
|
case 'hrs':
|
|
case 'hr':
|
|
case 'h':
|
|
return n * h;
|
|
case 'minutes':
|
|
case 'minute':
|
|
case 'mins':
|
|
case 'min':
|
|
case 'm':
|
|
return n * m;
|
|
case 'seconds':
|
|
case 'second':
|
|
case 'secs':
|
|
case 'sec':
|
|
case 's':
|
|
return n * s;
|
|
case 'milliseconds':
|
|
case 'millisecond':
|
|
case 'msecs':
|
|
case 'msec':
|
|
case 'ms':
|
|
return n;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Short format for `ms`.
|
|
*
|
|
* @param {Number} ms
|
|
* @return {String}
|
|
* @api private
|
|
*/
|
|
|
|
function short(ms) {
|
|
if (ms >= d) return Math.round(ms / d) + 'd';
|
|
if (ms >= h) return Math.round(ms / h) + 'h';
|
|
if (ms >= m) return Math.round(ms / m) + 'm';
|
|
if (ms >= s) return Math.round(ms / s) + 's';
|
|
return ms + 'ms';
|
|
}
|
|
|
|
/**
|
|
* Long format for `ms`.
|
|
*
|
|
* @param {Number} ms
|
|
* @return {String}
|
|
* @api private
|
|
*/
|
|
|
|
function long(ms) {
|
|
return plural(ms, d, 'day')
|
|
|| plural(ms, h, 'hour')
|
|
|| plural(ms, m, 'minute')
|
|
|| plural(ms, s, 'second')
|
|
|| ms + ' ms';
|
|
}
|
|
|
|
/**
|
|
* Pluralization helper.
|
|
*/
|
|
|
|
function plural(ms, n, name) {
|
|
if (ms < n) return;
|
|
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
|
|
return Math.ceil(ms / n) + ' ' + name + 's';
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 6 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var debug = __webpack_require__(3)('socket.io-parser');
|
|
var json = __webpack_require__(7);
|
|
var isArray = __webpack_require__(9);
|
|
var Emitter = __webpack_require__(10);
|
|
var binary = __webpack_require__(11);
|
|
var isBuf = __webpack_require__(12);
|
|
|
|
/**
|
|
* Protocol version.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.protocol = 4;
|
|
|
|
/**
|
|
* Packet types.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.types = [
|
|
'CONNECT',
|
|
'DISCONNECT',
|
|
'EVENT',
|
|
'ACK',
|
|
'ERROR',
|
|
'BINARY_EVENT',
|
|
'BINARY_ACK'
|
|
];
|
|
|
|
/**
|
|
* Packet type `connect`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.CONNECT = 0;
|
|
|
|
/**
|
|
* Packet type `disconnect`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.DISCONNECT = 1;
|
|
|
|
/**
|
|
* Packet type `event`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.EVENT = 2;
|
|
|
|
/**
|
|
* Packet type `ack`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.ACK = 3;
|
|
|
|
/**
|
|
* Packet type `error`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.ERROR = 4;
|
|
|
|
/**
|
|
* Packet type 'binary event'
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.BINARY_EVENT = 5;
|
|
|
|
/**
|
|
* Packet type `binary ack`. For acks with binary arguments.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.BINARY_ACK = 6;
|
|
|
|
/**
|
|
* Encoder constructor.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.Encoder = Encoder;
|
|
|
|
/**
|
|
* Decoder constructor.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
exports.Decoder = Decoder;
|
|
|
|
/**
|
|
* A socket.io Encoder instance
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function Encoder() {}
|
|
|
|
/**
|
|
* Encode a packet as a single string if non-binary, or as a
|
|
* buffer sequence, depending on packet type.
|
|
*
|
|
* @param {Object} obj - packet object
|
|
* @param {Function} callback - function to handle encodings (likely engine.write)
|
|
* @return Calls callback with Array of encodings
|
|
* @api public
|
|
*/
|
|
|
|
Encoder.prototype.encode = function(obj, callback){
|
|
debug('encoding packet %j', obj);
|
|
|
|
if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
|
|
encodeAsBinary(obj, callback);
|
|
}
|
|
else {
|
|
var encoding = encodeAsString(obj);
|
|
callback([encoding]);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Encode packet as string.
|
|
*
|
|
* @param {Object} packet
|
|
* @return {String} encoded
|
|
* @api private
|
|
*/
|
|
|
|
function encodeAsString(obj) {
|
|
var str = '';
|
|
var nsp = false;
|
|
|
|
// first is type
|
|
str += obj.type;
|
|
|
|
// attachments if we have them
|
|
if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
|
|
str += obj.attachments;
|
|
str += '-';
|
|
}
|
|
|
|
// if we have a namespace other than `/`
|
|
// we append it followed by a comma `,`
|
|
if (obj.nsp && '/' != obj.nsp) {
|
|
nsp = true;
|
|
str += obj.nsp;
|
|
}
|
|
|
|
// immediately followed by the id
|
|
if (null != obj.id) {
|
|
if (nsp) {
|
|
str += ',';
|
|
nsp = false;
|
|
}
|
|
str += obj.id;
|
|
}
|
|
|
|
// json data
|
|
if (null != obj.data) {
|
|
if (nsp) str += ',';
|
|
str += json.stringify(obj.data);
|
|
}
|
|
|
|
debug('encoded %j as %s', obj, str);
|
|
return str;
|
|
}
|
|
|
|
/**
|
|
* Encode packet as 'buffer sequence' by removing blobs, and
|
|
* deconstructing packet into object with placeholders and
|
|
* a list of buffers.
|
|
*
|
|
* @param {Object} packet
|
|
* @return {Buffer} encoded
|
|
* @api private
|
|
*/
|
|
|
|
function encodeAsBinary(obj, callback) {
|
|
|
|
function writeEncoding(bloblessData) {
|
|
var deconstruction = binary.deconstructPacket(bloblessData);
|
|
var pack = encodeAsString(deconstruction.packet);
|
|
var buffers = deconstruction.buffers;
|
|
|
|
buffers.unshift(pack); // add packet info to beginning of data list
|
|
callback(buffers); // write all the buffers
|
|
}
|
|
|
|
binary.removeBlobs(obj, writeEncoding);
|
|
}
|
|
|
|
/**
|
|
* A socket.io Decoder instance
|
|
*
|
|
* @return {Object} decoder
|
|
* @api public
|
|
*/
|
|
|
|
function Decoder() {
|
|
this.reconstructor = null;
|
|
}
|
|
|
|
/**
|
|
* Mix in `Emitter` with Decoder.
|
|
*/
|
|
|
|
Emitter(Decoder.prototype);
|
|
|
|
/**
|
|
* Decodes an ecoded packet string into packet JSON.
|
|
*
|
|
* @param {String} obj - encoded packet
|
|
* @return {Object} packet
|
|
* @api public
|
|
*/
|
|
|
|
Decoder.prototype.add = function(obj) {
|
|
var packet;
|
|
if ('string' == typeof obj) {
|
|
packet = decodeString(obj);
|
|
if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
|
|
this.reconstructor = new BinaryReconstructor(packet);
|
|
|
|
// no attachments, labeled binary but no binary data to follow
|
|
if (this.reconstructor.reconPack.attachments === 0) {
|
|
this.emit('decoded', packet);
|
|
}
|
|
} else { // non-binary full packet
|
|
this.emit('decoded', packet);
|
|
}
|
|
}
|
|
else if (isBuf(obj) || obj.base64) { // raw binary data
|
|
if (!this.reconstructor) {
|
|
throw new Error('got binary data when not reconstructing a packet');
|
|
} else {
|
|
packet = this.reconstructor.takeBinaryData(obj);
|
|
if (packet) { // received final buffer
|
|
this.reconstructor = null;
|
|
this.emit('decoded', packet);
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
throw new Error('Unknown type: ' + obj);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Decode a packet String (JSON data)
|
|
*
|
|
* @param {String} str
|
|
* @return {Object} packet
|
|
* @api private
|
|
*/
|
|
|
|
function decodeString(str) {
|
|
var p = {};
|
|
var i = 0;
|
|
|
|
// look up type
|
|
p.type = Number(str.charAt(0));
|
|
if (null == exports.types[p.type]) return error();
|
|
|
|
// look up attachments if type binary
|
|
if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
|
|
var buf = '';
|
|
while (str.charAt(++i) != '-') {
|
|
buf += str.charAt(i);
|
|
if (i == str.length) break;
|
|
}
|
|
if (buf != Number(buf) || str.charAt(i) != '-') {
|
|
throw new Error('Illegal attachments');
|
|
}
|
|
p.attachments = Number(buf);
|
|
}
|
|
|
|
// look up namespace (if any)
|
|
if ('/' == str.charAt(i + 1)) {
|
|
p.nsp = '';
|
|
while (++i) {
|
|
var c = str.charAt(i);
|
|
if (',' == c) break;
|
|
p.nsp += c;
|
|
if (i == str.length) break;
|
|
}
|
|
} else {
|
|
p.nsp = '/';
|
|
}
|
|
|
|
// look up id
|
|
var next = str.charAt(i + 1);
|
|
if ('' !== next && Number(next) == next) {
|
|
p.id = '';
|
|
while (++i) {
|
|
var c = str.charAt(i);
|
|
if (null == c || Number(c) != c) {
|
|
--i;
|
|
break;
|
|
}
|
|
p.id += str.charAt(i);
|
|
if (i == str.length) break;
|
|
}
|
|
p.id = Number(p.id);
|
|
}
|
|
|
|
// look up json data
|
|
if (str.charAt(++i)) {
|
|
try {
|
|
p.data = json.parse(str.substr(i));
|
|
} catch(e){
|
|
return error();
|
|
}
|
|
}
|
|
|
|
debug('decoded %s as %j', str, p);
|
|
return p;
|
|
}
|
|
|
|
/**
|
|
* Deallocates a parser's resources
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Decoder.prototype.destroy = function() {
|
|
if (this.reconstructor) {
|
|
this.reconstructor.finishedReconstruction();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* A manager of a binary event's 'buffer sequence'. Should
|
|
* be constructed whenever a packet of type BINARY_EVENT is
|
|
* decoded.
|
|
*
|
|
* @param {Object} packet
|
|
* @return {BinaryReconstructor} initialized reconstructor
|
|
* @api private
|
|
*/
|
|
|
|
function BinaryReconstructor(packet) {
|
|
this.reconPack = packet;
|
|
this.buffers = [];
|
|
}
|
|
|
|
/**
|
|
* Method to be called when binary data received from connection
|
|
* after a BINARY_EVENT packet.
|
|
*
|
|
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
|
|
* @return {null | Object} returns null if more binary data is expected or
|
|
* a reconstructed packet object if all buffers have been received.
|
|
* @api private
|
|
*/
|
|
|
|
BinaryReconstructor.prototype.takeBinaryData = function(binData) {
|
|
this.buffers.push(binData);
|
|
if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
|
|
var packet = binary.reconstructPacket(this.reconPack, this.buffers);
|
|
this.finishedReconstruction();
|
|
return packet;
|
|
}
|
|
return null;
|
|
};
|
|
|
|
/**
|
|
* Cleans up binary packet reconstruction variables.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
BinaryReconstructor.prototype.finishedReconstruction = function() {
|
|
this.reconPack = null;
|
|
this.buffers = [];
|
|
};
|
|
|
|
function error(data){
|
|
return {
|
|
type: exports.ERROR,
|
|
data: 'parser error'
|
|
};
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 7 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(module, global) {/*** IMPORTS FROM imports-loader ***/
|
|
var define = false;
|
|
|
|
/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
|
|
;(function () {
|
|
// Detect the `define` function exposed by asynchronous module loaders. The
|
|
// strict `define` check is necessary for compatibility with `r.js`.
|
|
var isLoader = typeof define === "function" && define.amd;
|
|
|
|
// A set of types used to distinguish objects from primitives.
|
|
var objectTypes = {
|
|
"function": true,
|
|
"object": true
|
|
};
|
|
|
|
// Detect the `exports` object exposed by CommonJS implementations.
|
|
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
|
|
|
|
// Use the `global` object exposed by Node (including Browserify via
|
|
// `insert-module-globals`), Narwhal, and Ringo as the default context,
|
|
// and the `window` object in browsers. Rhino exports a `global` function
|
|
// instead.
|
|
var root = objectTypes[typeof window] && window || this,
|
|
freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
|
|
|
|
if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
|
|
root = freeGlobal;
|
|
}
|
|
|
|
// Public: Initializes JSON 3 using the given `context` object, attaching the
|
|
// `stringify` and `parse` functions to the specified `exports` object.
|
|
function runInContext(context, exports) {
|
|
context || (context = root["Object"]());
|
|
exports || (exports = root["Object"]());
|
|
|
|
// Native constructor aliases.
|
|
var Number = context["Number"] || root["Number"],
|
|
String = context["String"] || root["String"],
|
|
Object = context["Object"] || root["Object"],
|
|
Date = context["Date"] || root["Date"],
|
|
SyntaxError = context["SyntaxError"] || root["SyntaxError"],
|
|
TypeError = context["TypeError"] || root["TypeError"],
|
|
Math = context["Math"] || root["Math"],
|
|
nativeJSON = context["JSON"] || root["JSON"];
|
|
|
|
// Delegate to the native `stringify` and `parse` implementations.
|
|
if (typeof nativeJSON == "object" && nativeJSON) {
|
|
exports.stringify = nativeJSON.stringify;
|
|
exports.parse = nativeJSON.parse;
|
|
}
|
|
|
|
// Convenience aliases.
|
|
var objectProto = Object.prototype,
|
|
getClass = objectProto.toString,
|
|
isProperty, forEach, undef;
|
|
|
|
// Test the `Date#getUTC*` methods. Based on work by @Yaffle.
|
|
var isExtended = new Date(-3509827334573292);
|
|
try {
|
|
// The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
|
|
// results for certain dates in Opera >= 10.53.
|
|
isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
|
|
// Safari < 2.0.2 stores the internal millisecond time value correctly,
|
|
// but clips the values returned by the date methods to the range of
|
|
// signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
|
|
isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
|
|
} catch (exception) {}
|
|
|
|
// Internal: Determines whether the native `JSON.stringify` and `parse`
|
|
// implementations are spec-compliant. Based on work by Ken Snyder.
|
|
function has(name) {
|
|
if (has[name] !== undef) {
|
|
// Return cached feature test result.
|
|
return has[name];
|
|
}
|
|
var isSupported;
|
|
if (name == "bug-string-char-index") {
|
|
// IE <= 7 doesn't support accessing string characters using square
|
|
// bracket notation. IE 8 only supports this for primitives.
|
|
isSupported = "a"[0] != "a";
|
|
} else if (name == "json") {
|
|
// Indicates whether both `JSON.stringify` and `JSON.parse` are
|
|
// supported.
|
|
isSupported = has("json-stringify") && has("json-parse");
|
|
} else {
|
|
var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
|
|
// Test `JSON.stringify`.
|
|
if (name == "json-stringify") {
|
|
var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
|
|
if (stringifySupported) {
|
|
// A test function object with a custom `toJSON` method.
|
|
(value = function () {
|
|
return 1;
|
|
}).toJSON = value;
|
|
try {
|
|
stringifySupported =
|
|
// Firefox 3.1b1 and b2 serialize string, number, and boolean
|
|
// primitives as object literals.
|
|
stringify(0) === "0" &&
|
|
// FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
|
|
// literals.
|
|
stringify(new Number()) === "0" &&
|
|
stringify(new String()) == '""' &&
|
|
// FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
|
|
// does not define a canonical JSON representation (this applies to
|
|
// objects with `toJSON` properties as well, *unless* they are nested
|
|
// within an object or array).
|
|
stringify(getClass) === undef &&
|
|
// IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
|
|
// FF 3.1b3 pass this test.
|
|
stringify(undef) === undef &&
|
|
// Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
|
|
// respectively, if the value is omitted entirely.
|
|
stringify() === undef &&
|
|
// FF 3.1b1, 2 throw an error if the given value is not a number,
|
|
// string, array, object, Boolean, or `null` literal. This applies to
|
|
// objects with custom `toJSON` methods as well, unless they are nested
|
|
// inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
|
|
// methods entirely.
|
|
stringify(value) === "1" &&
|
|
stringify([value]) == "[1]" &&
|
|
// Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
|
|
// `"[null]"`.
|
|
stringify([undef]) == "[null]" &&
|
|
// YUI 3.0.0b1 fails to serialize `null` literals.
|
|
stringify(null) == "null" &&
|
|
// FF 3.1b1, 2 halts serialization if an array contains a function:
|
|
// `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
|
|
// elides non-JSON values from objects and arrays, unless they
|
|
// define custom `toJSON` methods.
|
|
stringify([undef, getClass, null]) == "[null,null,null]" &&
|
|
// Simple serialization test. FF 3.1b1 uses Unicode escape sequences
|
|
// where character escape codes are expected (e.g., `\b` => `\u0008`).
|
|
stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
|
|
// FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
|
|
stringify(null, value) === "1" &&
|
|
stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
|
|
// JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
|
|
// serialize extended years.
|
|
stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
|
|
// The milliseconds are optional in ES 5, but required in 5.1.
|
|
stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
|
|
// Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
|
|
// four-digit years instead of six-digit years. Credits: @Yaffle.
|
|
stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
|
|
// Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
|
|
// values less than 1000. Credits: @Yaffle.
|
|
stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
|
|
} catch (exception) {
|
|
stringifySupported = false;
|
|
}
|
|
}
|
|
isSupported = stringifySupported;
|
|
}
|
|
// Test `JSON.parse`.
|
|
if (name == "json-parse") {
|
|
var parse = exports.parse;
|
|
if (typeof parse == "function") {
|
|
try {
|
|
// FF 3.1b1, b2 will throw an exception if a bare literal is provided.
|
|
// Conforming implementations should also coerce the initial argument to
|
|
// a string prior to parsing.
|
|
if (parse("0") === 0 && !parse(false)) {
|
|
// Simple parsing test.
|
|
value = parse(serialized);
|
|
var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
|
|
if (parseSupported) {
|
|
try {
|
|
// Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
|
|
parseSupported = !parse('"\t"');
|
|
} catch (exception) {}
|
|
if (parseSupported) {
|
|
try {
|
|
// FF 4.0 and 4.0.1 allow leading `+` signs and leading
|
|
// decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
|
|
// certain octal literals.
|
|
parseSupported = parse("01") !== 1;
|
|
} catch (exception) {}
|
|
}
|
|
if (parseSupported) {
|
|
try {
|
|
// FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
|
|
// points. These environments, along with FF 3.1b1 and 2,
|
|
// also allow trailing commas in JSON objects and arrays.
|
|
parseSupported = parse("1.") !== 1;
|
|
} catch (exception) {}
|
|
}
|
|
}
|
|
}
|
|
} catch (exception) {
|
|
parseSupported = false;
|
|
}
|
|
}
|
|
isSupported = parseSupported;
|
|
}
|
|
}
|
|
return has[name] = !!isSupported;
|
|
}
|
|
|
|
if (!has("json")) {
|
|
// Common `[[Class]]` name aliases.
|
|
var functionClass = "[object Function]",
|
|
dateClass = "[object Date]",
|
|
numberClass = "[object Number]",
|
|
stringClass = "[object String]",
|
|
arrayClass = "[object Array]",
|
|
booleanClass = "[object Boolean]";
|
|
|
|
// Detect incomplete support for accessing string characters by index.
|
|
var charIndexBuggy = has("bug-string-char-index");
|
|
|
|
// Define additional utility methods if the `Date` methods are buggy.
|
|
if (!isExtended) {
|
|
var floor = Math.floor;
|
|
// A mapping between the months of the year and the number of days between
|
|
// January 1st and the first of the respective month.
|
|
var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
|
|
// Internal: Calculates the number of days between the Unix epoch and the
|
|
// first day of the given month.
|
|
var getDay = function (year, month) {
|
|
return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
|
|
};
|
|
}
|
|
|
|
// Internal: Determines if a property is a direct property of the given
|
|
// object. Delegates to the native `Object#hasOwnProperty` method.
|
|
if (!(isProperty = objectProto.hasOwnProperty)) {
|
|
isProperty = function (property) {
|
|
var members = {}, constructor;
|
|
if ((members.__proto__ = null, members.__proto__ = {
|
|
// The *proto* property cannot be set multiple times in recent
|
|
// versions of Firefox and SeaMonkey.
|
|
"toString": 1
|
|
}, members).toString != getClass) {
|
|
// Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
|
|
// supports the mutable *proto* property.
|
|
isProperty = function (property) {
|
|
// Capture and break the object's prototype chain (see section 8.6.2
|
|
// of the ES 5.1 spec). The parenthesized expression prevents an
|
|
// unsafe transformation by the Closure Compiler.
|
|
var original = this.__proto__, result = property in (this.__proto__ = null, this);
|
|
// Restore the original prototype chain.
|
|
this.__proto__ = original;
|
|
return result;
|
|
};
|
|
} else {
|
|
// Capture a reference to the top-level `Object` constructor.
|
|
constructor = members.constructor;
|
|
// Use the `constructor` property to simulate `Object#hasOwnProperty` in
|
|
// other environments.
|
|
isProperty = function (property) {
|
|
var parent = (this.constructor || constructor).prototype;
|
|
return property in this && !(property in parent && this[property] === parent[property]);
|
|
};
|
|
}
|
|
members = null;
|
|
return isProperty.call(this, property);
|
|
};
|
|
}
|
|
|
|
// Internal: Normalizes the `for...in` iteration algorithm across
|
|
// environments. Each enumerated key is yielded to a `callback` function.
|
|
forEach = function (object, callback) {
|
|
var size = 0, Properties, members, property;
|
|
|
|
// Tests for bugs in the current environment's `for...in` algorithm. The
|
|
// `valueOf` property inherits the non-enumerable flag from
|
|
// `Object.prototype` in older versions of IE, Netscape, and Mozilla.
|
|
(Properties = function () {
|
|
this.valueOf = 0;
|
|
}).prototype.valueOf = 0;
|
|
|
|
// Iterate over a new instance of the `Properties` class.
|
|
members = new Properties();
|
|
for (property in members) {
|
|
// Ignore all properties inherited from `Object.prototype`.
|
|
if (isProperty.call(members, property)) {
|
|
size++;
|
|
}
|
|
}
|
|
Properties = members = null;
|
|
|
|
// Normalize the iteration algorithm.
|
|
if (!size) {
|
|
// A list of non-enumerable properties inherited from `Object.prototype`.
|
|
members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
|
|
// IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
|
|
// properties.
|
|
forEach = function (object, callback) {
|
|
var isFunction = getClass.call(object) == functionClass, property, length;
|
|
var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
|
|
for (property in object) {
|
|
// Gecko <= 1.0 enumerates the `prototype` property of functions under
|
|
// certain conditions; IE does not.
|
|
if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
|
|
callback(property);
|
|
}
|
|
}
|
|
// Manually invoke the callback for each non-enumerable property.
|
|
for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
|
|
};
|
|
} else if (size == 2) {
|
|
// Safari <= 2.0.4 enumerates shadowed properties twice.
|
|
forEach = function (object, callback) {
|
|
// Create a set of iterated properties.
|
|
var members = {}, isFunction = getClass.call(object) == functionClass, property;
|
|
for (property in object) {
|
|
// Store each property name to prevent double enumeration. The
|
|
// `prototype` property of functions is not enumerated due to cross-
|
|
// environment inconsistencies.
|
|
if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
|
|
callback(property);
|
|
}
|
|
}
|
|
};
|
|
} else {
|
|
// No bugs detected; use the standard `for...in` algorithm.
|
|
forEach = function (object, callback) {
|
|
var isFunction = getClass.call(object) == functionClass, property, isConstructor;
|
|
for (property in object) {
|
|
if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
|
|
callback(property);
|
|
}
|
|
}
|
|
// Manually invoke the callback for the `constructor` property due to
|
|
// cross-environment inconsistencies.
|
|
if (isConstructor || isProperty.call(object, (property = "constructor"))) {
|
|
callback(property);
|
|
}
|
|
};
|
|
}
|
|
return forEach(object, callback);
|
|
};
|
|
|
|
// Public: Serializes a JavaScript `value` as a JSON string. The optional
|
|
// `filter` argument may specify either a function that alters how object and
|
|
// array members are serialized, or an array of strings and numbers that
|
|
// indicates which properties should be serialized. The optional `width`
|
|
// argument may be either a string or number that specifies the indentation
|
|
// level of the output.
|
|
if (!has("json-stringify")) {
|
|
// Internal: A map of control characters and their escaped equivalents.
|
|
var Escapes = {
|
|
92: "\\\\",
|
|
34: '\\"',
|
|
8: "\\b",
|
|
12: "\\f",
|
|
10: "\\n",
|
|
13: "\\r",
|
|
9: "\\t"
|
|
};
|
|
|
|
// Internal: Converts `value` into a zero-padded string such that its
|
|
// length is at least equal to `width`. The `width` must be <= 6.
|
|
var leadingZeroes = "000000";
|
|
var toPaddedString = function (width, value) {
|
|
// The `|| 0` expression is necessary to work around a bug in
|
|
// Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
|
|
return (leadingZeroes + (value || 0)).slice(-width);
|
|
};
|
|
|
|
// Internal: Double-quotes a string `value`, replacing all ASCII control
|
|
// characters (characters with code unit values between 0 and 31) with
|
|
// their escaped equivalents. This is an implementation of the
|
|
// `Quote(value)` operation defined in ES 5.1 section 15.12.3.
|
|
var unicodePrefix = "\\u00";
|
|
var quote = function (value) {
|
|
var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
|
|
var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
|
|
for (; index < length; index++) {
|
|
var charCode = value.charCodeAt(index);
|
|
// If the character is a control character, append its Unicode or
|
|
// shorthand escape sequence; otherwise, append the character as-is.
|
|
switch (charCode) {
|
|
case 8: case 9: case 10: case 12: case 13: case 34: case 92:
|
|
result += Escapes[charCode];
|
|
break;
|
|
default:
|
|
if (charCode < 32) {
|
|
result += unicodePrefix + toPaddedString(2, charCode.toString(16));
|
|
break;
|
|
}
|
|
result += useCharIndex ? symbols[index] : value.charAt(index);
|
|
}
|
|
}
|
|
return result + '"';
|
|
};
|
|
|
|
// Internal: Recursively serializes an object. Implements the
|
|
// `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
|
|
var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
|
|
var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
|
|
try {
|
|
// Necessary for host object support.
|
|
value = object[property];
|
|
} catch (exception) {}
|
|
if (typeof value == "object" && value) {
|
|
className = getClass.call(value);
|
|
if (className == dateClass && !isProperty.call(value, "toJSON")) {
|
|
if (value > -1 / 0 && value < 1 / 0) {
|
|
// Dates are serialized according to the `Date#toJSON` method
|
|
// specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
|
|
// for the ISO 8601 date time string format.
|
|
if (getDay) {
|
|
// Manually compute the year, month, date, hours, minutes,
|
|
// seconds, and milliseconds if the `getUTC*` methods are
|
|
// buggy. Adapted from @Yaffle's `date-shim` project.
|
|
date = floor(value / 864e5);
|
|
for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
|
|
for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
|
|
date = 1 + date - getDay(year, month);
|
|
// The `time` value specifies the time within the day (see ES
|
|
// 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
|
|
// to compute `A modulo B`, as the `%` operator does not
|
|
// correspond to the `modulo` operation for negative numbers.
|
|
time = (value % 864e5 + 864e5) % 864e5;
|
|
// The hours, minutes, seconds, and milliseconds are obtained by
|
|
// decomposing the time within the day. See section 15.9.1.10.
|
|
hours = floor(time / 36e5) % 24;
|
|
minutes = floor(time / 6e4) % 60;
|
|
seconds = floor(time / 1e3) % 60;
|
|
milliseconds = time % 1e3;
|
|
} else {
|
|
year = value.getUTCFullYear();
|
|
month = value.getUTCMonth();
|
|
date = value.getUTCDate();
|
|
hours = value.getUTCHours();
|
|
minutes = value.getUTCMinutes();
|
|
seconds = value.getUTCSeconds();
|
|
milliseconds = value.getUTCMilliseconds();
|
|
}
|
|
// Serialize extended years correctly.
|
|
value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
|
|
"-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
|
|
// Months, dates, hours, minutes, and seconds should have two
|
|
// digits; milliseconds should have three.
|
|
"T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
|
|
// Milliseconds are optional in ES 5.0, but required in 5.1.
|
|
"." + toPaddedString(3, milliseconds) + "Z";
|
|
} else {
|
|
value = null;
|
|
}
|
|
} else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
|
|
// Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
|
|
// `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
|
|
// ignores all `toJSON` methods on these objects unless they are
|
|
// defined directly on an instance.
|
|
value = value.toJSON(property);
|
|
}
|
|
}
|
|
if (callback) {
|
|
// If a replacement function was provided, call it to obtain the value
|
|
// for serialization.
|
|
value = callback.call(object, property, value);
|
|
}
|
|
if (value === null) {
|
|
return "null";
|
|
}
|
|
className = getClass.call(value);
|
|
if (className == booleanClass) {
|
|
// Booleans are represented literally.
|
|
return "" + value;
|
|
} else if (className == numberClass) {
|
|
// JSON numbers must be finite. `Infinity` and `NaN` are serialized as
|
|
// `"null"`.
|
|
return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
|
|
} else if (className == stringClass) {
|
|
// Strings are double-quoted and escaped.
|
|
return quote("" + value);
|
|
}
|
|
// Recursively serialize objects and arrays.
|
|
if (typeof value == "object") {
|
|
// Check for cyclic structures. This is a linear search; performance
|
|
// is inversely proportional to the number of unique nested objects.
|
|
for (length = stack.length; length--;) {
|
|
if (stack[length] === value) {
|
|
// Cyclic structures cannot be serialized by `JSON.stringify`.
|
|
throw TypeError();
|
|
}
|
|
}
|
|
// Add the object to the stack of traversed objects.
|
|
stack.push(value);
|
|
results = [];
|
|
// Save the current indentation level and indent one additional level.
|
|
prefix = indentation;
|
|
indentation += whitespace;
|
|
if (className == arrayClass) {
|
|
// Recursively serialize array elements.
|
|
for (index = 0, length = value.length; index < length; index++) {
|
|
element = serialize(index, value, callback, properties, whitespace, indentation, stack);
|
|
results.push(element === undef ? "null" : element);
|
|
}
|
|
result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
|
|
} else {
|
|
// Recursively serialize object members. Members are selected from
|
|
// either a user-specified list of property names, or the object
|
|
// itself.
|
|
forEach(properties || value, function (property) {
|
|
var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
|
|
if (element !== undef) {
|
|
// According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
|
|
// is not the empty string, let `member` {quote(property) + ":"}
|
|
// be the concatenation of `member` and the `space` character."
|
|
// The "`space` character" refers to the literal space
|
|
// character, not the `space` {width} argument provided to
|
|
// `JSON.stringify`.
|
|
results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
|
|
}
|
|
});
|
|
result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
|
|
}
|
|
// Remove the object from the traversed object stack.
|
|
stack.pop();
|
|
return result;
|
|
}
|
|
};
|
|
|
|
// Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
|
|
exports.stringify = function (source, filter, width) {
|
|
var whitespace, callback, properties, className;
|
|
if (objectTypes[typeof filter] && filter) {
|
|
if ((className = getClass.call(filter)) == functionClass) {
|
|
callback = filter;
|
|
} else if (className == arrayClass) {
|
|
// Convert the property names array into a makeshift set.
|
|
properties = {};
|
|
for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
|
|
}
|
|
}
|
|
if (width) {
|
|
if ((className = getClass.call(width)) == numberClass) {
|
|
// Convert the `width` to an integer and create a string containing
|
|
// `width` number of space characters.
|
|
if ((width -= width % 1) > 0) {
|
|
for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
|
|
}
|
|
} else if (className == stringClass) {
|
|
whitespace = width.length <= 10 ? width : width.slice(0, 10);
|
|
}
|
|
}
|
|
// Opera <= 7.54u2 discards the values associated with empty string keys
|
|
// (`""`) only if they are used directly within an object member list
|
|
// (e.g., `!("" in { "": 1})`).
|
|
return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
|
|
};
|
|
}
|
|
|
|
// Public: Parses a JSON source string.
|
|
if (!has("json-parse")) {
|
|
var fromCharCode = String.fromCharCode;
|
|
|
|
// Internal: A map of escaped control characters and their unescaped
|
|
// equivalents.
|
|
var Unescapes = {
|
|
92: "\\",
|
|
34: '"',
|
|
47: "/",
|
|
98: "\b",
|
|
116: "\t",
|
|
110: "\n",
|
|
102: "\f",
|
|
114: "\r"
|
|
};
|
|
|
|
// Internal: Stores the parser state.
|
|
var Index, Source;
|
|
|
|
// Internal: Resets the parser state and throws a `SyntaxError`.
|
|
var abort = function () {
|
|
Index = Source = null;
|
|
throw SyntaxError();
|
|
};
|
|
|
|
// Internal: Returns the next token, or `"$"` if the parser has reached
|
|
// the end of the source string. A token may be a string, number, `null`
|
|
// literal, or Boolean literal.
|
|
var lex = function () {
|
|
var source = Source, length = source.length, value, begin, position, isSigned, charCode;
|
|
while (Index < length) {
|
|
charCode = source.charCodeAt(Index);
|
|
switch (charCode) {
|
|
case 9: case 10: case 13: case 32:
|
|
// Skip whitespace tokens, including tabs, carriage returns, line
|
|
// feeds, and space characters.
|
|
Index++;
|
|
break;
|
|
case 123: case 125: case 91: case 93: case 58: case 44:
|
|
// Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
|
|
// the current position.
|
|
value = charIndexBuggy ? source.charAt(Index) : source[Index];
|
|
Index++;
|
|
return value;
|
|
case 34:
|
|
// `"` delimits a JSON string; advance to the next character and
|
|
// begin parsing the string. String tokens are prefixed with the
|
|
// sentinel `@` character to distinguish them from punctuators and
|
|
// end-of-string tokens.
|
|
for (value = "@", Index++; Index < length;) {
|
|
charCode = source.charCodeAt(Index);
|
|
if (charCode < 32) {
|
|
// Unescaped ASCII control characters (those with a code unit
|
|
// less than the space character) are not permitted.
|
|
abort();
|
|
} else if (charCode == 92) {
|
|
// A reverse solidus (`\`) marks the beginning of an escaped
|
|
// control character (including `"`, `\`, and `/`) or Unicode
|
|
// escape sequence.
|
|
charCode = source.charCodeAt(++Index);
|
|
switch (charCode) {
|
|
case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
|
|
// Revive escaped control characters.
|
|
value += Unescapes[charCode];
|
|
Index++;
|
|
break;
|
|
case 117:
|
|
// `\u` marks the beginning of a Unicode escape sequence.
|
|
// Advance to the first character and validate the
|
|
// four-digit code point.
|
|
begin = ++Index;
|
|
for (position = Index + 4; Index < position; Index++) {
|
|
charCode = source.charCodeAt(Index);
|
|
// A valid sequence comprises four hexdigits (case-
|
|
// insensitive) that form a single hexadecimal value.
|
|
if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
|
|
// Invalid Unicode escape sequence.
|
|
abort();
|
|
}
|
|
}
|
|
// Revive the escaped character.
|
|
value += fromCharCode("0x" + source.slice(begin, Index));
|
|
break;
|
|
default:
|
|
// Invalid escape sequence.
|
|
abort();
|
|
}
|
|
} else {
|
|
if (charCode == 34) {
|
|
// An unescaped double-quote character marks the end of the
|
|
// string.
|
|
break;
|
|
}
|
|
charCode = source.charCodeAt(Index);
|
|
begin = Index;
|
|
// Optimize for the common case where a string is valid.
|
|
while (charCode >= 32 && charCode != 92 && charCode != 34) {
|
|
charCode = source.charCodeAt(++Index);
|
|
}
|
|
// Append the string as-is.
|
|
value += source.slice(begin, Index);
|
|
}
|
|
}
|
|
if (source.charCodeAt(Index) == 34) {
|
|
// Advance to the next character and return the revived string.
|
|
Index++;
|
|
return value;
|
|
}
|
|
// Unterminated string.
|
|
abort();
|
|
default:
|
|
// Parse numbers and literals.
|
|
begin = Index;
|
|
// Advance past the negative sign, if one is specified.
|
|
if (charCode == 45) {
|
|
isSigned = true;
|
|
charCode = source.charCodeAt(++Index);
|
|
}
|
|
// Parse an integer or floating-point value.
|
|
if (charCode >= 48 && charCode <= 57) {
|
|
// Leading zeroes are interpreted as octal literals.
|
|
if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
|
|
// Illegal octal literal.
|
|
abort();
|
|
}
|
|
isSigned = false;
|
|
// Parse the integer component.
|
|
for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
|
|
// Floats cannot contain a leading decimal point; however, this
|
|
// case is already accounted for by the parser.
|
|
if (source.charCodeAt(Index) == 46) {
|
|
position = ++Index;
|
|
// Parse the decimal component.
|
|
for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
|
|
if (position == Index) {
|
|
// Illegal trailing decimal.
|
|
abort();
|
|
}
|
|
Index = position;
|
|
}
|
|
// Parse exponents. The `e` denoting the exponent is
|
|
// case-insensitive.
|
|
charCode = source.charCodeAt(Index);
|
|
if (charCode == 101 || charCode == 69) {
|
|
charCode = source.charCodeAt(++Index);
|
|
// Skip past the sign following the exponent, if one is
|
|
// specified.
|
|
if (charCode == 43 || charCode == 45) {
|
|
Index++;
|
|
}
|
|
// Parse the exponential component.
|
|
for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
|
|
if (position == Index) {
|
|
// Illegal empty exponent.
|
|
abort();
|
|
}
|
|
Index = position;
|
|
}
|
|
// Coerce the parsed value to a JavaScript number.
|
|
return +source.slice(begin, Index);
|
|
}
|
|
// A negative sign may only precede numbers.
|
|
if (isSigned) {
|
|
abort();
|
|
}
|
|
// `true`, `false`, and `null` literals.
|
|
if (source.slice(Index, Index + 4) == "true") {
|
|
Index += 4;
|
|
return true;
|
|
} else if (source.slice(Index, Index + 5) == "false") {
|
|
Index += 5;
|
|
return false;
|
|
} else if (source.slice(Index, Index + 4) == "null") {
|
|
Index += 4;
|
|
return null;
|
|
}
|
|
// Unrecognized token.
|
|
abort();
|
|
}
|
|
}
|
|
// Return the sentinel `$` character if the parser has reached the end
|
|
// of the source string.
|
|
return "$";
|
|
};
|
|
|
|
// Internal: Parses a JSON `value` token.
|
|
var get = function (value) {
|
|
var results, hasMembers;
|
|
if (value == "$") {
|
|
// Unexpected end of input.
|
|
abort();
|
|
}
|
|
if (typeof value == "string") {
|
|
if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
|
|
// Remove the sentinel `@` character.
|
|
return value.slice(1);
|
|
}
|
|
// Parse object and array literals.
|
|
if (value == "[") {
|
|
// Parses a JSON array, returning a new JavaScript array.
|
|
results = [];
|
|
for (;; hasMembers || (hasMembers = true)) {
|
|
value = lex();
|
|
// A closing square bracket marks the end of the array literal.
|
|
if (value == "]") {
|
|
break;
|
|
}
|
|
// If the array literal contains elements, the current token
|
|
// should be a comma separating the previous element from the
|
|
// next.
|
|
if (hasMembers) {
|
|
if (value == ",") {
|
|
value = lex();
|
|
if (value == "]") {
|
|
// Unexpected trailing `,` in array literal.
|
|
abort();
|
|
}
|
|
} else {
|
|
// A `,` must separate each array element.
|
|
abort();
|
|
}
|
|
}
|
|
// Elisions and leading commas are not permitted.
|
|
if (value == ",") {
|
|
abort();
|
|
}
|
|
results.push(get(value));
|
|
}
|
|
return results;
|
|
} else if (value == "{") {
|
|
// Parses a JSON object, returning a new JavaScript object.
|
|
results = {};
|
|
for (;; hasMembers || (hasMembers = true)) {
|
|
value = lex();
|
|
// A closing curly brace marks the end of the object literal.
|
|
if (value == "}") {
|
|
break;
|
|
}
|
|
// If the object literal contains members, the current token
|
|
// should be a comma separator.
|
|
if (hasMembers) {
|
|
if (value == ",") {
|
|
value = lex();
|
|
if (value == "}") {
|
|
// Unexpected trailing `,` in object literal.
|
|
abort();
|
|
}
|
|
} else {
|
|
// A `,` must separate each object member.
|
|
abort();
|
|
}
|
|
}
|
|
// Leading commas are not permitted, object property names must be
|
|
// double-quoted strings, and a `:` must separate each property
|
|
// name and value.
|
|
if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
|
|
abort();
|
|
}
|
|
results[value.slice(1)] = get(lex());
|
|
}
|
|
return results;
|
|
}
|
|
// Unexpected token encountered.
|
|
abort();
|
|
}
|
|
return value;
|
|
};
|
|
|
|
// Internal: Updates a traversed object member.
|
|
var update = function (source, property, callback) {
|
|
var element = walk(source, property, callback);
|
|
if (element === undef) {
|
|
delete source[property];
|
|
} else {
|
|
source[property] = element;
|
|
}
|
|
};
|
|
|
|
// Internal: Recursively traverses a parsed JSON object, invoking the
|
|
// `callback` function for each value. This is an implementation of the
|
|
// `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
|
|
var walk = function (source, property, callback) {
|
|
var value = source[property], length;
|
|
if (typeof value == "object" && value) {
|
|
// `forEach` can't be used to traverse an array in Opera <= 8.54
|
|
// because its `Object#hasOwnProperty` implementation returns `false`
|
|
// for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
|
|
if (getClass.call(value) == arrayClass) {
|
|
for (length = value.length; length--;) {
|
|
update(value, length, callback);
|
|
}
|
|
} else {
|
|
forEach(value, function (property) {
|
|
update(value, property, callback);
|
|
});
|
|
}
|
|
}
|
|
return callback.call(source, property, value);
|
|
};
|
|
|
|
// Public: `JSON.parse`. See ES 5.1 section 15.12.2.
|
|
exports.parse = function (source, callback) {
|
|
var result, value;
|
|
Index = 0;
|
|
Source = "" + source;
|
|
result = get(lex());
|
|
// If a JSON string contains multiple tokens, it is invalid.
|
|
if (lex() != "$") {
|
|
abort();
|
|
}
|
|
// Reset the parser state.
|
|
Index = Source = null;
|
|
return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
|
|
};
|
|
}
|
|
}
|
|
|
|
exports["runInContext"] = runInContext;
|
|
return exports;
|
|
}
|
|
|
|
if (freeExports && !isLoader) {
|
|
// Export for CommonJS environments.
|
|
runInContext(root, freeExports);
|
|
} else {
|
|
// Export for web browsers and JavaScript engines.
|
|
var nativeJSON = root.JSON,
|
|
previousJSON = root["JSON3"],
|
|
isRestored = false;
|
|
|
|
var JSON3 = runInContext(root, (root["JSON3"] = {
|
|
// Public: Restores the original value of the global `JSON` object and
|
|
// returns a reference to the `JSON3` object.
|
|
"noConflict": function () {
|
|
if (!isRestored) {
|
|
isRestored = true;
|
|
root.JSON = nativeJSON;
|
|
root["JSON3"] = previousJSON;
|
|
nativeJSON = previousJSON = null;
|
|
}
|
|
return JSON3;
|
|
}
|
|
}));
|
|
|
|
root.JSON = {
|
|
"parse": JSON3.parse,
|
|
"stringify": JSON3.stringify
|
|
};
|
|
}
|
|
|
|
// Export for asynchronous module loaders.
|
|
if (isLoader) {
|
|
define(function () {
|
|
return JSON3;
|
|
});
|
|
}
|
|
}).call(this);
|
|
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8)(module), (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 8 */
|
|
/***/ function(module, exports) {
|
|
|
|
module.exports = function(module) {
|
|
if(!module.webpackPolyfill) {
|
|
module.deprecate = function() {};
|
|
module.paths = [];
|
|
// module.parent = undefined by default
|
|
module.children = [];
|
|
module.webpackPolyfill = 1;
|
|
}
|
|
return module;
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 9 */
|
|
/***/ function(module, exports) {
|
|
|
|
module.exports = Array.isArray || function (arr) {
|
|
return Object.prototype.toString.call(arr) == '[object Array]';
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 10 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
/**
|
|
* Expose `Emitter`.
|
|
*/
|
|
|
|
module.exports = Emitter;
|
|
|
|
/**
|
|
* Initialize a new `Emitter`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function Emitter(obj) {
|
|
if (obj) return mixin(obj);
|
|
};
|
|
|
|
/**
|
|
* Mixin the emitter properties.
|
|
*
|
|
* @param {Object} obj
|
|
* @return {Object}
|
|
* @api private
|
|
*/
|
|
|
|
function mixin(obj) {
|
|
for (var key in Emitter.prototype) {
|
|
obj[key] = Emitter.prototype[key];
|
|
}
|
|
return obj;
|
|
}
|
|
|
|
/**
|
|
* Listen on the given `event` with `fn`.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.on =
|
|
Emitter.prototype.addEventListener = function(event, fn){
|
|
this._callbacks = this._callbacks || {};
|
|
(this._callbacks[event] = this._callbacks[event] || [])
|
|
.push(fn);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Adds an `event` listener that will be invoked a single
|
|
* time then automatically removed.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.once = function(event, fn){
|
|
var self = this;
|
|
this._callbacks = this._callbacks || {};
|
|
|
|
function on() {
|
|
self.off(event, on);
|
|
fn.apply(this, arguments);
|
|
}
|
|
|
|
on.fn = fn;
|
|
this.on(event, on);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Remove the given callback for `event` or all
|
|
* registered callbacks.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.off =
|
|
Emitter.prototype.removeListener =
|
|
Emitter.prototype.removeAllListeners =
|
|
Emitter.prototype.removeEventListener = function(event, fn){
|
|
this._callbacks = this._callbacks || {};
|
|
|
|
// all
|
|
if (0 == arguments.length) {
|
|
this._callbacks = {};
|
|
return this;
|
|
}
|
|
|
|
// specific event
|
|
var callbacks = this._callbacks[event];
|
|
if (!callbacks) return this;
|
|
|
|
// remove all handlers
|
|
if (1 == arguments.length) {
|
|
delete this._callbacks[event];
|
|
return this;
|
|
}
|
|
|
|
// remove specific handler
|
|
var cb;
|
|
for (var i = 0; i < callbacks.length; i++) {
|
|
cb = callbacks[i];
|
|
if (cb === fn || cb.fn === fn) {
|
|
callbacks.splice(i, 1);
|
|
break;
|
|
}
|
|
}
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Emit `event` with the given args.
|
|
*
|
|
* @param {String} event
|
|
* @param {Mixed} ...
|
|
* @return {Emitter}
|
|
*/
|
|
|
|
Emitter.prototype.emit = function(event){
|
|
this._callbacks = this._callbacks || {};
|
|
var args = [].slice.call(arguments, 1)
|
|
, callbacks = this._callbacks[event];
|
|
|
|
if (callbacks) {
|
|
callbacks = callbacks.slice(0);
|
|
for (var i = 0, len = callbacks.length; i < len; ++i) {
|
|
callbacks[i].apply(this, args);
|
|
}
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Return array of callbacks for `event`.
|
|
*
|
|
* @param {String} event
|
|
* @return {Array}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.listeners = function(event){
|
|
this._callbacks = this._callbacks || {};
|
|
return this._callbacks[event] || [];
|
|
};
|
|
|
|
/**
|
|
* Check if this emitter has `event` handlers.
|
|
*
|
|
* @param {String} event
|
|
* @return {Boolean}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.hasListeners = function(event){
|
|
return !! this.listeners(event).length;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 11 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/*global Blob,File*/
|
|
|
|
/**
|
|
* Module requirements
|
|
*/
|
|
|
|
var isArray = __webpack_require__(9);
|
|
var isBuf = __webpack_require__(12);
|
|
|
|
/**
|
|
* Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
|
|
* Anything with blobs or files should be fed through removeBlobs before coming
|
|
* here.
|
|
*
|
|
* @param {Object} packet - socket.io event packet
|
|
* @return {Object} with deconstructed packet and list of buffers
|
|
* @api public
|
|
*/
|
|
|
|
exports.deconstructPacket = function(packet){
|
|
var buffers = [];
|
|
var packetData = packet.data;
|
|
|
|
function _deconstructPacket(data) {
|
|
if (!data) return data;
|
|
|
|
if (isBuf(data)) {
|
|
var placeholder = { _placeholder: true, num: buffers.length };
|
|
buffers.push(data);
|
|
return placeholder;
|
|
} else if (isArray(data)) {
|
|
var newData = new Array(data.length);
|
|
for (var i = 0; i < data.length; i++) {
|
|
newData[i] = _deconstructPacket(data[i]);
|
|
}
|
|
return newData;
|
|
} else if ('object' == typeof data && !(data instanceof Date)) {
|
|
var newData = {};
|
|
for (var key in data) {
|
|
newData[key] = _deconstructPacket(data[key]);
|
|
}
|
|
return newData;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
var pack = packet;
|
|
pack.data = _deconstructPacket(packetData);
|
|
pack.attachments = buffers.length; // number of binary 'attachments'
|
|
return {packet: pack, buffers: buffers};
|
|
};
|
|
|
|
/**
|
|
* Reconstructs a binary packet from its placeholder packet and buffers
|
|
*
|
|
* @param {Object} packet - event packet with placeholders
|
|
* @param {Array} buffers - binary buffers to put in placeholder positions
|
|
* @return {Object} reconstructed packet
|
|
* @api public
|
|
*/
|
|
|
|
exports.reconstructPacket = function(packet, buffers) {
|
|
var curPlaceHolder = 0;
|
|
|
|
function _reconstructPacket(data) {
|
|
if (data && data._placeholder) {
|
|
var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
|
|
return buf;
|
|
} else if (isArray(data)) {
|
|
for (var i = 0; i < data.length; i++) {
|
|
data[i] = _reconstructPacket(data[i]);
|
|
}
|
|
return data;
|
|
} else if (data && 'object' == typeof data) {
|
|
for (var key in data) {
|
|
data[key] = _reconstructPacket(data[key]);
|
|
}
|
|
return data;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
packet.data = _reconstructPacket(packet.data);
|
|
packet.attachments = undefined; // no longer useful
|
|
return packet;
|
|
};
|
|
|
|
/**
|
|
* Asynchronously removes Blobs or Files from data via
|
|
* FileReader's readAsArrayBuffer method. Used before encoding
|
|
* data as msgpack. Calls callback with the blobless data.
|
|
*
|
|
* @param {Object} data
|
|
* @param {Function} callback
|
|
* @api private
|
|
*/
|
|
|
|
exports.removeBlobs = function(data, callback) {
|
|
function _removeBlobs(obj, curKey, containingObject) {
|
|
if (!obj) return obj;
|
|
|
|
// convert any blob
|
|
if ((global.Blob && obj instanceof Blob) ||
|
|
(global.File && obj instanceof File)) {
|
|
pendingBlobs++;
|
|
|
|
// async filereader
|
|
var fileReader = new FileReader();
|
|
fileReader.onload = function() { // this.result == arraybuffer
|
|
if (containingObject) {
|
|
containingObject[curKey] = this.result;
|
|
}
|
|
else {
|
|
bloblessData = this.result;
|
|
}
|
|
|
|
// if nothing pending its callback time
|
|
if(! --pendingBlobs) {
|
|
callback(bloblessData);
|
|
}
|
|
};
|
|
|
|
fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
|
|
} else if (isArray(obj)) { // handle array
|
|
for (var i = 0; i < obj.length; i++) {
|
|
_removeBlobs(obj[i], i, obj);
|
|
}
|
|
} else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
|
|
for (var key in obj) {
|
|
_removeBlobs(obj[key], key, obj);
|
|
}
|
|
}
|
|
}
|
|
|
|
var pendingBlobs = 0;
|
|
var bloblessData = data;
|
|
_removeBlobs(bloblessData);
|
|
if (!pendingBlobs) {
|
|
callback(bloblessData);
|
|
}
|
|
};
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 12 */
|
|
/***/ function(module, exports) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {
|
|
module.exports = isBuf;
|
|
|
|
/**
|
|
* Returns true if obj is a buffer or an arraybuffer.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
function isBuf(obj) {
|
|
return (global.Buffer && global.Buffer.isBuffer(obj)) ||
|
|
(global.ArrayBuffer && obj instanceof ArrayBuffer);
|
|
}
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 13 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var eio = __webpack_require__(14);
|
|
var Socket = __webpack_require__(40);
|
|
var Emitter = __webpack_require__(41);
|
|
var parser = __webpack_require__(6);
|
|
var on = __webpack_require__(43);
|
|
var bind = __webpack_require__(44);
|
|
var debug = __webpack_require__(3)('socket.io-client:manager');
|
|
var indexOf = __webpack_require__(38);
|
|
var Backoff = __webpack_require__(46);
|
|
|
|
/**
|
|
* IE6+ hasOwnProperty
|
|
*/
|
|
|
|
var has = Object.prototype.hasOwnProperty;
|
|
|
|
/**
|
|
* Module exports
|
|
*/
|
|
|
|
module.exports = Manager;
|
|
|
|
/**
|
|
* `Manager` constructor.
|
|
*
|
|
* @param {String} engine instance or engine uri/opts
|
|
* @param {Object} options
|
|
* @api public
|
|
*/
|
|
|
|
function Manager(uri, opts) {
|
|
if (!(this instanceof Manager)) return new Manager(uri, opts);
|
|
if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
|
|
opts = uri;
|
|
uri = undefined;
|
|
}
|
|
opts = opts || {};
|
|
|
|
opts.path = opts.path || '/socket.io';
|
|
this.nsps = {};
|
|
this.subs = [];
|
|
this.opts = opts;
|
|
this.reconnection(opts.reconnection !== false);
|
|
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
|
|
this.reconnectionDelay(opts.reconnectionDelay || 1000);
|
|
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
|
|
this.randomizationFactor(opts.randomizationFactor || 0.5);
|
|
this.backoff = new Backoff({
|
|
min: this.reconnectionDelay(),
|
|
max: this.reconnectionDelayMax(),
|
|
jitter: this.randomizationFactor()
|
|
});
|
|
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
|
|
this.readyState = 'closed';
|
|
this.uri = uri;
|
|
this.connecting = [];
|
|
this.lastPing = null;
|
|
this.encoding = false;
|
|
this.packetBuffer = [];
|
|
this.encoder = new parser.Encoder();
|
|
this.decoder = new parser.Decoder();
|
|
this.autoConnect = opts.autoConnect !== false;
|
|
if (this.autoConnect) this.open();
|
|
}
|
|
|
|
/**
|
|
* Propagate given event to sockets and emit on `this`
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.emitAll = function () {
|
|
this.emit.apply(this, arguments);
|
|
for (var nsp in this.nsps) {
|
|
if (has.call(this.nsps, nsp)) {
|
|
this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Update `socket.id` of all sockets
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.updateSocketIds = function () {
|
|
for (var nsp in this.nsps) {
|
|
if (has.call(this.nsps, nsp)) {
|
|
this.nsps[nsp].id = this.engine.id;
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Mix in `Emitter`.
|
|
*/
|
|
|
|
Emitter(Manager.prototype);
|
|
|
|
/**
|
|
* Sets the `reconnection` config.
|
|
*
|
|
* @param {Boolean} true/false if it should automatically reconnect
|
|
* @return {Manager} self or value
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.reconnection = function (v) {
|
|
if (!arguments.length) return this._reconnection;
|
|
this._reconnection = !!v;
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sets the reconnection attempts config.
|
|
*
|
|
* @param {Number} max reconnection attempts before giving up
|
|
* @return {Manager} self or value
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.reconnectionAttempts = function (v) {
|
|
if (!arguments.length) return this._reconnectionAttempts;
|
|
this._reconnectionAttempts = v;
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sets the delay between reconnections.
|
|
*
|
|
* @param {Number} delay
|
|
* @return {Manager} self or value
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.reconnectionDelay = function (v) {
|
|
if (!arguments.length) return this._reconnectionDelay;
|
|
this._reconnectionDelay = v;
|
|
this.backoff && this.backoff.setMin(v);
|
|
return this;
|
|
};
|
|
|
|
Manager.prototype.randomizationFactor = function (v) {
|
|
if (!arguments.length) return this._randomizationFactor;
|
|
this._randomizationFactor = v;
|
|
this.backoff && this.backoff.setJitter(v);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sets the maximum delay between reconnections.
|
|
*
|
|
* @param {Number} delay
|
|
* @return {Manager} self or value
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.reconnectionDelayMax = function (v) {
|
|
if (!arguments.length) return this._reconnectionDelayMax;
|
|
this._reconnectionDelayMax = v;
|
|
this.backoff && this.backoff.setMax(v);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sets the connection timeout. `false` to disable
|
|
*
|
|
* @return {Manager} self or value
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.timeout = function (v) {
|
|
if (!arguments.length) return this._timeout;
|
|
this._timeout = v;
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Starts trying to reconnect if reconnection is enabled and we have not
|
|
* started reconnecting yet
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.maybeReconnectOnOpen = function () {
|
|
// Only try to reconnect if it's the first time we're connecting
|
|
if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
|
|
// keeps reconnection from firing twice for the same reconnection loop
|
|
this.reconnect();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Sets the current transport `socket`.
|
|
*
|
|
* @param {Function} optional, callback
|
|
* @return {Manager} self
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.open = Manager.prototype.connect = function (fn, opts) {
|
|
debug('readyState %s', this.readyState);
|
|
if (~this.readyState.indexOf('open')) return this;
|
|
|
|
debug('opening %s', this.uri);
|
|
this.engine = eio(this.uri, this.opts);
|
|
var socket = this.engine;
|
|
var self = this;
|
|
this.readyState = 'opening';
|
|
this.skipReconnect = false;
|
|
|
|
// emit `open`
|
|
var openSub = on(socket, 'open', function () {
|
|
self.onopen();
|
|
fn && fn();
|
|
});
|
|
|
|
// emit `connect_error`
|
|
var errorSub = on(socket, 'error', function (data) {
|
|
debug('connect_error');
|
|
self.cleanup();
|
|
self.readyState = 'closed';
|
|
self.emitAll('connect_error', data);
|
|
if (fn) {
|
|
var err = new Error('Connection error');
|
|
err.data = data;
|
|
fn(err);
|
|
} else {
|
|
// Only do this if there is no fn to handle the error
|
|
self.maybeReconnectOnOpen();
|
|
}
|
|
});
|
|
|
|
// emit `connect_timeout`
|
|
if (false !== this._timeout) {
|
|
var timeout = this._timeout;
|
|
debug('connect attempt will timeout after %d', timeout);
|
|
|
|
// set timer
|
|
var timer = setTimeout(function () {
|
|
debug('connect attempt timed out after %d', timeout);
|
|
openSub.destroy();
|
|
socket.close();
|
|
socket.emit('error', 'timeout');
|
|
self.emitAll('connect_timeout', timeout);
|
|
}, timeout);
|
|
|
|
this.subs.push({
|
|
destroy: function destroy() {
|
|
clearTimeout(timer);
|
|
}
|
|
});
|
|
}
|
|
|
|
this.subs.push(openSub);
|
|
this.subs.push(errorSub);
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Called upon transport open.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.onopen = function () {
|
|
debug('open');
|
|
|
|
// clear old subs
|
|
this.cleanup();
|
|
|
|
// mark as open
|
|
this.readyState = 'open';
|
|
this.emit('open');
|
|
|
|
// add new subs
|
|
var socket = this.engine;
|
|
this.subs.push(on(socket, 'data', bind(this, 'ondata')));
|
|
this.subs.push(on(socket, 'ping', bind(this, 'onping')));
|
|
this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
|
|
this.subs.push(on(socket, 'error', bind(this, 'onerror')));
|
|
this.subs.push(on(socket, 'close', bind(this, 'onclose')));
|
|
this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
|
|
};
|
|
|
|
/**
|
|
* Called upon a ping.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.onping = function () {
|
|
this.lastPing = new Date();
|
|
this.emitAll('ping');
|
|
};
|
|
|
|
/**
|
|
* Called upon a packet.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.onpong = function () {
|
|
this.emitAll('pong', new Date() - this.lastPing);
|
|
};
|
|
|
|
/**
|
|
* Called with data.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.ondata = function (data) {
|
|
this.decoder.add(data);
|
|
};
|
|
|
|
/**
|
|
* Called when parser fully decodes a packet.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.ondecoded = function (packet) {
|
|
this.emit('packet', packet);
|
|
};
|
|
|
|
/**
|
|
* Called upon socket error.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.onerror = function (err) {
|
|
debug('error', err);
|
|
this.emitAll('error', err);
|
|
};
|
|
|
|
/**
|
|
* Creates a new socket for the given `nsp`.
|
|
*
|
|
* @return {Socket}
|
|
* @api public
|
|
*/
|
|
|
|
Manager.prototype.socket = function (nsp, opts) {
|
|
var socket = this.nsps[nsp];
|
|
if (!socket) {
|
|
socket = new Socket(this, nsp, opts);
|
|
this.nsps[nsp] = socket;
|
|
var self = this;
|
|
socket.on('connecting', onConnecting);
|
|
socket.on('connect', function () {
|
|
socket.id = self.engine.id;
|
|
});
|
|
|
|
if (this.autoConnect) {
|
|
// manually call here since connecting evnet is fired before listening
|
|
onConnecting();
|
|
}
|
|
}
|
|
|
|
function onConnecting() {
|
|
if (!~indexOf(self.connecting, socket)) {
|
|
self.connecting.push(socket);
|
|
}
|
|
}
|
|
|
|
return socket;
|
|
};
|
|
|
|
/**
|
|
* Called upon a socket close.
|
|
*
|
|
* @param {Socket} socket
|
|
*/
|
|
|
|
Manager.prototype.destroy = function (socket) {
|
|
var index = indexOf(this.connecting, socket);
|
|
if (~index) this.connecting.splice(index, 1);
|
|
if (this.connecting.length) return;
|
|
|
|
this.close();
|
|
};
|
|
|
|
/**
|
|
* Writes a packet.
|
|
*
|
|
* @param {Object} packet
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.packet = function (packet) {
|
|
debug('writing packet %j', packet);
|
|
var self = this;
|
|
if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
|
|
|
|
if (!self.encoding) {
|
|
// encode, then write to engine with result
|
|
self.encoding = true;
|
|
this.encoder.encode(packet, function (encodedPackets) {
|
|
for (var i = 0; i < encodedPackets.length; i++) {
|
|
self.engine.write(encodedPackets[i], packet.options);
|
|
}
|
|
self.encoding = false;
|
|
self.processPacketQueue();
|
|
});
|
|
} else {
|
|
// add packet to the queue
|
|
self.packetBuffer.push(packet);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* If packet buffer is non-empty, begins encoding the
|
|
* next packet in line.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.processPacketQueue = function () {
|
|
if (this.packetBuffer.length > 0 && !this.encoding) {
|
|
var pack = this.packetBuffer.shift();
|
|
this.packet(pack);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Clean up transport subscriptions and packet buffer.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.cleanup = function () {
|
|
debug('cleanup');
|
|
|
|
var subsLength = this.subs.length;
|
|
for (var i = 0; i < subsLength; i++) {
|
|
var sub = this.subs.shift();
|
|
sub.destroy();
|
|
}
|
|
|
|
this.packetBuffer = [];
|
|
this.encoding = false;
|
|
this.lastPing = null;
|
|
|
|
this.decoder.destroy();
|
|
};
|
|
|
|
/**
|
|
* Close the current socket.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.close = Manager.prototype.disconnect = function () {
|
|
debug('disconnect');
|
|
this.skipReconnect = true;
|
|
this.reconnecting = false;
|
|
if ('opening' === this.readyState) {
|
|
// `onclose` will not fire because
|
|
// an open event never happened
|
|
this.cleanup();
|
|
}
|
|
this.backoff.reset();
|
|
this.readyState = 'closed';
|
|
if (this.engine) this.engine.close();
|
|
};
|
|
|
|
/**
|
|
* Called upon engine close.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.onclose = function (reason) {
|
|
debug('onclose');
|
|
|
|
this.cleanup();
|
|
this.backoff.reset();
|
|
this.readyState = 'closed';
|
|
this.emit('close', reason);
|
|
|
|
if (this._reconnection && !this.skipReconnect) {
|
|
this.reconnect();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Attempt a reconnection.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.reconnect = function () {
|
|
if (this.reconnecting || this.skipReconnect) return this;
|
|
|
|
var self = this;
|
|
|
|
if (this.backoff.attempts >= this._reconnectionAttempts) {
|
|
debug('reconnect failed');
|
|
this.backoff.reset();
|
|
this.emitAll('reconnect_failed');
|
|
this.reconnecting = false;
|
|
} else {
|
|
var delay = this.backoff.duration();
|
|
debug('will wait %dms before reconnect attempt', delay);
|
|
|
|
this.reconnecting = true;
|
|
var timer = setTimeout(function () {
|
|
if (self.skipReconnect) return;
|
|
|
|
debug('attempting reconnect');
|
|
self.emitAll('reconnect_attempt', self.backoff.attempts);
|
|
self.emitAll('reconnecting', self.backoff.attempts);
|
|
|
|
// check again for the case socket closed in above events
|
|
if (self.skipReconnect) return;
|
|
|
|
self.open(function (err) {
|
|
if (err) {
|
|
debug('reconnect attempt error');
|
|
self.reconnecting = false;
|
|
self.reconnect();
|
|
self.emitAll('reconnect_error', err.data);
|
|
} else {
|
|
debug('reconnect success');
|
|
self.onreconnect();
|
|
}
|
|
});
|
|
}, delay);
|
|
|
|
this.subs.push({
|
|
destroy: function destroy() {
|
|
clearTimeout(timer);
|
|
}
|
|
});
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon successful reconnect.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Manager.prototype.onreconnect = function () {
|
|
var attempt = this.backoff.attempts;
|
|
this.reconnecting = false;
|
|
this.backoff.reset();
|
|
this.updateSocketIds();
|
|
this.emitAll('reconnect', attempt);
|
|
};
|
|
|
|
/***/ },
|
|
/* 14 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
|
|
module.exports = __webpack_require__(15);
|
|
|
|
|
|
/***/ },
|
|
/* 15 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
|
|
module.exports = __webpack_require__(16);
|
|
|
|
/**
|
|
* Exports parser
|
|
*
|
|
* @api public
|
|
*
|
|
*/
|
|
module.exports.parser = __webpack_require__(23);
|
|
|
|
|
|
/***/ },
|
|
/* 16 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var transports = __webpack_require__(17);
|
|
var Emitter = __webpack_require__(31);
|
|
var debug = __webpack_require__(3)('engine.io-client:socket');
|
|
var index = __webpack_require__(38);
|
|
var parser = __webpack_require__(23);
|
|
var parseuri = __webpack_require__(2);
|
|
var parsejson = __webpack_require__(39);
|
|
var parseqs = __webpack_require__(32);
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = Socket;
|
|
|
|
/**
|
|
* Socket constructor.
|
|
*
|
|
* @param {String|Object} uri or options
|
|
* @param {Object} options
|
|
* @api public
|
|
*/
|
|
|
|
function Socket (uri, opts) {
|
|
if (!(this instanceof Socket)) return new Socket(uri, opts);
|
|
|
|
opts = opts || {};
|
|
|
|
if (uri && 'object' === typeof uri) {
|
|
opts = uri;
|
|
uri = null;
|
|
}
|
|
|
|
if (uri) {
|
|
uri = parseuri(uri);
|
|
opts.hostname = uri.host;
|
|
opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
|
|
opts.port = uri.port;
|
|
if (uri.query) opts.query = uri.query;
|
|
} else if (opts.host) {
|
|
opts.hostname = parseuri(opts.host).host;
|
|
}
|
|
|
|
this.secure = null != opts.secure ? opts.secure
|
|
: (global.location && 'https:' === location.protocol);
|
|
|
|
if (opts.hostname && !opts.port) {
|
|
// if no port is specified manually, use the protocol default
|
|
opts.port = this.secure ? '443' : '80';
|
|
}
|
|
|
|
this.agent = opts.agent || false;
|
|
this.hostname = opts.hostname ||
|
|
(global.location ? location.hostname : 'localhost');
|
|
this.port = opts.port || (global.location && location.port
|
|
? location.port
|
|
: (this.secure ? 443 : 80));
|
|
this.query = opts.query || {};
|
|
if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
|
|
this.upgrade = false !== opts.upgrade;
|
|
this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
|
|
this.forceJSONP = !!opts.forceJSONP;
|
|
this.jsonp = false !== opts.jsonp;
|
|
this.forceBase64 = !!opts.forceBase64;
|
|
this.enablesXDR = !!opts.enablesXDR;
|
|
this.timestampParam = opts.timestampParam || 't';
|
|
this.timestampRequests = opts.timestampRequests;
|
|
this.transports = opts.transports || ['polling', 'websocket'];
|
|
this.readyState = '';
|
|
this.writeBuffer = [];
|
|
this.prevBufferLen = 0;
|
|
this.policyPort = opts.policyPort || 843;
|
|
this.rememberUpgrade = opts.rememberUpgrade || false;
|
|
this.binaryType = null;
|
|
this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
|
|
this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
|
|
|
|
if (true === this.perMessageDeflate) this.perMessageDeflate = {};
|
|
if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
|
|
this.perMessageDeflate.threshold = 1024;
|
|
}
|
|
|
|
// SSL options for Node.js client
|
|
this.pfx = opts.pfx || null;
|
|
this.key = opts.key || null;
|
|
this.passphrase = opts.passphrase || null;
|
|
this.cert = opts.cert || null;
|
|
this.ca = opts.ca || null;
|
|
this.ciphers = opts.ciphers || null;
|
|
this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;
|
|
|
|
// other options for Node.js client
|
|
var freeGlobal = typeof global === 'object' && global;
|
|
if (freeGlobal.global === freeGlobal) {
|
|
if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
|
|
this.extraHeaders = opts.extraHeaders;
|
|
}
|
|
}
|
|
|
|
// set on handshake
|
|
this.id = null;
|
|
this.upgrades = null;
|
|
this.pingInterval = null;
|
|
this.pingTimeout = null;
|
|
|
|
// set on heartbeat
|
|
this.pingIntervalTimer = null;
|
|
this.pingTimeoutTimer = null;
|
|
|
|
this.open();
|
|
}
|
|
|
|
Socket.priorWebsocketSuccess = false;
|
|
|
|
/**
|
|
* Mix in `Emitter`.
|
|
*/
|
|
|
|
Emitter(Socket.prototype);
|
|
|
|
/**
|
|
* Protocol version.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Socket.protocol = parser.protocol; // this is an int
|
|
|
|
/**
|
|
* Expose deps for legacy compatibility
|
|
* and standalone browser access.
|
|
*/
|
|
|
|
Socket.Socket = Socket;
|
|
Socket.Transport = __webpack_require__(22);
|
|
Socket.transports = __webpack_require__(17);
|
|
Socket.parser = __webpack_require__(23);
|
|
|
|
/**
|
|
* Creates transport of the given type.
|
|
*
|
|
* @param {String} transport name
|
|
* @return {Transport}
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.createTransport = function (name) {
|
|
debug('creating transport "%s"', name);
|
|
var query = clone(this.query);
|
|
|
|
// append engine.io protocol identifier
|
|
query.EIO = parser.protocol;
|
|
|
|
// transport name
|
|
query.transport = name;
|
|
|
|
// session id if we already have one
|
|
if (this.id) query.sid = this.id;
|
|
|
|
var transport = new transports[name]({
|
|
agent: this.agent,
|
|
hostname: this.hostname,
|
|
port: this.port,
|
|
secure: this.secure,
|
|
path: this.path,
|
|
query: query,
|
|
forceJSONP: this.forceJSONP,
|
|
jsonp: this.jsonp,
|
|
forceBase64: this.forceBase64,
|
|
enablesXDR: this.enablesXDR,
|
|
timestampRequests: this.timestampRequests,
|
|
timestampParam: this.timestampParam,
|
|
policyPort: this.policyPort,
|
|
socket: this,
|
|
pfx: this.pfx,
|
|
key: this.key,
|
|
passphrase: this.passphrase,
|
|
cert: this.cert,
|
|
ca: this.ca,
|
|
ciphers: this.ciphers,
|
|
rejectUnauthorized: this.rejectUnauthorized,
|
|
perMessageDeflate: this.perMessageDeflate,
|
|
extraHeaders: this.extraHeaders
|
|
});
|
|
|
|
return transport;
|
|
};
|
|
|
|
function clone (obj) {
|
|
var o = {};
|
|
for (var i in obj) {
|
|
if (obj.hasOwnProperty(i)) {
|
|
o[i] = obj[i];
|
|
}
|
|
}
|
|
return o;
|
|
}
|
|
|
|
/**
|
|
* Initializes transport to use and starts probe.
|
|
*
|
|
* @api private
|
|
*/
|
|
Socket.prototype.open = function () {
|
|
var transport;
|
|
if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
|
|
transport = 'websocket';
|
|
} else if (0 === this.transports.length) {
|
|
// Emit error on next tick so it can be listened to
|
|
var self = this;
|
|
setTimeout(function () {
|
|
self.emit('error', 'No transports available');
|
|
}, 0);
|
|
return;
|
|
} else {
|
|
transport = this.transports[0];
|
|
}
|
|
this.readyState = 'opening';
|
|
|
|
// Retry with the next transport if the transport is disabled (jsonp: false)
|
|
try {
|
|
transport = this.createTransport(transport);
|
|
} catch (e) {
|
|
this.transports.shift();
|
|
this.open();
|
|
return;
|
|
}
|
|
|
|
transport.open();
|
|
this.setTransport(transport);
|
|
};
|
|
|
|
/**
|
|
* Sets the current transport. Disables the existing one (if any).
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.setTransport = function (transport) {
|
|
debug('setting transport %s', transport.name);
|
|
var self = this;
|
|
|
|
if (this.transport) {
|
|
debug('clearing existing transport %s', this.transport.name);
|
|
this.transport.removeAllListeners();
|
|
}
|
|
|
|
// set up transport
|
|
this.transport = transport;
|
|
|
|
// set up transport listeners
|
|
transport
|
|
.on('drain', function () {
|
|
self.onDrain();
|
|
})
|
|
.on('packet', function (packet) {
|
|
self.onPacket(packet);
|
|
})
|
|
.on('error', function (e) {
|
|
self.onError(e);
|
|
})
|
|
.on('close', function () {
|
|
self.onClose('transport close');
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Probes a transport.
|
|
*
|
|
* @param {String} transport name
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.probe = function (name) {
|
|
debug('probing transport "%s"', name);
|
|
var transport = this.createTransport(name, { probe: 1 });
|
|
var failed = false;
|
|
var self = this;
|
|
|
|
Socket.priorWebsocketSuccess = false;
|
|
|
|
function onTransportOpen () {
|
|
if (self.onlyBinaryUpgrades) {
|
|
var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
|
|
failed = failed || upgradeLosesBinary;
|
|
}
|
|
if (failed) return;
|
|
|
|
debug('probe transport "%s" opened', name);
|
|
transport.send([{ type: 'ping', data: 'probe' }]);
|
|
transport.once('packet', function (msg) {
|
|
if (failed) return;
|
|
if ('pong' === msg.type && 'probe' === msg.data) {
|
|
debug('probe transport "%s" pong', name);
|
|
self.upgrading = true;
|
|
self.emit('upgrading', transport);
|
|
if (!transport) return;
|
|
Socket.priorWebsocketSuccess = 'websocket' === transport.name;
|
|
|
|
debug('pausing current transport "%s"', self.transport.name);
|
|
self.transport.pause(function () {
|
|
if (failed) return;
|
|
if ('closed' === self.readyState) return;
|
|
debug('changing transport and sending upgrade packet');
|
|
|
|
cleanup();
|
|
|
|
self.setTransport(transport);
|
|
transport.send([{ type: 'upgrade' }]);
|
|
self.emit('upgrade', transport);
|
|
transport = null;
|
|
self.upgrading = false;
|
|
self.flush();
|
|
});
|
|
} else {
|
|
debug('probe transport "%s" failed', name);
|
|
var err = new Error('probe error');
|
|
err.transport = transport.name;
|
|
self.emit('upgradeError', err);
|
|
}
|
|
});
|
|
}
|
|
|
|
function freezeTransport () {
|
|
if (failed) return;
|
|
|
|
// Any callback called by transport should be ignored since now
|
|
failed = true;
|
|
|
|
cleanup();
|
|
|
|
transport.close();
|
|
transport = null;
|
|
}
|
|
|
|
// Handle any error that happens while probing
|
|
function onerror (err) {
|
|
var error = new Error('probe error: ' + err);
|
|
error.transport = transport.name;
|
|
|
|
freezeTransport();
|
|
|
|
debug('probe transport "%s" failed because of error: %s', name, err);
|
|
|
|
self.emit('upgradeError', error);
|
|
}
|
|
|
|
function onTransportClose () {
|
|
onerror('transport closed');
|
|
}
|
|
|
|
// When the socket is closed while we're probing
|
|
function onclose () {
|
|
onerror('socket closed');
|
|
}
|
|
|
|
// When the socket is upgraded while we're probing
|
|
function onupgrade (to) {
|
|
if (transport && to.name !== transport.name) {
|
|
debug('"%s" works - aborting "%s"', to.name, transport.name);
|
|
freezeTransport();
|
|
}
|
|
}
|
|
|
|
// Remove all listeners on the transport and on self
|
|
function cleanup () {
|
|
transport.removeListener('open', onTransportOpen);
|
|
transport.removeListener('error', onerror);
|
|
transport.removeListener('close', onTransportClose);
|
|
self.removeListener('close', onclose);
|
|
self.removeListener('upgrading', onupgrade);
|
|
}
|
|
|
|
transport.once('open', onTransportOpen);
|
|
transport.once('error', onerror);
|
|
transport.once('close', onTransportClose);
|
|
|
|
this.once('close', onclose);
|
|
this.once('upgrading', onupgrade);
|
|
|
|
transport.open();
|
|
};
|
|
|
|
/**
|
|
* Called when connection is deemed open.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.onOpen = function () {
|
|
debug('socket open');
|
|
this.readyState = 'open';
|
|
Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
|
|
this.emit('open');
|
|
this.flush();
|
|
|
|
// we check for `readyState` in case an `open`
|
|
// listener already closed the socket
|
|
if ('open' === this.readyState && this.upgrade && this.transport.pause) {
|
|
debug('starting upgrade probes');
|
|
for (var i = 0, l = this.upgrades.length; i < l; i++) {
|
|
this.probe(this.upgrades[i]);
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Handles a packet.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onPacket = function (packet) {
|
|
if ('opening' === this.readyState || 'open' === this.readyState) {
|
|
debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
|
|
|
|
this.emit('packet', packet);
|
|
|
|
// Socket is live - any packet counts
|
|
this.emit('heartbeat');
|
|
|
|
switch (packet.type) {
|
|
case 'open':
|
|
this.onHandshake(parsejson(packet.data));
|
|
break;
|
|
|
|
case 'pong':
|
|
this.setPing();
|
|
this.emit('pong');
|
|
break;
|
|
|
|
case 'error':
|
|
var err = new Error('server error');
|
|
err.code = packet.data;
|
|
this.onError(err);
|
|
break;
|
|
|
|
case 'message':
|
|
this.emit('data', packet.data);
|
|
this.emit('message', packet.data);
|
|
break;
|
|
}
|
|
} else {
|
|
debug('packet received with socket readyState "%s"', this.readyState);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon handshake completion.
|
|
*
|
|
* @param {Object} handshake obj
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onHandshake = function (data) {
|
|
this.emit('handshake', data);
|
|
this.id = data.sid;
|
|
this.transport.query.sid = data.sid;
|
|
this.upgrades = this.filterUpgrades(data.upgrades);
|
|
this.pingInterval = data.pingInterval;
|
|
this.pingTimeout = data.pingTimeout;
|
|
this.onOpen();
|
|
// In case open handler closes socket
|
|
if ('closed' === this.readyState) return;
|
|
this.setPing();
|
|
|
|
// Prolong liveness of socket on heartbeat
|
|
this.removeListener('heartbeat', this.onHeartbeat);
|
|
this.on('heartbeat', this.onHeartbeat);
|
|
};
|
|
|
|
/**
|
|
* Resets ping timeout.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onHeartbeat = function (timeout) {
|
|
clearTimeout(this.pingTimeoutTimer);
|
|
var self = this;
|
|
self.pingTimeoutTimer = setTimeout(function () {
|
|
if ('closed' === self.readyState) return;
|
|
self.onClose('ping timeout');
|
|
}, timeout || (self.pingInterval + self.pingTimeout));
|
|
};
|
|
|
|
/**
|
|
* Pings server every `this.pingInterval` and expects response
|
|
* within `this.pingTimeout` or closes connection.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.setPing = function () {
|
|
var self = this;
|
|
clearTimeout(self.pingIntervalTimer);
|
|
self.pingIntervalTimer = setTimeout(function () {
|
|
debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
|
|
self.ping();
|
|
self.onHeartbeat(self.pingTimeout);
|
|
}, self.pingInterval);
|
|
};
|
|
|
|
/**
|
|
* Sends a ping packet.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.ping = function () {
|
|
var self = this;
|
|
this.sendPacket('ping', function () {
|
|
self.emit('ping');
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Called on `drain` event
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onDrain = function () {
|
|
this.writeBuffer.splice(0, this.prevBufferLen);
|
|
|
|
// setting prevBufferLen = 0 is very important
|
|
// for example, when upgrading, upgrade packet is sent over,
|
|
// and a nonzero prevBufferLen could cause problems on `drain`
|
|
this.prevBufferLen = 0;
|
|
|
|
if (0 === this.writeBuffer.length) {
|
|
this.emit('drain');
|
|
} else {
|
|
this.flush();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Flush write buffers.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.flush = function () {
|
|
if ('closed' !== this.readyState && this.transport.writable &&
|
|
!this.upgrading && this.writeBuffer.length) {
|
|
debug('flushing %d packets in socket', this.writeBuffer.length);
|
|
this.transport.send(this.writeBuffer);
|
|
// keep track of current length of writeBuffer
|
|
// splice writeBuffer and callbackBuffer on `drain`
|
|
this.prevBufferLen = this.writeBuffer.length;
|
|
this.emit('flush');
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Sends a message.
|
|
*
|
|
* @param {String} message.
|
|
* @param {Function} callback function.
|
|
* @param {Object} options.
|
|
* @return {Socket} for chaining.
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.write =
|
|
Socket.prototype.send = function (msg, options, fn) {
|
|
this.sendPacket('message', msg, options, fn);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sends a packet.
|
|
*
|
|
* @param {String} packet type.
|
|
* @param {String} data.
|
|
* @param {Object} options.
|
|
* @param {Function} callback function.
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.sendPacket = function (type, data, options, fn) {
|
|
if ('function' === typeof data) {
|
|
fn = data;
|
|
data = undefined;
|
|
}
|
|
|
|
if ('function' === typeof options) {
|
|
fn = options;
|
|
options = null;
|
|
}
|
|
|
|
if ('closing' === this.readyState || 'closed' === this.readyState) {
|
|
return;
|
|
}
|
|
|
|
options = options || {};
|
|
options.compress = false !== options.compress;
|
|
|
|
var packet = {
|
|
type: type,
|
|
data: data,
|
|
options: options
|
|
};
|
|
this.emit('packetCreate', packet);
|
|
this.writeBuffer.push(packet);
|
|
if (fn) this.once('flush', fn);
|
|
this.flush();
|
|
};
|
|
|
|
/**
|
|
* Closes the connection.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.close = function () {
|
|
if ('opening' === this.readyState || 'open' === this.readyState) {
|
|
this.readyState = 'closing';
|
|
|
|
var self = this;
|
|
|
|
if (this.writeBuffer.length) {
|
|
this.once('drain', function () {
|
|
if (this.upgrading) {
|
|
waitForUpgrade();
|
|
} else {
|
|
close();
|
|
}
|
|
});
|
|
} else if (this.upgrading) {
|
|
waitForUpgrade();
|
|
} else {
|
|
close();
|
|
}
|
|
}
|
|
|
|
function close () {
|
|
self.onClose('forced close');
|
|
debug('socket closing - telling transport to close');
|
|
self.transport.close();
|
|
}
|
|
|
|
function cleanupAndClose () {
|
|
self.removeListener('upgrade', cleanupAndClose);
|
|
self.removeListener('upgradeError', cleanupAndClose);
|
|
close();
|
|
}
|
|
|
|
function waitForUpgrade () {
|
|
// wait for upgrade to finish since we can't send packets while pausing a transport
|
|
self.once('upgrade', cleanupAndClose);
|
|
self.once('upgradeError', cleanupAndClose);
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Called upon transport error
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onError = function (err) {
|
|
debug('socket error %j', err);
|
|
Socket.priorWebsocketSuccess = false;
|
|
this.emit('error', err);
|
|
this.onClose('transport error', err);
|
|
};
|
|
|
|
/**
|
|
* Called upon transport close.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onClose = function (reason, desc) {
|
|
if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
|
|
debug('socket close with reason: "%s"', reason);
|
|
var self = this;
|
|
|
|
// clear timers
|
|
clearTimeout(this.pingIntervalTimer);
|
|
clearTimeout(this.pingTimeoutTimer);
|
|
|
|
// stop event from firing again for transport
|
|
this.transport.removeAllListeners('close');
|
|
|
|
// ensure transport won't stay open
|
|
this.transport.close();
|
|
|
|
// ignore further transport communication
|
|
this.transport.removeAllListeners();
|
|
|
|
// set ready state
|
|
this.readyState = 'closed';
|
|
|
|
// clear session id
|
|
this.id = null;
|
|
|
|
// emit close event
|
|
this.emit('close', reason, desc);
|
|
|
|
// clean buffers after, so users can still
|
|
// grab the buffers on `close` event
|
|
self.writeBuffer = [];
|
|
self.prevBufferLen = 0;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Filters upgrades, returning only those matching client transports.
|
|
*
|
|
* @param {Array} server upgrades
|
|
* @api private
|
|
*
|
|
*/
|
|
|
|
Socket.prototype.filterUpgrades = function (upgrades) {
|
|
var filteredUpgrades = [];
|
|
for (var i = 0, j = upgrades.length; i < j; i++) {
|
|
if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
|
|
}
|
|
return filteredUpgrades;
|
|
};
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 17 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* Module dependencies
|
|
*/
|
|
|
|
var XMLHttpRequest = __webpack_require__(18);
|
|
var XHR = __webpack_require__(20);
|
|
var JSONP = __webpack_require__(35);
|
|
var websocket = __webpack_require__(36);
|
|
|
|
/**
|
|
* Export transports.
|
|
*/
|
|
|
|
exports.polling = polling;
|
|
exports.websocket = websocket;
|
|
|
|
/**
|
|
* Polling transport polymorphic constructor.
|
|
* Decides on xhr vs jsonp based on feature detection.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
function polling (opts) {
|
|
var xhr;
|
|
var xd = false;
|
|
var xs = false;
|
|
var jsonp = false !== opts.jsonp;
|
|
|
|
if (global.location) {
|
|
var isSSL = 'https:' === location.protocol;
|
|
var port = location.port;
|
|
|
|
// some user agents have empty `location.port`
|
|
if (!port) {
|
|
port = isSSL ? 443 : 80;
|
|
}
|
|
|
|
xd = opts.hostname !== location.hostname || port !== opts.port;
|
|
xs = opts.secure !== isSSL;
|
|
}
|
|
|
|
opts.xdomain = xd;
|
|
opts.xscheme = xs;
|
|
xhr = new XMLHttpRequest(opts);
|
|
|
|
if ('open' in xhr && !opts.forceJSONP) {
|
|
return new XHR(opts);
|
|
} else {
|
|
if (!jsonp) throw new Error('JSONP disabled');
|
|
return new JSONP(opts);
|
|
}
|
|
}
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 18 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
// browser shim for xmlhttprequest module
|
|
|
|
// Indicate to eslint that ActiveXObject is global
|
|
/* global ActiveXObject */
|
|
|
|
var hasCORS = __webpack_require__(19);
|
|
|
|
module.exports = function (opts) {
|
|
var xdomain = opts.xdomain;
|
|
|
|
// scheme must be same when usign XDomainRequest
|
|
// http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
|
|
var xscheme = opts.xscheme;
|
|
|
|
// XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
|
|
// https://github.com/Automattic/engine.io-client/pull/217
|
|
var enablesXDR = opts.enablesXDR;
|
|
|
|
// XMLHttpRequest can be disabled on IE
|
|
try {
|
|
if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
|
|
return new XMLHttpRequest();
|
|
}
|
|
} catch (e) { }
|
|
|
|
// Use XDomainRequest for IE8 if enablesXDR is true
|
|
// because loading bar keeps flashing when using jsonp-polling
|
|
// https://github.com/yujiosaka/socke.io-ie8-loading-example
|
|
try {
|
|
if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
|
|
return new XDomainRequest();
|
|
}
|
|
} catch (e) { }
|
|
|
|
if (!xdomain) {
|
|
try {
|
|
return new ActiveXObject('Microsoft.XMLHTTP');
|
|
} catch (e) { }
|
|
}
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 19 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
/**
|
|
* Module exports.
|
|
*
|
|
* Logic borrowed from Modernizr:
|
|
*
|
|
* - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
|
|
*/
|
|
|
|
try {
|
|
module.exports = typeof XMLHttpRequest !== 'undefined' &&
|
|
'withCredentials' in new XMLHttpRequest();
|
|
} catch (err) {
|
|
// if XMLHttp support is disabled in IE then it will throw
|
|
// when trying to create
|
|
module.exports = false;
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 20 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* Module requirements.
|
|
*/
|
|
|
|
var XMLHttpRequest = __webpack_require__(18);
|
|
var Polling = __webpack_require__(21);
|
|
var Emitter = __webpack_require__(31);
|
|
var inherit = __webpack_require__(33);
|
|
var debug = __webpack_require__(3)('engine.io-client:polling-xhr');
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = XHR;
|
|
module.exports.Request = Request;
|
|
|
|
/**
|
|
* Empty function
|
|
*/
|
|
|
|
function empty () {}
|
|
|
|
/**
|
|
* XHR Polling constructor.
|
|
*
|
|
* @param {Object} opts
|
|
* @api public
|
|
*/
|
|
|
|
function XHR (opts) {
|
|
Polling.call(this, opts);
|
|
|
|
if (global.location) {
|
|
var isSSL = 'https:' === location.protocol;
|
|
var port = location.port;
|
|
|
|
// some user agents have empty `location.port`
|
|
if (!port) {
|
|
port = isSSL ? 443 : 80;
|
|
}
|
|
|
|
this.xd = opts.hostname !== global.location.hostname ||
|
|
port !== opts.port;
|
|
this.xs = opts.secure !== isSSL;
|
|
} else {
|
|
this.extraHeaders = opts.extraHeaders;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Inherits from Polling.
|
|
*/
|
|
|
|
inherit(XHR, Polling);
|
|
|
|
/**
|
|
* XHR supports binary
|
|
*/
|
|
|
|
XHR.prototype.supportsBinary = true;
|
|
|
|
/**
|
|
* Creates a request.
|
|
*
|
|
* @param {String} method
|
|
* @api private
|
|
*/
|
|
|
|
XHR.prototype.request = function (opts) {
|
|
opts = opts || {};
|
|
opts.uri = this.uri();
|
|
opts.xd = this.xd;
|
|
opts.xs = this.xs;
|
|
opts.agent = this.agent || false;
|
|
opts.supportsBinary = this.supportsBinary;
|
|
opts.enablesXDR = this.enablesXDR;
|
|
|
|
// SSL options for Node.js client
|
|
opts.pfx = this.pfx;
|
|
opts.key = this.key;
|
|
opts.passphrase = this.passphrase;
|
|
opts.cert = this.cert;
|
|
opts.ca = this.ca;
|
|
opts.ciphers = this.ciphers;
|
|
opts.rejectUnauthorized = this.rejectUnauthorized;
|
|
|
|
// other options for Node.js client
|
|
opts.extraHeaders = this.extraHeaders;
|
|
|
|
return new Request(opts);
|
|
};
|
|
|
|
/**
|
|
* Sends data.
|
|
*
|
|
* @param {String} data to send.
|
|
* @param {Function} called upon flush.
|
|
* @api private
|
|
*/
|
|
|
|
XHR.prototype.doWrite = function (data, fn) {
|
|
var isBinary = typeof data !== 'string' && data !== undefined;
|
|
var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
|
|
var self = this;
|
|
req.on('success', fn);
|
|
req.on('error', function (err) {
|
|
self.onError('xhr post error', err);
|
|
});
|
|
this.sendXhr = req;
|
|
};
|
|
|
|
/**
|
|
* Starts a poll cycle.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
XHR.prototype.doPoll = function () {
|
|
debug('xhr poll');
|
|
var req = this.request();
|
|
var self = this;
|
|
req.on('data', function (data) {
|
|
self.onData(data);
|
|
});
|
|
req.on('error', function (err) {
|
|
self.onError('xhr poll error', err);
|
|
});
|
|
this.pollXhr = req;
|
|
};
|
|
|
|
/**
|
|
* Request constructor
|
|
*
|
|
* @param {Object} options
|
|
* @api public
|
|
*/
|
|
|
|
function Request (opts) {
|
|
this.method = opts.method || 'GET';
|
|
this.uri = opts.uri;
|
|
this.xd = !!opts.xd;
|
|
this.xs = !!opts.xs;
|
|
this.async = false !== opts.async;
|
|
this.data = undefined !== opts.data ? opts.data : null;
|
|
this.agent = opts.agent;
|
|
this.isBinary = opts.isBinary;
|
|
this.supportsBinary = opts.supportsBinary;
|
|
this.enablesXDR = opts.enablesXDR;
|
|
|
|
// SSL options for Node.js client
|
|
this.pfx = opts.pfx;
|
|
this.key = opts.key;
|
|
this.passphrase = opts.passphrase;
|
|
this.cert = opts.cert;
|
|
this.ca = opts.ca;
|
|
this.ciphers = opts.ciphers;
|
|
this.rejectUnauthorized = opts.rejectUnauthorized;
|
|
|
|
// other options for Node.js client
|
|
this.extraHeaders = opts.extraHeaders;
|
|
|
|
this.create();
|
|
}
|
|
|
|
/**
|
|
* Mix in `Emitter`.
|
|
*/
|
|
|
|
Emitter(Request.prototype);
|
|
|
|
/**
|
|
* Creates the XHR object and sends the request.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.create = function () {
|
|
var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
|
|
|
|
// SSL options for Node.js client
|
|
opts.pfx = this.pfx;
|
|
opts.key = this.key;
|
|
opts.passphrase = this.passphrase;
|
|
opts.cert = this.cert;
|
|
opts.ca = this.ca;
|
|
opts.ciphers = this.ciphers;
|
|
opts.rejectUnauthorized = this.rejectUnauthorized;
|
|
|
|
var xhr = this.xhr = new XMLHttpRequest(opts);
|
|
var self = this;
|
|
|
|
try {
|
|
debug('xhr open %s: %s', this.method, this.uri);
|
|
xhr.open(this.method, this.uri, this.async);
|
|
try {
|
|
if (this.extraHeaders) {
|
|
xhr.setDisableHeaderCheck(true);
|
|
for (var i in this.extraHeaders) {
|
|
if (this.extraHeaders.hasOwnProperty(i)) {
|
|
xhr.setRequestHeader(i, this.extraHeaders[i]);
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {}
|
|
if (this.supportsBinary) {
|
|
// This has to be done after open because Firefox is stupid
|
|
// http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
|
|
xhr.responseType = 'arraybuffer';
|
|
}
|
|
|
|
if ('POST' === this.method) {
|
|
try {
|
|
if (this.isBinary) {
|
|
xhr.setRequestHeader('Content-type', 'application/octet-stream');
|
|
} else {
|
|
xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
|
|
}
|
|
} catch (e) {}
|
|
}
|
|
|
|
// ie6 check
|
|
if ('withCredentials' in xhr) {
|
|
xhr.withCredentials = true;
|
|
}
|
|
|
|
if (this.hasXDR()) {
|
|
xhr.onload = function () {
|
|
self.onLoad();
|
|
};
|
|
xhr.onerror = function () {
|
|
self.onError(xhr.responseText);
|
|
};
|
|
} else {
|
|
xhr.onreadystatechange = function () {
|
|
if (4 !== xhr.readyState) return;
|
|
if (200 === xhr.status || 1223 === xhr.status) {
|
|
self.onLoad();
|
|
} else {
|
|
// make sure the `error` event handler that's user-set
|
|
// does not throw in the same tick and gets caught here
|
|
setTimeout(function () {
|
|
self.onError(xhr.status);
|
|
}, 0);
|
|
}
|
|
};
|
|
}
|
|
|
|
debug('xhr data %s', this.data);
|
|
xhr.send(this.data);
|
|
} catch (e) {
|
|
// Need to defer since .create() is called directly fhrom the constructor
|
|
// and thus the 'error' event can only be only bound *after* this exception
|
|
// occurs. Therefore, also, we cannot throw here at all.
|
|
setTimeout(function () {
|
|
self.onError(e);
|
|
}, 0);
|
|
return;
|
|
}
|
|
|
|
if (global.document) {
|
|
this.index = Request.requestsCount++;
|
|
Request.requests[this.index] = this;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon successful response.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.onSuccess = function () {
|
|
this.emit('success');
|
|
this.cleanup();
|
|
};
|
|
|
|
/**
|
|
* Called if we have data.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.onData = function (data) {
|
|
this.emit('data', data);
|
|
this.onSuccess();
|
|
};
|
|
|
|
/**
|
|
* Called upon error.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.onError = function (err) {
|
|
this.emit('error', err);
|
|
this.cleanup(true);
|
|
};
|
|
|
|
/**
|
|
* Cleans up house.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.cleanup = function (fromError) {
|
|
if ('undefined' === typeof this.xhr || null === this.xhr) {
|
|
return;
|
|
}
|
|
// xmlhttprequest
|
|
if (this.hasXDR()) {
|
|
this.xhr.onload = this.xhr.onerror = empty;
|
|
} else {
|
|
this.xhr.onreadystatechange = empty;
|
|
}
|
|
|
|
if (fromError) {
|
|
try {
|
|
this.xhr.abort();
|
|
} catch (e) {}
|
|
}
|
|
|
|
if (global.document) {
|
|
delete Request.requests[this.index];
|
|
}
|
|
|
|
this.xhr = null;
|
|
};
|
|
|
|
/**
|
|
* Called upon load.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.onLoad = function () {
|
|
var data;
|
|
try {
|
|
var contentType;
|
|
try {
|
|
contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
|
|
} catch (e) {}
|
|
if (contentType === 'application/octet-stream') {
|
|
data = this.xhr.response || this.xhr.responseText;
|
|
} else {
|
|
if (!this.supportsBinary) {
|
|
data = this.xhr.responseText;
|
|
} else {
|
|
try {
|
|
data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
|
|
} catch (e) {
|
|
var ui8Arr = new Uint8Array(this.xhr.response);
|
|
var dataArray = [];
|
|
for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
|
|
dataArray.push(ui8Arr[idx]);
|
|
}
|
|
|
|
data = String.fromCharCode.apply(null, dataArray);
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
this.onError(e);
|
|
}
|
|
if (null != data) {
|
|
this.onData(data);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Check if it has XDomainRequest.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Request.prototype.hasXDR = function () {
|
|
return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
|
|
};
|
|
|
|
/**
|
|
* Aborts the request.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Request.prototype.abort = function () {
|
|
this.cleanup();
|
|
};
|
|
|
|
/**
|
|
* Aborts pending requests when unloading the window. This is needed to prevent
|
|
* memory leaks (e.g. when using IE) and to ensure that no spurious error is
|
|
* emitted.
|
|
*/
|
|
|
|
Request.requestsCount = 0;
|
|
Request.requests = {};
|
|
|
|
if (global.document) {
|
|
if (global.attachEvent) {
|
|
global.attachEvent('onunload', unloadHandler);
|
|
} else if (global.addEventListener) {
|
|
global.addEventListener('beforeunload', unloadHandler, false);
|
|
}
|
|
}
|
|
|
|
function unloadHandler () {
|
|
for (var i in Request.requests) {
|
|
if (Request.requests.hasOwnProperty(i)) {
|
|
Request.requests[i].abort();
|
|
}
|
|
}
|
|
}
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 21 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var Transport = __webpack_require__(22);
|
|
var parseqs = __webpack_require__(32);
|
|
var parser = __webpack_require__(23);
|
|
var inherit = __webpack_require__(33);
|
|
var yeast = __webpack_require__(34);
|
|
var debug = __webpack_require__(3)('engine.io-client:polling');
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = Polling;
|
|
|
|
/**
|
|
* Is XHR2 supported?
|
|
*/
|
|
|
|
var hasXHR2 = (function () {
|
|
var XMLHttpRequest = __webpack_require__(18);
|
|
var xhr = new XMLHttpRequest({ xdomain: false });
|
|
return null != xhr.responseType;
|
|
})();
|
|
|
|
/**
|
|
* Polling interface.
|
|
*
|
|
* @param {Object} opts
|
|
* @api private
|
|
*/
|
|
|
|
function Polling (opts) {
|
|
var forceBase64 = (opts && opts.forceBase64);
|
|
if (!hasXHR2 || forceBase64) {
|
|
this.supportsBinary = false;
|
|
}
|
|
Transport.call(this, opts);
|
|
}
|
|
|
|
/**
|
|
* Inherits from Transport.
|
|
*/
|
|
|
|
inherit(Polling, Transport);
|
|
|
|
/**
|
|
* Transport name.
|
|
*/
|
|
|
|
Polling.prototype.name = 'polling';
|
|
|
|
/**
|
|
* Opens the socket (triggers polling). We write a PING message to determine
|
|
* when the transport is open.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Polling.prototype.doOpen = function () {
|
|
this.poll();
|
|
};
|
|
|
|
/**
|
|
* Pauses polling.
|
|
*
|
|
* @param {Function} callback upon buffers are flushed and transport is paused
|
|
* @api private
|
|
*/
|
|
|
|
Polling.prototype.pause = function (onPause) {
|
|
var self = this;
|
|
|
|
this.readyState = 'pausing';
|
|
|
|
function pause () {
|
|
debug('paused');
|
|
self.readyState = 'paused';
|
|
onPause();
|
|
}
|
|
|
|
if (this.polling || !this.writable) {
|
|
var total = 0;
|
|
|
|
if (this.polling) {
|
|
debug('we are currently polling - waiting to pause');
|
|
total++;
|
|
this.once('pollComplete', function () {
|
|
debug('pre-pause polling complete');
|
|
--total || pause();
|
|
});
|
|
}
|
|
|
|
if (!this.writable) {
|
|
debug('we are currently writing - waiting to pause');
|
|
total++;
|
|
this.once('drain', function () {
|
|
debug('pre-pause writing complete');
|
|
--total || pause();
|
|
});
|
|
}
|
|
} else {
|
|
pause();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Starts polling cycle.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Polling.prototype.poll = function () {
|
|
debug('polling');
|
|
this.polling = true;
|
|
this.doPoll();
|
|
this.emit('poll');
|
|
};
|
|
|
|
/**
|
|
* Overloads onData to detect payloads.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Polling.prototype.onData = function (data) {
|
|
var self = this;
|
|
debug('polling got data %s', data);
|
|
var callback = function (packet, index, total) {
|
|
// if its the first message we consider the transport open
|
|
if ('opening' === self.readyState) {
|
|
self.onOpen();
|
|
}
|
|
|
|
// if its a close packet, we close the ongoing requests
|
|
if ('close' === packet.type) {
|
|
self.onClose();
|
|
return false;
|
|
}
|
|
|
|
// otherwise bypass onData and handle the message
|
|
self.onPacket(packet);
|
|
};
|
|
|
|
// decode payload
|
|
parser.decodePayload(data, this.socket.binaryType, callback);
|
|
|
|
// if an event did not trigger closing
|
|
if ('closed' !== this.readyState) {
|
|
// if we got data we're not polling
|
|
this.polling = false;
|
|
this.emit('pollComplete');
|
|
|
|
if ('open' === this.readyState) {
|
|
this.poll();
|
|
} else {
|
|
debug('ignoring poll - transport state "%s"', this.readyState);
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* For polling, send a close packet.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Polling.prototype.doClose = function () {
|
|
var self = this;
|
|
|
|
function close () {
|
|
debug('writing close packet');
|
|
self.write([{ type: 'close' }]);
|
|
}
|
|
|
|
if ('open' === this.readyState) {
|
|
debug('transport open - closing');
|
|
close();
|
|
} else {
|
|
// in case we're trying to close while
|
|
// handshaking is in progress (GH-164)
|
|
debug('transport not open - deferring close');
|
|
this.once('open', close);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Writes a packets payload.
|
|
*
|
|
* @param {Array} data packets
|
|
* @param {Function} drain callback
|
|
* @api private
|
|
*/
|
|
|
|
Polling.prototype.write = function (packets) {
|
|
var self = this;
|
|
this.writable = false;
|
|
var callbackfn = function () {
|
|
self.writable = true;
|
|
self.emit('drain');
|
|
};
|
|
|
|
parser.encodePayload(packets, this.supportsBinary, function (data) {
|
|
self.doWrite(data, callbackfn);
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Generates uri for connection.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Polling.prototype.uri = function () {
|
|
var query = this.query || {};
|
|
var schema = this.secure ? 'https' : 'http';
|
|
var port = '';
|
|
|
|
// cache busting is forced
|
|
if (false !== this.timestampRequests) {
|
|
query[this.timestampParam] = yeast();
|
|
}
|
|
|
|
if (!this.supportsBinary && !query.sid) {
|
|
query.b64 = 1;
|
|
}
|
|
|
|
query = parseqs.encode(query);
|
|
|
|
// avoid port if default for schema
|
|
if (this.port && (('https' === schema && this.port !== 443) ||
|
|
('http' === schema && this.port !== 80))) {
|
|
port = ':' + this.port;
|
|
}
|
|
|
|
// prepend ? to query
|
|
if (query.length) {
|
|
query = '?' + query;
|
|
}
|
|
|
|
var ipv6 = this.hostname.indexOf(':') !== -1;
|
|
return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 22 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var parser = __webpack_require__(23);
|
|
var Emitter = __webpack_require__(31);
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = Transport;
|
|
|
|
/**
|
|
* Transport abstract constructor.
|
|
*
|
|
* @param {Object} options.
|
|
* @api private
|
|
*/
|
|
|
|
function Transport (opts) {
|
|
this.path = opts.path;
|
|
this.hostname = opts.hostname;
|
|
this.port = opts.port;
|
|
this.secure = opts.secure;
|
|
this.query = opts.query;
|
|
this.timestampParam = opts.timestampParam;
|
|
this.timestampRequests = opts.timestampRequests;
|
|
this.readyState = '';
|
|
this.agent = opts.agent || false;
|
|
this.socket = opts.socket;
|
|
this.enablesXDR = opts.enablesXDR;
|
|
|
|
// SSL options for Node.js client
|
|
this.pfx = opts.pfx;
|
|
this.key = opts.key;
|
|
this.passphrase = opts.passphrase;
|
|
this.cert = opts.cert;
|
|
this.ca = opts.ca;
|
|
this.ciphers = opts.ciphers;
|
|
this.rejectUnauthorized = opts.rejectUnauthorized;
|
|
|
|
// other options for Node.js client
|
|
this.extraHeaders = opts.extraHeaders;
|
|
}
|
|
|
|
/**
|
|
* Mix in `Emitter`.
|
|
*/
|
|
|
|
Emitter(Transport.prototype);
|
|
|
|
/**
|
|
* Emits an error.
|
|
*
|
|
* @param {String} str
|
|
* @return {Transport} for chaining
|
|
* @api public
|
|
*/
|
|
|
|
Transport.prototype.onError = function (msg, desc) {
|
|
var err = new Error(msg);
|
|
err.type = 'TransportError';
|
|
err.description = desc;
|
|
this.emit('error', err);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Opens the transport.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Transport.prototype.open = function () {
|
|
if ('closed' === this.readyState || '' === this.readyState) {
|
|
this.readyState = 'opening';
|
|
this.doOpen();
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Closes the transport.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Transport.prototype.close = function () {
|
|
if ('opening' === this.readyState || 'open' === this.readyState) {
|
|
this.doClose();
|
|
this.onClose();
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sends multiple packets.
|
|
*
|
|
* @param {Array} packets
|
|
* @api private
|
|
*/
|
|
|
|
Transport.prototype.send = function (packets) {
|
|
if ('open' === this.readyState) {
|
|
this.write(packets);
|
|
} else {
|
|
throw new Error('Transport not open');
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon open
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Transport.prototype.onOpen = function () {
|
|
this.readyState = 'open';
|
|
this.writable = true;
|
|
this.emit('open');
|
|
};
|
|
|
|
/**
|
|
* Called with data.
|
|
*
|
|
* @param {String} data
|
|
* @api private
|
|
*/
|
|
|
|
Transport.prototype.onData = function (data) {
|
|
var packet = parser.decodePacket(data, this.socket.binaryType);
|
|
this.onPacket(packet);
|
|
};
|
|
|
|
/**
|
|
* Called with a decoded packet.
|
|
*/
|
|
|
|
Transport.prototype.onPacket = function (packet) {
|
|
this.emit('packet', packet);
|
|
};
|
|
|
|
/**
|
|
* Called upon close.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Transport.prototype.onClose = function () {
|
|
this.readyState = 'closed';
|
|
this.emit('close');
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 23 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var keys = __webpack_require__(24);
|
|
var hasBinary = __webpack_require__(25);
|
|
var sliceBuffer = __webpack_require__(26);
|
|
var after = __webpack_require__(27);
|
|
var utf8 = __webpack_require__(28);
|
|
|
|
var base64encoder;
|
|
if (global && global.ArrayBuffer) {
|
|
base64encoder = __webpack_require__(29);
|
|
}
|
|
|
|
/**
|
|
* Check if we are running an android browser. That requires us to use
|
|
* ArrayBuffer with polling transports...
|
|
*
|
|
* http://ghinda.net/jpeg-blob-ajax-android/
|
|
*/
|
|
|
|
var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
|
|
|
|
/**
|
|
* Check if we are running in PhantomJS.
|
|
* Uploading a Blob with PhantomJS does not work correctly, as reported here:
|
|
* https://github.com/ariya/phantomjs/issues/11395
|
|
* @type boolean
|
|
*/
|
|
var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
|
|
|
|
/**
|
|
* When true, avoids using Blobs to encode payloads.
|
|
* @type boolean
|
|
*/
|
|
var dontSendBlobs = isAndroid || isPhantomJS;
|
|
|
|
/**
|
|
* Current protocol version.
|
|
*/
|
|
|
|
exports.protocol = 3;
|
|
|
|
/**
|
|
* Packet types.
|
|
*/
|
|
|
|
var packets = exports.packets = {
|
|
open: 0 // non-ws
|
|
, close: 1 // non-ws
|
|
, ping: 2
|
|
, pong: 3
|
|
, message: 4
|
|
, upgrade: 5
|
|
, noop: 6
|
|
};
|
|
|
|
var packetslist = keys(packets);
|
|
|
|
/**
|
|
* Premade error packet.
|
|
*/
|
|
|
|
var err = { type: 'error', data: 'parser error' };
|
|
|
|
/**
|
|
* Create a blob api even for blob builder when vendor prefixes exist
|
|
*/
|
|
|
|
var Blob = __webpack_require__(30);
|
|
|
|
/**
|
|
* Encodes a packet.
|
|
*
|
|
* <packet type id> [ <data> ]
|
|
*
|
|
* Example:
|
|
*
|
|
* 5hello world
|
|
* 3
|
|
* 4
|
|
*
|
|
* Binary is encoded in an identical principle
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
|
|
if ('function' == typeof supportsBinary) {
|
|
callback = supportsBinary;
|
|
supportsBinary = false;
|
|
}
|
|
|
|
if ('function' == typeof utf8encode) {
|
|
callback = utf8encode;
|
|
utf8encode = null;
|
|
}
|
|
|
|
var data = (packet.data === undefined)
|
|
? undefined
|
|
: packet.data.buffer || packet.data;
|
|
|
|
if (global.ArrayBuffer && data instanceof ArrayBuffer) {
|
|
return encodeArrayBuffer(packet, supportsBinary, callback);
|
|
} else if (Blob && data instanceof global.Blob) {
|
|
return encodeBlob(packet, supportsBinary, callback);
|
|
}
|
|
|
|
// might be an object with { base64: true, data: dataAsBase64String }
|
|
if (data && data.base64) {
|
|
return encodeBase64Object(packet, callback);
|
|
}
|
|
|
|
// Sending data as a utf-8 string
|
|
var encoded = packets[packet.type];
|
|
|
|
// data fragment is optional
|
|
if (undefined !== packet.data) {
|
|
encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
|
|
}
|
|
|
|
return callback('' + encoded);
|
|
|
|
};
|
|
|
|
function encodeBase64Object(packet, callback) {
|
|
// packet data is an object { base64: true, data: dataAsBase64String }
|
|
var message = 'b' + exports.packets[packet.type] + packet.data.data;
|
|
return callback(message);
|
|
}
|
|
|
|
/**
|
|
* Encode packet helpers for binary types
|
|
*/
|
|
|
|
function encodeArrayBuffer(packet, supportsBinary, callback) {
|
|
if (!supportsBinary) {
|
|
return exports.encodeBase64Packet(packet, callback);
|
|
}
|
|
|
|
var data = packet.data;
|
|
var contentArray = new Uint8Array(data);
|
|
var resultBuffer = new Uint8Array(1 + data.byteLength);
|
|
|
|
resultBuffer[0] = packets[packet.type];
|
|
for (var i = 0; i < contentArray.length; i++) {
|
|
resultBuffer[i+1] = contentArray[i];
|
|
}
|
|
|
|
return callback(resultBuffer.buffer);
|
|
}
|
|
|
|
function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
|
|
if (!supportsBinary) {
|
|
return exports.encodeBase64Packet(packet, callback);
|
|
}
|
|
|
|
var fr = new FileReader();
|
|
fr.onload = function() {
|
|
packet.data = fr.result;
|
|
exports.encodePacket(packet, supportsBinary, true, callback);
|
|
};
|
|
return fr.readAsArrayBuffer(packet.data);
|
|
}
|
|
|
|
function encodeBlob(packet, supportsBinary, callback) {
|
|
if (!supportsBinary) {
|
|
return exports.encodeBase64Packet(packet, callback);
|
|
}
|
|
|
|
if (dontSendBlobs) {
|
|
return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
|
|
}
|
|
|
|
var length = new Uint8Array(1);
|
|
length[0] = packets[packet.type];
|
|
var blob = new Blob([length.buffer, packet.data]);
|
|
|
|
return callback(blob);
|
|
}
|
|
|
|
/**
|
|
* Encodes a packet with binary data in a base64 string
|
|
*
|
|
* @param {Object} packet, has `type` and `data`
|
|
* @return {String} base64 encoded message
|
|
*/
|
|
|
|
exports.encodeBase64Packet = function(packet, callback) {
|
|
var message = 'b' + exports.packets[packet.type];
|
|
if (Blob && packet.data instanceof global.Blob) {
|
|
var fr = new FileReader();
|
|
fr.onload = function() {
|
|
var b64 = fr.result.split(',')[1];
|
|
callback(message + b64);
|
|
};
|
|
return fr.readAsDataURL(packet.data);
|
|
}
|
|
|
|
var b64data;
|
|
try {
|
|
b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
|
|
} catch (e) {
|
|
// iPhone Safari doesn't let you apply with typed arrays
|
|
var typed = new Uint8Array(packet.data);
|
|
var basic = new Array(typed.length);
|
|
for (var i = 0; i < typed.length; i++) {
|
|
basic[i] = typed[i];
|
|
}
|
|
b64data = String.fromCharCode.apply(null, basic);
|
|
}
|
|
message += global.btoa(b64data);
|
|
return callback(message);
|
|
};
|
|
|
|
/**
|
|
* Decodes a packet. Changes format to Blob if requested.
|
|
*
|
|
* @return {Object} with `type` and `data` (if any)
|
|
* @api private
|
|
*/
|
|
|
|
exports.decodePacket = function (data, binaryType, utf8decode) {
|
|
if (data === undefined) {
|
|
return err;
|
|
}
|
|
// String data
|
|
if (typeof data == 'string') {
|
|
if (data.charAt(0) == 'b') {
|
|
return exports.decodeBase64Packet(data.substr(1), binaryType);
|
|
}
|
|
|
|
if (utf8decode) {
|
|
data = tryDecode(data);
|
|
if (data === false) {
|
|
return err;
|
|
}
|
|
}
|
|
var type = data.charAt(0);
|
|
|
|
if (Number(type) != type || !packetslist[type]) {
|
|
return err;
|
|
}
|
|
|
|
if (data.length > 1) {
|
|
return { type: packetslist[type], data: data.substring(1) };
|
|
} else {
|
|
return { type: packetslist[type] };
|
|
}
|
|
}
|
|
|
|
var asArray = new Uint8Array(data);
|
|
var type = asArray[0];
|
|
var rest = sliceBuffer(data, 1);
|
|
if (Blob && binaryType === 'blob') {
|
|
rest = new Blob([rest]);
|
|
}
|
|
return { type: packetslist[type], data: rest };
|
|
};
|
|
|
|
function tryDecode(data) {
|
|
try {
|
|
data = utf8.decode(data);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
/**
|
|
* Decodes a packet encoded in a base64 string
|
|
*
|
|
* @param {String} base64 encoded message
|
|
* @return {Object} with `type` and `data` (if any)
|
|
*/
|
|
|
|
exports.decodeBase64Packet = function(msg, binaryType) {
|
|
var type = packetslist[msg.charAt(0)];
|
|
if (!base64encoder) {
|
|
return { type: type, data: { base64: true, data: msg.substr(1) } };
|
|
}
|
|
|
|
var data = base64encoder.decode(msg.substr(1));
|
|
|
|
if (binaryType === 'blob' && Blob) {
|
|
data = new Blob([data]);
|
|
}
|
|
|
|
return { type: type, data: data };
|
|
};
|
|
|
|
/**
|
|
* Encodes multiple messages (payload).
|
|
*
|
|
* <length>:data
|
|
*
|
|
* Example:
|
|
*
|
|
* 11:hello world2:hi
|
|
*
|
|
* If any contents are binary, they will be encoded as base64 strings. Base64
|
|
* encoded strings are marked with a b before the length specifier
|
|
*
|
|
* @param {Array} packets
|
|
* @api private
|
|
*/
|
|
|
|
exports.encodePayload = function (packets, supportsBinary, callback) {
|
|
if (typeof supportsBinary == 'function') {
|
|
callback = supportsBinary;
|
|
supportsBinary = null;
|
|
}
|
|
|
|
var isBinary = hasBinary(packets);
|
|
|
|
if (supportsBinary && isBinary) {
|
|
if (Blob && !dontSendBlobs) {
|
|
return exports.encodePayloadAsBlob(packets, callback);
|
|
}
|
|
|
|
return exports.encodePayloadAsArrayBuffer(packets, callback);
|
|
}
|
|
|
|
if (!packets.length) {
|
|
return callback('0:');
|
|
}
|
|
|
|
function setLengthHeader(message) {
|
|
return message.length + ':' + message;
|
|
}
|
|
|
|
function encodeOne(packet, doneCallback) {
|
|
exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
|
|
doneCallback(null, setLengthHeader(message));
|
|
});
|
|
}
|
|
|
|
map(packets, encodeOne, function(err, results) {
|
|
return callback(results.join(''));
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Async array map using after
|
|
*/
|
|
|
|
function map(ary, each, done) {
|
|
var result = new Array(ary.length);
|
|
var next = after(ary.length, done);
|
|
|
|
var eachWithIndex = function(i, el, cb) {
|
|
each(el, function(error, msg) {
|
|
result[i] = msg;
|
|
cb(error, result);
|
|
});
|
|
};
|
|
|
|
for (var i = 0; i < ary.length; i++) {
|
|
eachWithIndex(i, ary[i], next);
|
|
}
|
|
}
|
|
|
|
/*
|
|
* Decodes data when a payload is maybe expected. Possible binary contents are
|
|
* decoded from their base64 representation
|
|
*
|
|
* @param {String} data, callback method
|
|
* @api public
|
|
*/
|
|
|
|
exports.decodePayload = function (data, binaryType, callback) {
|
|
if (typeof data != 'string') {
|
|
return exports.decodePayloadAsBinary(data, binaryType, callback);
|
|
}
|
|
|
|
if (typeof binaryType === 'function') {
|
|
callback = binaryType;
|
|
binaryType = null;
|
|
}
|
|
|
|
var packet;
|
|
if (data == '') {
|
|
// parser error - ignoring payload
|
|
return callback(err, 0, 1);
|
|
}
|
|
|
|
var length = ''
|
|
, n, msg;
|
|
|
|
for (var i = 0, l = data.length; i < l; i++) {
|
|
var chr = data.charAt(i);
|
|
|
|
if (':' != chr) {
|
|
length += chr;
|
|
} else {
|
|
if ('' == length || (length != (n = Number(length)))) {
|
|
// parser error - ignoring payload
|
|
return callback(err, 0, 1);
|
|
}
|
|
|
|
msg = data.substr(i + 1, n);
|
|
|
|
if (length != msg.length) {
|
|
// parser error - ignoring payload
|
|
return callback(err, 0, 1);
|
|
}
|
|
|
|
if (msg.length) {
|
|
packet = exports.decodePacket(msg, binaryType, true);
|
|
|
|
if (err.type == packet.type && err.data == packet.data) {
|
|
// parser error in individual packet - ignoring payload
|
|
return callback(err, 0, 1);
|
|
}
|
|
|
|
var ret = callback(packet, i + n, l);
|
|
if (false === ret) return;
|
|
}
|
|
|
|
// advance cursor
|
|
i += n;
|
|
length = '';
|
|
}
|
|
}
|
|
|
|
if (length != '') {
|
|
// parser error - ignoring payload
|
|
return callback(err, 0, 1);
|
|
}
|
|
|
|
};
|
|
|
|
/**
|
|
* Encodes multiple messages (payload) as binary.
|
|
*
|
|
* <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
|
|
* 255><data>
|
|
*
|
|
* Example:
|
|
* 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
|
|
*
|
|
* @param {Array} packets
|
|
* @return {ArrayBuffer} encoded payload
|
|
* @api private
|
|
*/
|
|
|
|
exports.encodePayloadAsArrayBuffer = function(packets, callback) {
|
|
if (!packets.length) {
|
|
return callback(new ArrayBuffer(0));
|
|
}
|
|
|
|
function encodeOne(packet, doneCallback) {
|
|
exports.encodePacket(packet, true, true, function(data) {
|
|
return doneCallback(null, data);
|
|
});
|
|
}
|
|
|
|
map(packets, encodeOne, function(err, encodedPackets) {
|
|
var totalLength = encodedPackets.reduce(function(acc, p) {
|
|
var len;
|
|
if (typeof p === 'string'){
|
|
len = p.length;
|
|
} else {
|
|
len = p.byteLength;
|
|
}
|
|
return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
|
|
}, 0);
|
|
|
|
var resultArray = new Uint8Array(totalLength);
|
|
|
|
var bufferIndex = 0;
|
|
encodedPackets.forEach(function(p) {
|
|
var isString = typeof p === 'string';
|
|
var ab = p;
|
|
if (isString) {
|
|
var view = new Uint8Array(p.length);
|
|
for (var i = 0; i < p.length; i++) {
|
|
view[i] = p.charCodeAt(i);
|
|
}
|
|
ab = view.buffer;
|
|
}
|
|
|
|
if (isString) { // not true binary
|
|
resultArray[bufferIndex++] = 0;
|
|
} else { // true binary
|
|
resultArray[bufferIndex++] = 1;
|
|
}
|
|
|
|
var lenStr = ab.byteLength.toString();
|
|
for (var i = 0; i < lenStr.length; i++) {
|
|
resultArray[bufferIndex++] = parseInt(lenStr[i]);
|
|
}
|
|
resultArray[bufferIndex++] = 255;
|
|
|
|
var view = new Uint8Array(ab);
|
|
for (var i = 0; i < view.length; i++) {
|
|
resultArray[bufferIndex++] = view[i];
|
|
}
|
|
});
|
|
|
|
return callback(resultArray.buffer);
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Encode as Blob
|
|
*/
|
|
|
|
exports.encodePayloadAsBlob = function(packets, callback) {
|
|
function encodeOne(packet, doneCallback) {
|
|
exports.encodePacket(packet, true, true, function(encoded) {
|
|
var binaryIdentifier = new Uint8Array(1);
|
|
binaryIdentifier[0] = 1;
|
|
if (typeof encoded === 'string') {
|
|
var view = new Uint8Array(encoded.length);
|
|
for (var i = 0; i < encoded.length; i++) {
|
|
view[i] = encoded.charCodeAt(i);
|
|
}
|
|
encoded = view.buffer;
|
|
binaryIdentifier[0] = 0;
|
|
}
|
|
|
|
var len = (encoded instanceof ArrayBuffer)
|
|
? encoded.byteLength
|
|
: encoded.size;
|
|
|
|
var lenStr = len.toString();
|
|
var lengthAry = new Uint8Array(lenStr.length + 1);
|
|
for (var i = 0; i < lenStr.length; i++) {
|
|
lengthAry[i] = parseInt(lenStr[i]);
|
|
}
|
|
lengthAry[lenStr.length] = 255;
|
|
|
|
if (Blob) {
|
|
var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
|
|
doneCallback(null, blob);
|
|
}
|
|
});
|
|
}
|
|
|
|
map(packets, encodeOne, function(err, results) {
|
|
return callback(new Blob(results));
|
|
});
|
|
};
|
|
|
|
/*
|
|
* Decodes data when a payload is maybe expected. Strings are decoded by
|
|
* interpreting each byte as a key code for entries marked to start with 0. See
|
|
* description of encodePayloadAsBinary
|
|
*
|
|
* @param {ArrayBuffer} data, callback method
|
|
* @api public
|
|
*/
|
|
|
|
exports.decodePayloadAsBinary = function (data, binaryType, callback) {
|
|
if (typeof binaryType === 'function') {
|
|
callback = binaryType;
|
|
binaryType = null;
|
|
}
|
|
|
|
var bufferTail = data;
|
|
var buffers = [];
|
|
|
|
var numberTooLong = false;
|
|
while (bufferTail.byteLength > 0) {
|
|
var tailArray = new Uint8Array(bufferTail);
|
|
var isString = tailArray[0] === 0;
|
|
var msgLength = '';
|
|
|
|
for (var i = 1; ; i++) {
|
|
if (tailArray[i] == 255) break;
|
|
|
|
if (msgLength.length > 310) {
|
|
numberTooLong = true;
|
|
break;
|
|
}
|
|
|
|
msgLength += tailArray[i];
|
|
}
|
|
|
|
if(numberTooLong) return callback(err, 0, 1);
|
|
|
|
bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
|
|
msgLength = parseInt(msgLength);
|
|
|
|
var msg = sliceBuffer(bufferTail, 0, msgLength);
|
|
if (isString) {
|
|
try {
|
|
msg = String.fromCharCode.apply(null, new Uint8Array(msg));
|
|
} catch (e) {
|
|
// iPhone Safari doesn't let you apply to typed arrays
|
|
var typed = new Uint8Array(msg);
|
|
msg = '';
|
|
for (var i = 0; i < typed.length; i++) {
|
|
msg += String.fromCharCode(typed[i]);
|
|
}
|
|
}
|
|
}
|
|
|
|
buffers.push(msg);
|
|
bufferTail = sliceBuffer(bufferTail, msgLength);
|
|
}
|
|
|
|
var total = buffers.length;
|
|
buffers.forEach(function(buffer, i) {
|
|
callback(exports.decodePacket(buffer, binaryType, true), i, total);
|
|
});
|
|
};
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 24 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
/**
|
|
* Gets the keys for an object.
|
|
*
|
|
* @return {Array} keys
|
|
* @api private
|
|
*/
|
|
|
|
module.exports = Object.keys || function keys (obj){
|
|
var arr = [];
|
|
var has = Object.prototype.hasOwnProperty;
|
|
|
|
for (var i in obj) {
|
|
if (has.call(obj, i)) {
|
|
arr.push(i);
|
|
}
|
|
}
|
|
return arr;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 25 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {
|
|
/*
|
|
* Module requirements.
|
|
*/
|
|
|
|
var isArray = __webpack_require__(9);
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = hasBinary;
|
|
|
|
/**
|
|
* Checks for binary data.
|
|
*
|
|
* Right now only Buffer and ArrayBuffer are supported..
|
|
*
|
|
* @param {Object} anything
|
|
* @api public
|
|
*/
|
|
|
|
function hasBinary(data) {
|
|
|
|
function _hasBinary(obj) {
|
|
if (!obj) return false;
|
|
|
|
if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
|
|
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
|
|
(global.Blob && obj instanceof Blob) ||
|
|
(global.File && obj instanceof File)
|
|
) {
|
|
return true;
|
|
}
|
|
|
|
if (isArray(obj)) {
|
|
for (var i = 0; i < obj.length; i++) {
|
|
if (_hasBinary(obj[i])) {
|
|
return true;
|
|
}
|
|
}
|
|
} else if (obj && 'object' == typeof obj) {
|
|
if (obj.toJSON) {
|
|
obj = obj.toJSON();
|
|
}
|
|
|
|
for (var key in obj) {
|
|
if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
return _hasBinary(data);
|
|
}
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 26 */
|
|
/***/ function(module, exports) {
|
|
|
|
/**
|
|
* An abstraction for slicing an arraybuffer even when
|
|
* ArrayBuffer.prototype.slice is not supported
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
module.exports = function(arraybuffer, start, end) {
|
|
var bytes = arraybuffer.byteLength;
|
|
start = start || 0;
|
|
end = end || bytes;
|
|
|
|
if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
|
|
|
|
if (start < 0) { start += bytes; }
|
|
if (end < 0) { end += bytes; }
|
|
if (end > bytes) { end = bytes; }
|
|
|
|
if (start >= bytes || start >= end || bytes === 0) {
|
|
return new ArrayBuffer(0);
|
|
}
|
|
|
|
var abv = new Uint8Array(arraybuffer);
|
|
var result = new Uint8Array(end - start);
|
|
for (var i = start, ii = 0; i < end; i++, ii++) {
|
|
result[ii] = abv[i];
|
|
}
|
|
return result.buffer;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 27 */
|
|
/***/ function(module, exports) {
|
|
|
|
module.exports = after
|
|
|
|
function after(count, callback, err_cb) {
|
|
var bail = false
|
|
err_cb = err_cb || noop
|
|
proxy.count = count
|
|
|
|
return (count === 0) ? callback() : proxy
|
|
|
|
function proxy(err, result) {
|
|
if (proxy.count <= 0) {
|
|
throw new Error('after called too many times')
|
|
}
|
|
--proxy.count
|
|
|
|
// after first error, rest are passed to err_cb
|
|
if (err) {
|
|
bail = true
|
|
callback(err)
|
|
// future error callbacks will go to error handler
|
|
callback = err_cb
|
|
} else if (proxy.count === 0 && !bail) {
|
|
callback(null, result)
|
|
}
|
|
}
|
|
}
|
|
|
|
function noop() {}
|
|
|
|
|
|
/***/ },
|
|
/* 28 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/wtf8 v1.0.0 by @mathias */
|
|
;(function(root) {
|
|
|
|
// Detect free variables `exports`
|
|
var freeExports = typeof exports == 'object' && exports;
|
|
|
|
// Detect free variable `module`
|
|
var freeModule = typeof module == 'object' && module &&
|
|
module.exports == freeExports && module;
|
|
|
|
// Detect free variable `global`, from Node.js or Browserified code,
|
|
// and use it as `root`
|
|
var freeGlobal = typeof global == 'object' && global;
|
|
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
|
|
root = freeGlobal;
|
|
}
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
var stringFromCharCode = String.fromCharCode;
|
|
|
|
// Taken from https://mths.be/punycode
|
|
function ucs2decode(string) {
|
|
var output = [];
|
|
var counter = 0;
|
|
var length = string.length;
|
|
var value;
|
|
var extra;
|
|
while (counter < length) {
|
|
value = string.charCodeAt(counter++);
|
|
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
|
|
// high surrogate, and there is a next character
|
|
extra = string.charCodeAt(counter++);
|
|
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
|
|
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
|
|
} else {
|
|
// unmatched surrogate; only append this code unit, in case the next
|
|
// code unit is the high surrogate of a surrogate pair
|
|
output.push(value);
|
|
counter--;
|
|
}
|
|
} else {
|
|
output.push(value);
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
|
|
// Taken from https://mths.be/punycode
|
|
function ucs2encode(array) {
|
|
var length = array.length;
|
|
var index = -1;
|
|
var value;
|
|
var output = '';
|
|
while (++index < length) {
|
|
value = array[index];
|
|
if (value > 0xFFFF) {
|
|
value -= 0x10000;
|
|
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
|
|
value = 0xDC00 | value & 0x3FF;
|
|
}
|
|
output += stringFromCharCode(value);
|
|
}
|
|
return output;
|
|
}
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
function createByte(codePoint, shift) {
|
|
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
|
|
}
|
|
|
|
function encodeCodePoint(codePoint) {
|
|
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
|
|
return stringFromCharCode(codePoint);
|
|
}
|
|
var symbol = '';
|
|
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
|
|
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
|
|
}
|
|
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
|
|
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
|
|
symbol += createByte(codePoint, 6);
|
|
}
|
|
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
|
|
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
|
|
symbol += createByte(codePoint, 12);
|
|
symbol += createByte(codePoint, 6);
|
|
}
|
|
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
|
|
return symbol;
|
|
}
|
|
|
|
function wtf8encode(string) {
|
|
var codePoints = ucs2decode(string);
|
|
var length = codePoints.length;
|
|
var index = -1;
|
|
var codePoint;
|
|
var byteString = '';
|
|
while (++index < length) {
|
|
codePoint = codePoints[index];
|
|
byteString += encodeCodePoint(codePoint);
|
|
}
|
|
return byteString;
|
|
}
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
function readContinuationByte() {
|
|
if (byteIndex >= byteCount) {
|
|
throw Error('Invalid byte index');
|
|
}
|
|
|
|
var continuationByte = byteArray[byteIndex] & 0xFF;
|
|
byteIndex++;
|
|
|
|
if ((continuationByte & 0xC0) == 0x80) {
|
|
return continuationByte & 0x3F;
|
|
}
|
|
|
|
// If we end up here, it’s not a continuation byte.
|
|
throw Error('Invalid continuation byte');
|
|
}
|
|
|
|
function decodeSymbol() {
|
|
var byte1;
|
|
var byte2;
|
|
var byte3;
|
|
var byte4;
|
|
var codePoint;
|
|
|
|
if (byteIndex > byteCount) {
|
|
throw Error('Invalid byte index');
|
|
}
|
|
|
|
if (byteIndex == byteCount) {
|
|
return false;
|
|
}
|
|
|
|
// Read the first byte.
|
|
byte1 = byteArray[byteIndex] & 0xFF;
|
|
byteIndex++;
|
|
|
|
// 1-byte sequence (no continuation bytes)
|
|
if ((byte1 & 0x80) == 0) {
|
|
return byte1;
|
|
}
|
|
|
|
// 2-byte sequence
|
|
if ((byte1 & 0xE0) == 0xC0) {
|
|
var byte2 = readContinuationByte();
|
|
codePoint = ((byte1 & 0x1F) << 6) | byte2;
|
|
if (codePoint >= 0x80) {
|
|
return codePoint;
|
|
} else {
|
|
throw Error('Invalid continuation byte');
|
|
}
|
|
}
|
|
|
|
// 3-byte sequence (may include unpaired surrogates)
|
|
if ((byte1 & 0xF0) == 0xE0) {
|
|
byte2 = readContinuationByte();
|
|
byte3 = readContinuationByte();
|
|
codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
|
|
if (codePoint >= 0x0800) {
|
|
return codePoint;
|
|
} else {
|
|
throw Error('Invalid continuation byte');
|
|
}
|
|
}
|
|
|
|
// 4-byte sequence
|
|
if ((byte1 & 0xF8) == 0xF0) {
|
|
byte2 = readContinuationByte();
|
|
byte3 = readContinuationByte();
|
|
byte4 = readContinuationByte();
|
|
codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
|
|
(byte3 << 0x06) | byte4;
|
|
if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
|
|
return codePoint;
|
|
}
|
|
}
|
|
|
|
throw Error('Invalid WTF-8 detected');
|
|
}
|
|
|
|
var byteArray;
|
|
var byteCount;
|
|
var byteIndex;
|
|
function wtf8decode(byteString) {
|
|
byteArray = ucs2decode(byteString);
|
|
byteCount = byteArray.length;
|
|
byteIndex = 0;
|
|
var codePoints = [];
|
|
var tmp;
|
|
while ((tmp = decodeSymbol()) !== false) {
|
|
codePoints.push(tmp);
|
|
}
|
|
return ucs2encode(codePoints);
|
|
}
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
var wtf8 = {
|
|
'version': '1.0.0',
|
|
'encode': wtf8encode,
|
|
'decode': wtf8decode
|
|
};
|
|
|
|
// Some AMD build optimizers, like r.js, check for specific condition patterns
|
|
// like the following:
|
|
if (
|
|
true
|
|
) {
|
|
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
|
|
return wtf8;
|
|
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
|
|
} else if (freeExports && !freeExports.nodeType) {
|
|
if (freeModule) { // in Node.js or RingoJS v0.8.0+
|
|
freeModule.exports = wtf8;
|
|
} else { // in Narwhal or RingoJS v0.7.0-
|
|
var object = {};
|
|
var hasOwnProperty = object.hasOwnProperty;
|
|
for (var key in wtf8) {
|
|
hasOwnProperty.call(wtf8, key) && (freeExports[key] = wtf8[key]);
|
|
}
|
|
}
|
|
} else { // in Rhino or a web browser
|
|
root.wtf8 = wtf8;
|
|
}
|
|
|
|
}(this));
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8)(module), (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 29 */
|
|
/***/ function(module, exports) {
|
|
|
|
/*
|
|
* base64-arraybuffer
|
|
* https://github.com/niklasvh/base64-arraybuffer
|
|
*
|
|
* Copyright (c) 2012 Niklas von Hertzen
|
|
* Licensed under the MIT license.
|
|
*/
|
|
(function(){
|
|
"use strict";
|
|
|
|
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
|
|
// Use a lookup table to find the index.
|
|
var lookup = new Uint8Array(256);
|
|
for (var i = 0; i < chars.length; i++) {
|
|
lookup[chars.charCodeAt(i)] = i;
|
|
}
|
|
|
|
exports.encode = function(arraybuffer) {
|
|
var bytes = new Uint8Array(arraybuffer),
|
|
i, len = bytes.length, base64 = "";
|
|
|
|
for (i = 0; i < len; i+=3) {
|
|
base64 += chars[bytes[i] >> 2];
|
|
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
|
|
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
|
|
base64 += chars[bytes[i + 2] & 63];
|
|
}
|
|
|
|
if ((len % 3) === 2) {
|
|
base64 = base64.substring(0, base64.length - 1) + "=";
|
|
} else if (len % 3 === 1) {
|
|
base64 = base64.substring(0, base64.length - 2) + "==";
|
|
}
|
|
|
|
return base64;
|
|
};
|
|
|
|
exports.decode = function(base64) {
|
|
var bufferLength = base64.length * 0.75,
|
|
len = base64.length, i, p = 0,
|
|
encoded1, encoded2, encoded3, encoded4;
|
|
|
|
if (base64[base64.length - 1] === "=") {
|
|
bufferLength--;
|
|
if (base64[base64.length - 2] === "=") {
|
|
bufferLength--;
|
|
}
|
|
}
|
|
|
|
var arraybuffer = new ArrayBuffer(bufferLength),
|
|
bytes = new Uint8Array(arraybuffer);
|
|
|
|
for (i = 0; i < len; i+=4) {
|
|
encoded1 = lookup[base64.charCodeAt(i)];
|
|
encoded2 = lookup[base64.charCodeAt(i+1)];
|
|
encoded3 = lookup[base64.charCodeAt(i+2)];
|
|
encoded4 = lookup[base64.charCodeAt(i+3)];
|
|
|
|
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
|
|
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
|
|
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
|
|
}
|
|
|
|
return arraybuffer;
|
|
};
|
|
})();
|
|
|
|
|
|
/***/ },
|
|
/* 30 */
|
|
/***/ function(module, exports) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* Create a blob builder even when vendor prefixes exist
|
|
*/
|
|
|
|
var BlobBuilder = global.BlobBuilder
|
|
|| global.WebKitBlobBuilder
|
|
|| global.MSBlobBuilder
|
|
|| global.MozBlobBuilder;
|
|
|
|
/**
|
|
* Check if Blob constructor is supported
|
|
*/
|
|
|
|
var blobSupported = (function() {
|
|
try {
|
|
var a = new Blob(['hi']);
|
|
return a.size === 2;
|
|
} catch(e) {
|
|
return false;
|
|
}
|
|
})();
|
|
|
|
/**
|
|
* Check if Blob constructor supports ArrayBufferViews
|
|
* Fails in Safari 6, so we need to map to ArrayBuffers there.
|
|
*/
|
|
|
|
var blobSupportsArrayBufferView = blobSupported && (function() {
|
|
try {
|
|
var b = new Blob([new Uint8Array([1,2])]);
|
|
return b.size === 2;
|
|
} catch(e) {
|
|
return false;
|
|
}
|
|
})();
|
|
|
|
/**
|
|
* Check if BlobBuilder is supported
|
|
*/
|
|
|
|
var blobBuilderSupported = BlobBuilder
|
|
&& BlobBuilder.prototype.append
|
|
&& BlobBuilder.prototype.getBlob;
|
|
|
|
/**
|
|
* Helper function that maps ArrayBufferViews to ArrayBuffers
|
|
* Used by BlobBuilder constructor and old browsers that didn't
|
|
* support it in the Blob constructor.
|
|
*/
|
|
|
|
function mapArrayBufferViews(ary) {
|
|
for (var i = 0; i < ary.length; i++) {
|
|
var chunk = ary[i];
|
|
if (chunk.buffer instanceof ArrayBuffer) {
|
|
var buf = chunk.buffer;
|
|
|
|
// if this is a subarray, make a copy so we only
|
|
// include the subarray region from the underlying buffer
|
|
if (chunk.byteLength !== buf.byteLength) {
|
|
var copy = new Uint8Array(chunk.byteLength);
|
|
copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
|
|
buf = copy.buffer;
|
|
}
|
|
|
|
ary[i] = buf;
|
|
}
|
|
}
|
|
}
|
|
|
|
function BlobBuilderConstructor(ary, options) {
|
|
options = options || {};
|
|
|
|
var bb = new BlobBuilder();
|
|
mapArrayBufferViews(ary);
|
|
|
|
for (var i = 0; i < ary.length; i++) {
|
|
bb.append(ary[i]);
|
|
}
|
|
|
|
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
|
|
};
|
|
|
|
function BlobConstructor(ary, options) {
|
|
mapArrayBufferViews(ary);
|
|
return new Blob(ary, options || {});
|
|
};
|
|
|
|
module.exports = (function() {
|
|
if (blobSupported) {
|
|
return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
|
|
} else if (blobBuilderSupported) {
|
|
return BlobBuilderConstructor;
|
|
} else {
|
|
return undefined;
|
|
}
|
|
})();
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 31 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
/**
|
|
* Expose `Emitter`.
|
|
*/
|
|
|
|
module.exports = Emitter;
|
|
|
|
/**
|
|
* Initialize a new `Emitter`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function Emitter(obj) {
|
|
if (obj) return mixin(obj);
|
|
};
|
|
|
|
/**
|
|
* Mixin the emitter properties.
|
|
*
|
|
* @param {Object} obj
|
|
* @return {Object}
|
|
* @api private
|
|
*/
|
|
|
|
function mixin(obj) {
|
|
for (var key in Emitter.prototype) {
|
|
obj[key] = Emitter.prototype[key];
|
|
}
|
|
return obj;
|
|
}
|
|
|
|
/**
|
|
* Listen on the given `event` with `fn`.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.on =
|
|
Emitter.prototype.addEventListener = function(event, fn){
|
|
this._callbacks = this._callbacks || {};
|
|
(this._callbacks[event] = this._callbacks[event] || [])
|
|
.push(fn);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Adds an `event` listener that will be invoked a single
|
|
* time then automatically removed.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.once = function(event, fn){
|
|
var self = this;
|
|
this._callbacks = this._callbacks || {};
|
|
|
|
function on() {
|
|
self.off(event, on);
|
|
fn.apply(this, arguments);
|
|
}
|
|
|
|
on.fn = fn;
|
|
this.on(event, on);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Remove the given callback for `event` or all
|
|
* registered callbacks.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.off =
|
|
Emitter.prototype.removeListener =
|
|
Emitter.prototype.removeAllListeners =
|
|
Emitter.prototype.removeEventListener = function(event, fn){
|
|
this._callbacks = this._callbacks || {};
|
|
|
|
// all
|
|
if (0 == arguments.length) {
|
|
this._callbacks = {};
|
|
return this;
|
|
}
|
|
|
|
// specific event
|
|
var callbacks = this._callbacks[event];
|
|
if (!callbacks) return this;
|
|
|
|
// remove all handlers
|
|
if (1 == arguments.length) {
|
|
delete this._callbacks[event];
|
|
return this;
|
|
}
|
|
|
|
// remove specific handler
|
|
var cb;
|
|
for (var i = 0; i < callbacks.length; i++) {
|
|
cb = callbacks[i];
|
|
if (cb === fn || cb.fn === fn) {
|
|
callbacks.splice(i, 1);
|
|
break;
|
|
}
|
|
}
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Emit `event` with the given args.
|
|
*
|
|
* @param {String} event
|
|
* @param {Mixed} ...
|
|
* @return {Emitter}
|
|
*/
|
|
|
|
Emitter.prototype.emit = function(event){
|
|
this._callbacks = this._callbacks || {};
|
|
var args = [].slice.call(arguments, 1)
|
|
, callbacks = this._callbacks[event];
|
|
|
|
if (callbacks) {
|
|
callbacks = callbacks.slice(0);
|
|
for (var i = 0, len = callbacks.length; i < len; ++i) {
|
|
callbacks[i].apply(this, args);
|
|
}
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Return array of callbacks for `event`.
|
|
*
|
|
* @param {String} event
|
|
* @return {Array}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.listeners = function(event){
|
|
this._callbacks = this._callbacks || {};
|
|
return this._callbacks[event] || [];
|
|
};
|
|
|
|
/**
|
|
* Check if this emitter has `event` handlers.
|
|
*
|
|
* @param {String} event
|
|
* @return {Boolean}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.hasListeners = function(event){
|
|
return !! this.listeners(event).length;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 32 */
|
|
/***/ function(module, exports) {
|
|
|
|
/**
|
|
* Compiles a querystring
|
|
* Returns string representation of the object
|
|
*
|
|
* @param {Object}
|
|
* @api private
|
|
*/
|
|
|
|
exports.encode = function (obj) {
|
|
var str = '';
|
|
|
|
for (var i in obj) {
|
|
if (obj.hasOwnProperty(i)) {
|
|
if (str.length) str += '&';
|
|
str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
|
|
}
|
|
}
|
|
|
|
return str;
|
|
};
|
|
|
|
/**
|
|
* Parses a simple querystring into an object
|
|
*
|
|
* @param {String} qs
|
|
* @api private
|
|
*/
|
|
|
|
exports.decode = function(qs){
|
|
var qry = {};
|
|
var pairs = qs.split('&');
|
|
for (var i = 0, l = pairs.length; i < l; i++) {
|
|
var pair = pairs[i].split('=');
|
|
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
|
|
}
|
|
return qry;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 33 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
module.exports = function(a, b){
|
|
var fn = function(){};
|
|
fn.prototype = b.prototype;
|
|
a.prototype = new fn;
|
|
a.prototype.constructor = a;
|
|
};
|
|
|
|
/***/ },
|
|
/* 34 */
|
|
/***/ function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
|
|
, length = 64
|
|
, map = {}
|
|
, seed = 0
|
|
, i = 0
|
|
, prev;
|
|
|
|
/**
|
|
* Return a string representing the specified number.
|
|
*
|
|
* @param {Number} num The number to convert.
|
|
* @returns {String} The string representation of the number.
|
|
* @api public
|
|
*/
|
|
function encode(num) {
|
|
var encoded = '';
|
|
|
|
do {
|
|
encoded = alphabet[num % length] + encoded;
|
|
num = Math.floor(num / length);
|
|
} while (num > 0);
|
|
|
|
return encoded;
|
|
}
|
|
|
|
/**
|
|
* Return the integer value specified by the given string.
|
|
*
|
|
* @param {String} str The string to convert.
|
|
* @returns {Number} The integer value represented by the string.
|
|
* @api public
|
|
*/
|
|
function decode(str) {
|
|
var decoded = 0;
|
|
|
|
for (i = 0; i < str.length; i++) {
|
|
decoded = decoded * length + map[str.charAt(i)];
|
|
}
|
|
|
|
return decoded;
|
|
}
|
|
|
|
/**
|
|
* Yeast: A tiny growing id generator.
|
|
*
|
|
* @returns {String} A unique id.
|
|
* @api public
|
|
*/
|
|
function yeast() {
|
|
var now = encode(+new Date());
|
|
|
|
if (now !== prev) return seed = 0, prev = now;
|
|
return now +'.'+ encode(seed++);
|
|
}
|
|
|
|
//
|
|
// Map each character to its index.
|
|
//
|
|
for (; i < length; i++) map[alphabet[i]] = i;
|
|
|
|
//
|
|
// Expose the `yeast`, `encode` and `decode` functions.
|
|
//
|
|
yeast.encode = encode;
|
|
yeast.decode = decode;
|
|
module.exports = yeast;
|
|
|
|
|
|
/***/ },
|
|
/* 35 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {
|
|
/**
|
|
* Module requirements.
|
|
*/
|
|
|
|
var Polling = __webpack_require__(21);
|
|
var inherit = __webpack_require__(33);
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = JSONPPolling;
|
|
|
|
/**
|
|
* Cached regular expressions.
|
|
*/
|
|
|
|
var rNewline = /\n/g;
|
|
var rEscapedNewline = /\\n/g;
|
|
|
|
/**
|
|
* Global JSONP callbacks.
|
|
*/
|
|
|
|
var callbacks;
|
|
|
|
/**
|
|
* Noop.
|
|
*/
|
|
|
|
function empty () { }
|
|
|
|
/**
|
|
* JSONP Polling constructor.
|
|
*
|
|
* @param {Object} opts.
|
|
* @api public
|
|
*/
|
|
|
|
function JSONPPolling (opts) {
|
|
Polling.call(this, opts);
|
|
|
|
this.query = this.query || {};
|
|
|
|
// define global callbacks array if not present
|
|
// we do this here (lazily) to avoid unneeded global pollution
|
|
if (!callbacks) {
|
|
// we need to consider multiple engines in the same page
|
|
if (!global.___eio) global.___eio = [];
|
|
callbacks = global.___eio;
|
|
}
|
|
|
|
// callback identifier
|
|
this.index = callbacks.length;
|
|
|
|
// add callback to jsonp global
|
|
var self = this;
|
|
callbacks.push(function (msg) {
|
|
self.onData(msg);
|
|
});
|
|
|
|
// append to query string
|
|
this.query.j = this.index;
|
|
|
|
// prevent spurious errors from being emitted when the window is unloaded
|
|
if (global.document && global.addEventListener) {
|
|
global.addEventListener('beforeunload', function () {
|
|
if (self.script) self.script.onerror = empty;
|
|
}, false);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Inherits from Polling.
|
|
*/
|
|
|
|
inherit(JSONPPolling, Polling);
|
|
|
|
/*
|
|
* JSONP only supports binary as base64 encoded strings
|
|
*/
|
|
|
|
JSONPPolling.prototype.supportsBinary = false;
|
|
|
|
/**
|
|
* Closes the socket.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
JSONPPolling.prototype.doClose = function () {
|
|
if (this.script) {
|
|
this.script.parentNode.removeChild(this.script);
|
|
this.script = null;
|
|
}
|
|
|
|
if (this.form) {
|
|
this.form.parentNode.removeChild(this.form);
|
|
this.form = null;
|
|
this.iframe = null;
|
|
}
|
|
|
|
Polling.prototype.doClose.call(this);
|
|
};
|
|
|
|
/**
|
|
* Starts a poll cycle.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
JSONPPolling.prototype.doPoll = function () {
|
|
var self = this;
|
|
var script = document.createElement('script');
|
|
|
|
if (this.script) {
|
|
this.script.parentNode.removeChild(this.script);
|
|
this.script = null;
|
|
}
|
|
|
|
script.async = true;
|
|
script.src = this.uri();
|
|
script.onerror = function (e) {
|
|
self.onError('jsonp poll error', e);
|
|
};
|
|
|
|
var insertAt = document.getElementsByTagName('script')[0];
|
|
if (insertAt) {
|
|
insertAt.parentNode.insertBefore(script, insertAt);
|
|
} else {
|
|
(document.head || document.body).appendChild(script);
|
|
}
|
|
this.script = script;
|
|
|
|
var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
|
|
|
|
if (isUAgecko) {
|
|
setTimeout(function () {
|
|
var iframe = document.createElement('iframe');
|
|
document.body.appendChild(iframe);
|
|
document.body.removeChild(iframe);
|
|
}, 100);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Writes with a hidden iframe.
|
|
*
|
|
* @param {String} data to send
|
|
* @param {Function} called upon flush.
|
|
* @api private
|
|
*/
|
|
|
|
JSONPPolling.prototype.doWrite = function (data, fn) {
|
|
var self = this;
|
|
|
|
if (!this.form) {
|
|
var form = document.createElement('form');
|
|
var area = document.createElement('textarea');
|
|
var id = this.iframeId = 'eio_iframe_' + this.index;
|
|
var iframe;
|
|
|
|
form.className = 'socketio';
|
|
form.style.position = 'absolute';
|
|
form.style.top = '-1000px';
|
|
form.style.left = '-1000px';
|
|
form.target = id;
|
|
form.method = 'POST';
|
|
form.setAttribute('accept-charset', 'utf-8');
|
|
area.name = 'd';
|
|
form.appendChild(area);
|
|
document.body.appendChild(form);
|
|
|
|
this.form = form;
|
|
this.area = area;
|
|
}
|
|
|
|
this.form.action = this.uri();
|
|
|
|
function complete () {
|
|
initIframe();
|
|
fn();
|
|
}
|
|
|
|
function initIframe () {
|
|
if (self.iframe) {
|
|
try {
|
|
self.form.removeChild(self.iframe);
|
|
} catch (e) {
|
|
self.onError('jsonp polling iframe removal error', e);
|
|
}
|
|
}
|
|
|
|
try {
|
|
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
|
|
var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
|
|
iframe = document.createElement(html);
|
|
} catch (e) {
|
|
iframe = document.createElement('iframe');
|
|
iframe.name = self.iframeId;
|
|
iframe.src = 'javascript:0';
|
|
}
|
|
|
|
iframe.id = self.iframeId;
|
|
|
|
self.form.appendChild(iframe);
|
|
self.iframe = iframe;
|
|
}
|
|
|
|
initIframe();
|
|
|
|
// escape \n to prevent it from being converted into \r\n by some UAs
|
|
// double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
|
|
data = data.replace(rEscapedNewline, '\\\n');
|
|
this.area.value = data.replace(rNewline, '\\n');
|
|
|
|
try {
|
|
this.form.submit();
|
|
} catch (e) {}
|
|
|
|
if (this.iframe.attachEvent) {
|
|
this.iframe.onreadystatechange = function () {
|
|
if (self.iframe.readyState === 'complete') {
|
|
complete();
|
|
}
|
|
};
|
|
} else {
|
|
this.iframe.onload = complete;
|
|
}
|
|
};
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 36 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var Transport = __webpack_require__(22);
|
|
var parser = __webpack_require__(23);
|
|
var parseqs = __webpack_require__(32);
|
|
var inherit = __webpack_require__(33);
|
|
var yeast = __webpack_require__(34);
|
|
var debug = __webpack_require__(3)('engine.io-client:websocket');
|
|
var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
|
|
|
|
/**
|
|
* Get either the `WebSocket` or `MozWebSocket` globals
|
|
* in the browser or try to resolve WebSocket-compatible
|
|
* interface exposed by `ws` for Node-like environment.
|
|
*/
|
|
|
|
var WebSocket = BrowserWebSocket;
|
|
if (!WebSocket && typeof window === 'undefined') {
|
|
try {
|
|
WebSocket = __webpack_require__(37);
|
|
} catch (e) { }
|
|
}
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = WS;
|
|
|
|
/**
|
|
* WebSocket transport constructor.
|
|
*
|
|
* @api {Object} connection options
|
|
* @api public
|
|
*/
|
|
|
|
function WS (opts) {
|
|
var forceBase64 = (opts && opts.forceBase64);
|
|
if (forceBase64) {
|
|
this.supportsBinary = false;
|
|
}
|
|
this.perMessageDeflate = opts.perMessageDeflate;
|
|
Transport.call(this, opts);
|
|
}
|
|
|
|
/**
|
|
* Inherits from Transport.
|
|
*/
|
|
|
|
inherit(WS, Transport);
|
|
|
|
/**
|
|
* Transport name.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
WS.prototype.name = 'websocket';
|
|
|
|
/*
|
|
* WebSockets support binary
|
|
*/
|
|
|
|
WS.prototype.supportsBinary = true;
|
|
|
|
/**
|
|
* Opens socket.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
WS.prototype.doOpen = function () {
|
|
if (!this.check()) {
|
|
// let probe timeout
|
|
return;
|
|
}
|
|
|
|
var uri = this.uri();
|
|
var protocols = void (0);
|
|
var opts = {
|
|
agent: this.agent,
|
|
perMessageDeflate: this.perMessageDeflate
|
|
};
|
|
|
|
// SSL options for Node.js client
|
|
opts.pfx = this.pfx;
|
|
opts.key = this.key;
|
|
opts.passphrase = this.passphrase;
|
|
opts.cert = this.cert;
|
|
opts.ca = this.ca;
|
|
opts.ciphers = this.ciphers;
|
|
opts.rejectUnauthorized = this.rejectUnauthorized;
|
|
if (this.extraHeaders) {
|
|
opts.headers = this.extraHeaders;
|
|
}
|
|
|
|
try {
|
|
this.ws = BrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
|
|
} catch (err) {
|
|
return this.emit('error', err);
|
|
}
|
|
|
|
if (this.ws.binaryType === undefined) {
|
|
this.supportsBinary = false;
|
|
}
|
|
|
|
if (this.ws.supports && this.ws.supports.binary) {
|
|
this.supportsBinary = true;
|
|
this.ws.binaryType = 'nodebuffer';
|
|
} else {
|
|
this.ws.binaryType = 'arraybuffer';
|
|
}
|
|
|
|
this.addEventListeners();
|
|
};
|
|
|
|
/**
|
|
* Adds event listeners to the socket
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
WS.prototype.addEventListeners = function () {
|
|
var self = this;
|
|
|
|
this.ws.onopen = function () {
|
|
self.onOpen();
|
|
};
|
|
this.ws.onclose = function () {
|
|
self.onClose();
|
|
};
|
|
this.ws.onmessage = function (ev) {
|
|
self.onData(ev.data);
|
|
};
|
|
this.ws.onerror = function (e) {
|
|
self.onError('websocket error', e);
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Override `onData` to use a timer on iOS.
|
|
* See: https://gist.github.com/mloughran/2052006
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
if ('undefined' !== typeof navigator &&
|
|
/iPad|iPhone|iPod/i.test(navigator.userAgent)) {
|
|
WS.prototype.onData = function (data) {
|
|
var self = this;
|
|
setTimeout(function () {
|
|
Transport.prototype.onData.call(self, data);
|
|
}, 0);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Writes data to socket.
|
|
*
|
|
* @param {Array} array of packets.
|
|
* @api private
|
|
*/
|
|
|
|
WS.prototype.write = function (packets) {
|
|
var self = this;
|
|
this.writable = false;
|
|
|
|
// encodePacket efficient as it uses WS framing
|
|
// no need for encodePayload
|
|
var total = packets.length;
|
|
for (var i = 0, l = total; i < l; i++) {
|
|
(function (packet) {
|
|
parser.encodePacket(packet, self.supportsBinary, function (data) {
|
|
if (!BrowserWebSocket) {
|
|
// always create a new object (GH-437)
|
|
var opts = {};
|
|
if (packet.options) {
|
|
opts.compress = packet.options.compress;
|
|
}
|
|
|
|
if (self.perMessageDeflate) {
|
|
var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length;
|
|
if (len < self.perMessageDeflate.threshold) {
|
|
opts.compress = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Sometimes the websocket has already been closed but the browser didn't
|
|
// have a chance of informing us about it yet, in that case send will
|
|
// throw an error
|
|
try {
|
|
if (BrowserWebSocket) {
|
|
// TypeError is thrown when passing the second argument on Safari
|
|
self.ws.send(data);
|
|
} else {
|
|
self.ws.send(data, opts);
|
|
}
|
|
} catch (e) {
|
|
debug('websocket closed before onclose event');
|
|
}
|
|
|
|
--total || done();
|
|
});
|
|
})(packets[i]);
|
|
}
|
|
|
|
function done () {
|
|
self.emit('flush');
|
|
|
|
// fake drain
|
|
// defer to next tick to allow Socket to clear writeBuffer
|
|
setTimeout(function () {
|
|
self.writable = true;
|
|
self.emit('drain');
|
|
}, 0);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon close
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
WS.prototype.onClose = function () {
|
|
Transport.prototype.onClose.call(this);
|
|
};
|
|
|
|
/**
|
|
* Closes socket.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
WS.prototype.doClose = function () {
|
|
if (typeof this.ws !== 'undefined') {
|
|
this.ws.close();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Generates uri for connection.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
WS.prototype.uri = function () {
|
|
var query = this.query || {};
|
|
var schema = this.secure ? 'wss' : 'ws';
|
|
var port = '';
|
|
|
|
// avoid port if default for schema
|
|
if (this.port && (('wss' === schema && this.port !== 443) ||
|
|
('ws' === schema && this.port !== 80))) {
|
|
port = ':' + this.port;
|
|
}
|
|
|
|
// append timestamp to URI
|
|
if (this.timestampRequests) {
|
|
query[this.timestampParam] = yeast();
|
|
}
|
|
|
|
// communicate binary support capabilities
|
|
if (!this.supportsBinary) {
|
|
query.b64 = 1;
|
|
}
|
|
|
|
query = parseqs.encode(query);
|
|
|
|
// prepend ? to query
|
|
if (query.length) {
|
|
query = '?' + query;
|
|
}
|
|
|
|
var ipv6 = this.hostname.indexOf(':') !== -1;
|
|
return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
|
|
};
|
|
|
|
/**
|
|
* Feature detection for WebSocket.
|
|
*
|
|
* @return {Boolean} whether this transport is available.
|
|
* @api public
|
|
*/
|
|
|
|
WS.prototype.check = function () {
|
|
return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
|
|
};
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 37 */
|
|
/***/ function(module, exports) {
|
|
|
|
/* (ignored) */
|
|
|
|
/***/ },
|
|
/* 38 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
var indexOf = [].indexOf;
|
|
|
|
module.exports = function(arr, obj){
|
|
if (indexOf) return arr.indexOf(obj);
|
|
for (var i = 0; i < arr.length; ++i) {
|
|
if (arr[i] === obj) return i;
|
|
}
|
|
return -1;
|
|
};
|
|
|
|
/***/ },
|
|
/* 39 */
|
|
/***/ function(module, exports) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {/**
|
|
* JSON parse.
|
|
*
|
|
* @see Based on jQuery#parseJSON (MIT) and JSON2
|
|
* @api private
|
|
*/
|
|
|
|
var rvalidchars = /^[\],:{}\s]*$/;
|
|
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
|
|
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
|
|
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
|
|
var rtrimLeft = /^\s+/;
|
|
var rtrimRight = /\s+$/;
|
|
|
|
module.exports = function parsejson(data) {
|
|
if ('string' != typeof data || !data) {
|
|
return null;
|
|
}
|
|
|
|
data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
|
|
|
|
// Attempt to parse using the native JSON parser first
|
|
if (global.JSON && JSON.parse) {
|
|
return JSON.parse(data);
|
|
}
|
|
|
|
if (rvalidchars.test(data.replace(rvalidescape, '@')
|
|
.replace(rvalidtokens, ']')
|
|
.replace(rvalidbraces, ''))) {
|
|
return (new Function('return ' + data))();
|
|
}
|
|
};
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 40 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
|
|
var parser = __webpack_require__(6);
|
|
var Emitter = __webpack_require__(41);
|
|
var toArray = __webpack_require__(42);
|
|
var on = __webpack_require__(43);
|
|
var bind = __webpack_require__(44);
|
|
var debug = __webpack_require__(3)('socket.io-client:socket');
|
|
var hasBin = __webpack_require__(45);
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = exports = Socket;
|
|
|
|
/**
|
|
* Internal events (blacklisted).
|
|
* These events can't be emitted by the user.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
var events = {
|
|
connect: 1,
|
|
connect_error: 1,
|
|
connect_timeout: 1,
|
|
connecting: 1,
|
|
disconnect: 1,
|
|
error: 1,
|
|
reconnect: 1,
|
|
reconnect_attempt: 1,
|
|
reconnect_failed: 1,
|
|
reconnect_error: 1,
|
|
reconnecting: 1,
|
|
ping: 1,
|
|
pong: 1
|
|
};
|
|
|
|
/**
|
|
* Shortcut to `Emitter#emit`.
|
|
*/
|
|
|
|
var emit = Emitter.prototype.emit;
|
|
|
|
/**
|
|
* `Socket` constructor.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function Socket(io, nsp, opts) {
|
|
this.io = io;
|
|
this.nsp = nsp;
|
|
this.json = this; // compat
|
|
this.ids = 0;
|
|
this.acks = {};
|
|
this.receiveBuffer = [];
|
|
this.sendBuffer = [];
|
|
this.connected = false;
|
|
this.disconnected = true;
|
|
if (opts && opts.query) {
|
|
this.query = opts.query;
|
|
}
|
|
if (this.io.autoConnect) this.open();
|
|
}
|
|
|
|
/**
|
|
* Mix in `Emitter`.
|
|
*/
|
|
|
|
Emitter(Socket.prototype);
|
|
|
|
/**
|
|
* Subscribe to open, close and packet events
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.subEvents = function () {
|
|
if (this.subs) return;
|
|
|
|
var io = this.io;
|
|
this.subs = [on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose'))];
|
|
};
|
|
|
|
/**
|
|
* "Opens" the socket.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.open = Socket.prototype.connect = function () {
|
|
if (this.connected) return this;
|
|
|
|
this.subEvents();
|
|
this.io.open(); // ensure open
|
|
if ('open' === this.io.readyState) this.onopen();
|
|
this.emit('connecting');
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sends a `message` event.
|
|
*
|
|
* @return {Socket} self
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.send = function () {
|
|
var args = toArray(arguments);
|
|
args.unshift('message');
|
|
this.emit.apply(this, args);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Override `emit`.
|
|
* If the event is in `events`, it's emitted normally.
|
|
*
|
|
* @param {String} event name
|
|
* @return {Socket} self
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.emit = function (ev) {
|
|
if (events.hasOwnProperty(ev)) {
|
|
emit.apply(this, arguments);
|
|
return this;
|
|
}
|
|
|
|
var args = toArray(arguments);
|
|
var parserType = parser.EVENT; // default
|
|
if (hasBin(args)) {
|
|
parserType = parser.BINARY_EVENT;
|
|
} // binary
|
|
var packet = { type: parserType, data: args };
|
|
|
|
packet.options = {};
|
|
packet.options.compress = !this.flags || false !== this.flags.compress;
|
|
|
|
// event ack callback
|
|
if ('function' === typeof args[args.length - 1]) {
|
|
debug('emitting packet with ack id %d', this.ids);
|
|
this.acks[this.ids] = args.pop();
|
|
packet.id = this.ids++;
|
|
}
|
|
|
|
if (this.connected) {
|
|
this.packet(packet);
|
|
} else {
|
|
this.sendBuffer.push(packet);
|
|
}
|
|
|
|
delete this.flags;
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sends a packet.
|
|
*
|
|
* @param {Object} packet
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.packet = function (packet) {
|
|
packet.nsp = this.nsp;
|
|
this.io.packet(packet);
|
|
};
|
|
|
|
/**
|
|
* Called upon engine `open`.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onopen = function () {
|
|
debug('transport is open - connecting');
|
|
|
|
// write connect packet if necessary
|
|
if ('/' !== this.nsp) {
|
|
if (this.query) {
|
|
this.packet({ type: parser.CONNECT, query: this.query });
|
|
} else {
|
|
this.packet({ type: parser.CONNECT });
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon engine `close`.
|
|
*
|
|
* @param {String} reason
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onclose = function (reason) {
|
|
debug('close (%s)', reason);
|
|
this.connected = false;
|
|
this.disconnected = true;
|
|
delete this.id;
|
|
this.emit('disconnect', reason);
|
|
};
|
|
|
|
/**
|
|
* Called with socket packet.
|
|
*
|
|
* @param {Object} packet
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onpacket = function (packet) {
|
|
if (packet.nsp !== this.nsp) return;
|
|
|
|
switch (packet.type) {
|
|
case parser.CONNECT:
|
|
this.onconnect();
|
|
break;
|
|
|
|
case parser.EVENT:
|
|
this.onevent(packet);
|
|
break;
|
|
|
|
case parser.BINARY_EVENT:
|
|
this.onevent(packet);
|
|
break;
|
|
|
|
case parser.ACK:
|
|
this.onack(packet);
|
|
break;
|
|
|
|
case parser.BINARY_ACK:
|
|
this.onack(packet);
|
|
break;
|
|
|
|
case parser.DISCONNECT:
|
|
this.ondisconnect();
|
|
break;
|
|
|
|
case parser.ERROR:
|
|
this.emit('error', packet.data);
|
|
break;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon a server event.
|
|
*
|
|
* @param {Object} packet
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onevent = function (packet) {
|
|
var args = packet.data || [];
|
|
debug('emitting event %j', args);
|
|
|
|
if (null != packet.id) {
|
|
debug('attaching ack callback to event');
|
|
args.push(this.ack(packet.id));
|
|
}
|
|
|
|
if (this.connected) {
|
|
emit.apply(this, args);
|
|
} else {
|
|
this.receiveBuffer.push(args);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Produces an ack callback to emit with an event.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.ack = function (id) {
|
|
var self = this;
|
|
var sent = false;
|
|
return function () {
|
|
// prevent double callbacks
|
|
if (sent) return;
|
|
sent = true;
|
|
var args = toArray(arguments);
|
|
debug('sending ack %j', args);
|
|
|
|
var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
|
|
self.packet({
|
|
type: type,
|
|
id: id,
|
|
data: args
|
|
});
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Called upon a server acknowlegement.
|
|
*
|
|
* @param {Object} packet
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onack = function (packet) {
|
|
var ack = this.acks[packet.id];
|
|
if ('function' === typeof ack) {
|
|
debug('calling ack %s with %j', packet.id, packet.data);
|
|
ack.apply(this, packet.data);
|
|
delete this.acks[packet.id];
|
|
} else {
|
|
debug('bad ack %s', packet.id);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Called upon server connect.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.onconnect = function () {
|
|
this.connected = true;
|
|
this.disconnected = false;
|
|
this.emit('connect');
|
|
this.emitBuffered();
|
|
};
|
|
|
|
/**
|
|
* Emit buffered events (received and emitted).
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.emitBuffered = function () {
|
|
var i;
|
|
for (i = 0; i < this.receiveBuffer.length; i++) {
|
|
emit.apply(this, this.receiveBuffer[i]);
|
|
}
|
|
this.receiveBuffer = [];
|
|
|
|
for (i = 0; i < this.sendBuffer.length; i++) {
|
|
this.packet(this.sendBuffer[i]);
|
|
}
|
|
this.sendBuffer = [];
|
|
};
|
|
|
|
/**
|
|
* Called upon server disconnect.
|
|
*
|
|
* @api private
|
|
*/
|
|
|
|
Socket.prototype.ondisconnect = function () {
|
|
debug('server disconnect (%s)', this.nsp);
|
|
this.destroy();
|
|
this.onclose('io server disconnect');
|
|
};
|
|
|
|
/**
|
|
* Called upon forced client/server side disconnections,
|
|
* this method ensures the manager stops tracking us and
|
|
* that reconnections don't get triggered for this.
|
|
*
|
|
* @api private.
|
|
*/
|
|
|
|
Socket.prototype.destroy = function () {
|
|
if (this.subs) {
|
|
// clean subscriptions to avoid reconnections
|
|
for (var i = 0; i < this.subs.length; i++) {
|
|
this.subs[i].destroy();
|
|
}
|
|
this.subs = null;
|
|
}
|
|
|
|
this.io.destroy(this);
|
|
};
|
|
|
|
/**
|
|
* Disconnects the socket manually.
|
|
*
|
|
* @return {Socket} self
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.close = Socket.prototype.disconnect = function () {
|
|
if (this.connected) {
|
|
debug('performing disconnect (%s)', this.nsp);
|
|
this.packet({ type: parser.DISCONNECT });
|
|
}
|
|
|
|
// remove socket from pool
|
|
this.destroy();
|
|
|
|
if (this.connected) {
|
|
// fire events
|
|
this.onclose('io client disconnect');
|
|
}
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Sets the compress flag.
|
|
*
|
|
* @param {Boolean} if `true`, compresses the sending data
|
|
* @return {Socket} self
|
|
* @api public
|
|
*/
|
|
|
|
Socket.prototype.compress = function (compress) {
|
|
this.flags = this.flags || {};
|
|
this.flags.compress = compress;
|
|
return this;
|
|
};
|
|
|
|
/***/ },
|
|
/* 41 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
/**
|
|
* Expose `Emitter`.
|
|
*/
|
|
|
|
module.exports = Emitter;
|
|
|
|
/**
|
|
* Initialize a new `Emitter`.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
function Emitter(obj) {
|
|
if (obj) return mixin(obj);
|
|
};
|
|
|
|
/**
|
|
* Mixin the emitter properties.
|
|
*
|
|
* @param {Object} obj
|
|
* @return {Object}
|
|
* @api private
|
|
*/
|
|
|
|
function mixin(obj) {
|
|
for (var key in Emitter.prototype) {
|
|
obj[key] = Emitter.prototype[key];
|
|
}
|
|
return obj;
|
|
}
|
|
|
|
/**
|
|
* Listen on the given `event` with `fn`.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.on =
|
|
Emitter.prototype.addEventListener = function(event, fn){
|
|
this._callbacks = this._callbacks || {};
|
|
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
|
|
.push(fn);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Adds an `event` listener that will be invoked a single
|
|
* time then automatically removed.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.once = function(event, fn){
|
|
function on() {
|
|
this.off(event, on);
|
|
fn.apply(this, arguments);
|
|
}
|
|
|
|
on.fn = fn;
|
|
this.on(event, on);
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Remove the given callback for `event` or all
|
|
* registered callbacks.
|
|
*
|
|
* @param {String} event
|
|
* @param {Function} fn
|
|
* @return {Emitter}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.off =
|
|
Emitter.prototype.removeListener =
|
|
Emitter.prototype.removeAllListeners =
|
|
Emitter.prototype.removeEventListener = function(event, fn){
|
|
this._callbacks = this._callbacks || {};
|
|
|
|
// all
|
|
if (0 == arguments.length) {
|
|
this._callbacks = {};
|
|
return this;
|
|
}
|
|
|
|
// specific event
|
|
var callbacks = this._callbacks['$' + event];
|
|
if (!callbacks) return this;
|
|
|
|
// remove all handlers
|
|
if (1 == arguments.length) {
|
|
delete this._callbacks['$' + event];
|
|
return this;
|
|
}
|
|
|
|
// remove specific handler
|
|
var cb;
|
|
for (var i = 0; i < callbacks.length; i++) {
|
|
cb = callbacks[i];
|
|
if (cb === fn || cb.fn === fn) {
|
|
callbacks.splice(i, 1);
|
|
break;
|
|
}
|
|
}
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Emit `event` with the given args.
|
|
*
|
|
* @param {String} event
|
|
* @param {Mixed} ...
|
|
* @return {Emitter}
|
|
*/
|
|
|
|
Emitter.prototype.emit = function(event){
|
|
this._callbacks = this._callbacks || {};
|
|
var args = [].slice.call(arguments, 1)
|
|
, callbacks = this._callbacks['$' + event];
|
|
|
|
if (callbacks) {
|
|
callbacks = callbacks.slice(0);
|
|
for (var i = 0, len = callbacks.length; i < len; ++i) {
|
|
callbacks[i].apply(this, args);
|
|
}
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* Return array of callbacks for `event`.
|
|
*
|
|
* @param {String} event
|
|
* @return {Array}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.listeners = function(event){
|
|
this._callbacks = this._callbacks || {};
|
|
return this._callbacks['$' + event] || [];
|
|
};
|
|
|
|
/**
|
|
* Check if this emitter has `event` handlers.
|
|
*
|
|
* @param {String} event
|
|
* @return {Boolean}
|
|
* @api public
|
|
*/
|
|
|
|
Emitter.prototype.hasListeners = function(event){
|
|
return !! this.listeners(event).length;
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 42 */
|
|
/***/ function(module, exports) {
|
|
|
|
module.exports = toArray
|
|
|
|
function toArray(list, index) {
|
|
var array = []
|
|
|
|
index = index || 0
|
|
|
|
for (var i = index || 0; i < list.length; i++) {
|
|
array[i - index] = list[i]
|
|
}
|
|
|
|
return array
|
|
}
|
|
|
|
|
|
/***/ },
|
|
/* 43 */
|
|
/***/ function(module, exports) {
|
|
|
|
"use strict";
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = on;
|
|
|
|
/**
|
|
* Helper for subscriptions.
|
|
*
|
|
* @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
|
|
* @param {String} event name
|
|
* @param {Function} callback
|
|
* @api public
|
|
*/
|
|
|
|
function on(obj, ev, fn) {
|
|
obj.on(ev, fn);
|
|
return {
|
|
destroy: function destroy() {
|
|
obj.removeListener(ev, fn);
|
|
}
|
|
};
|
|
}
|
|
|
|
/***/ },
|
|
/* 44 */
|
|
/***/ function(module, exports) {
|
|
|
|
/**
|
|
* Slice reference.
|
|
*/
|
|
|
|
var slice = [].slice;
|
|
|
|
/**
|
|
* Bind `obj` to `fn`.
|
|
*
|
|
* @param {Object} obj
|
|
* @param {Function|String} fn or string
|
|
* @return {Function}
|
|
* @api public
|
|
*/
|
|
|
|
module.exports = function(obj, fn){
|
|
if ('string' == typeof fn) fn = obj[fn];
|
|
if ('function' != typeof fn) throw new Error('bind() requires a function');
|
|
var args = slice.call(arguments, 2);
|
|
return function(){
|
|
return fn.apply(obj, args.concat(slice.call(arguments)));
|
|
}
|
|
};
|
|
|
|
|
|
/***/ },
|
|
/* 45 */
|
|
/***/ function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {
|
|
/*
|
|
* Module requirements.
|
|
*/
|
|
|
|
var isArray = __webpack_require__(9);
|
|
|
|
/**
|
|
* Module exports.
|
|
*/
|
|
|
|
module.exports = hasBinary;
|
|
|
|
/**
|
|
* Checks for binary data.
|
|
*
|
|
* Right now only Buffer and ArrayBuffer are supported..
|
|
*
|
|
* @param {Object} anything
|
|
* @api public
|
|
*/
|
|
|
|
function hasBinary(data) {
|
|
|
|
function _hasBinary(obj) {
|
|
if (!obj) return false;
|
|
|
|
if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
|
|
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
|
|
(global.Blob && obj instanceof Blob) ||
|
|
(global.File && obj instanceof File)
|
|
) {
|
|
return true;
|
|
}
|
|
|
|
if (isArray(obj)) {
|
|
for (var i = 0; i < obj.length; i++) {
|
|
if (_hasBinary(obj[i])) {
|
|
return true;
|
|
}
|
|
}
|
|
} else if (obj && 'object' == typeof obj) {
|
|
// see: https://github.com/Automattic/has-binary/pull/4
|
|
if (obj.toJSON && 'function' == typeof obj.toJSON) {
|
|
obj = obj.toJSON();
|
|
}
|
|
|
|
for (var key in obj) {
|
|
if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
return _hasBinary(data);
|
|
}
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ },
|
|
/* 46 */
|
|
/***/ function(module, exports) {
|
|
|
|
|
|
/**
|
|
* Expose `Backoff`.
|
|
*/
|
|
|
|
module.exports = Backoff;
|
|
|
|
/**
|
|
* Initialize backoff timer with `opts`.
|
|
*
|
|
* - `min` initial timeout in milliseconds [100]
|
|
* - `max` max timeout [10000]
|
|
* - `jitter` [0]
|
|
* - `factor` [2]
|
|
*
|
|
* @param {Object} opts
|
|
* @api public
|
|
*/
|
|
|
|
function Backoff(opts) {
|
|
opts = opts || {};
|
|
this.ms = opts.min || 100;
|
|
this.max = opts.max || 10000;
|
|
this.factor = opts.factor || 2;
|
|
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
|
|
this.attempts = 0;
|
|
}
|
|
|
|
/**
|
|
* Return the backoff duration.
|
|
*
|
|
* @return {Number}
|
|
* @api public
|
|
*/
|
|
|
|
Backoff.prototype.duration = function(){
|
|
var ms = this.ms * Math.pow(this.factor, this.attempts++);
|
|
if (this.jitter) {
|
|
var rand = Math.random();
|
|
var deviation = Math.floor(rand * this.jitter * ms);
|
|
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
|
|
}
|
|
return Math.min(ms, this.max) | 0;
|
|
};
|
|
|
|
/**
|
|
* Reset the number of attempts.
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Backoff.prototype.reset = function(){
|
|
this.attempts = 0;
|
|
};
|
|
|
|
/**
|
|
* Set the minimum duration
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Backoff.prototype.setMin = function(min){
|
|
this.ms = min;
|
|
};
|
|
|
|
/**
|
|
* Set the maximum duration
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Backoff.prototype.setMax = function(max){
|
|
this.max = max;
|
|
};
|
|
|
|
/**
|
|
* Set the jitter
|
|
*
|
|
* @api public
|
|
*/
|
|
|
|
Backoff.prototype.setJitter = function(jitter){
|
|
this.jitter = jitter;
|
|
};
|
|
|
|
|
|
|
|
/***/ }
|
|
/******/ ])
|
|
});
|
|
;
|
|
})(window);
|