cl-speakeasy-sdk
Version:
CenturyLink SpeakEasy JavaScript SDK
2 lines • 402 kB
JavaScript
var Ctlspeakeasy_Version,Ctlspeakeasy_Config,Ctl_Logger,Ctl_Utils,Ctl_Promise,Ctl_Ajax,Ctlmodelrequest_BaseRequest,Ctlmodelrequest_SubscriptionServiceIdentitiesRequest,Ctlmodelrequest_SubscriptionServiceCatalogRequest,Ctl_Subscription,Ctl_Error,fcs,Ctlspeakeasy_Notification,Ctlmodelrequest_AccessTokenRequest,Ctlmodelrequest_RefreshTokenRequest,Ctl_Auth,Ctlspeakeasy_EventEmitter,Ctlspeakeasy_CallInfo,Ctlspeakeasy_AudiotonesManager,Ctlspeakeasy_BaseCall,Ctlspeakeasy_IncomingCall,Ctlspeakeasy_OutgoingCall,Ctlspeakeasy_CallManager,SpeakEasy;Ctlspeakeasy_Version="0.1.8",Ctlspeakeasy_Config={useConfig:"cert",settings:{intg:{ctlServerURL:"https://lab.iaf.centurylink.com:8889"},cert:{ctlServerURL:"https://lab.af.centurylink.com:8889"},loginURI:"/token",getSubscriptionServiceIdentitiesURI:"/SpeakEasyProvision/v1/util/products",getSubscriptionServiceCatalogURI:"/SpeakEasyProvision/v1/serviceProfile/{publicId}",subscribeServiceURI:"/{serviceName}/{identity}@{domain}/subscription",unsubscribeServiceURI:"/SpeakEasy/{identity}@ctlvoip.lab.centurylink/subscription/{channelId}",getInstantMessageURI:"/rest/version/{versionId}/user/{userId}/notification/{notificationChannelId}",postImByUseridURI:"/rest/version/{versionId}/user/{userId}/instantmessage",postImByDeviceidURI:"/rest/version/{versionId}/device/{deviceId}/instantmessage",defaultOutgoingCallDomain:"ctlvoip.lab.centurylink",proxyForURLPatterns:["/rest/version/[0-9]+/user","/rest/version/latest"],SEProxyPrependURL:"/SpeakEasy/"},fcsapi:{intg:{notificationType:"websocket",restUrl:"lab.iaf.centurylink.com",restPort:"8889",callAuditTimer:"30000",codecsToRemove:["103","104","105","106","107"],protocol:"https",clientControlled:"true",services:["CallControl","custom"],websocketProtocol:"wss",earlyMedia:!0},cert:{notificationType:"websocketonly",restUrl:"lab.af.centurylink.com",restPort:"8889",callAuditTimer:"30000",codecsToRemove:["103","104","105","106","107"],protocol:"https",clientControlled:"true",services:["CallControl","custom"],websocketProtocol:"wss",earlyMedia:!0}},callManager:{localVideoContainer:"speakeasy_localVideoContainer",remoteVideoContainer:"speakeasy_remoteVideoContainer",videoQuality:"640x480",baseToneUrl:"../dist/tones"}},Ctl_Logger=function(){function e(e){this.logEnabled=!0,this.init(e,!0)}return e.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],e.prototype.init=function(t,n){this.name=t||"UNKNOWN",this.logEnabled=n||!0;var i=function(e){this[e]=this.createLogMethod(e)}.bind(this);e.METHODS.forEach(i)},e.prototype.createLogMethod=function(t){return e.prototype.log.bind(this,t)},e.prototype.prefix=function(e,t){var n="["+e.toUpperCase()+"]["+this.name+"]: ";return-1!==["log","error","warn","info","debug"].indexOf(e)&&("string"==typeof t[0]?t[0]=n+t[0]:t.unshift(n)),t},e.prototype.log=function(){var t=[].slice.call(arguments),n=t.shift();-1===e.METHODS.indexOf(n)&&(n="log"),this.logEnabled&&console&&console[n]&&(t=this.prefix(n,t),console[n].apply(console,t))},e.prototype.setLogEnabled=function(e){this.logEnabled=e||!0},e.mixin=function(t){t.__logger=new e(t.name||"UNKNOWN");var n=function(e){e in t.prototype&&(console.warn("overwriting '"+e+"' on '"+t.name+"'."),console.warn("the previous version can be found at '_"+e+"' on '"+t.name+"'."),t.prototype["_"+e]=t.prototype[e]),t.prototype[e]=t.__logger.createLogMethod(e)};e.METHODS.forEach(n)},e}(),Ctl_Utils=function(){function e(){function e(e){if(!e)return!1;var t,n,i,r=!1;try{t=document.implementation.createHTMLDocument(""),n=t.createElement("base"),n.href=n||window.lo,t.head.appendChild(n),i=t.createElement("a"),i.href=e,t.body.appendChild(i),r=""!==i.href}catch(o){console.error(o)}finally{return t.head.removeChild(n),t.body.removeChild(i),n=null,i=null,t=null,r}}function t(e){var t;return e&&Object.keys(e)&&(t=[].slice.call(arguments).reduce(function(e,t){return e.concat(t instanceof Array?t:[t])},[]).filter(function(e){return"object"==typeof e}).reduce(function(e,t){return t instanceof Array?e.push(t):e=e.concat(Object.keys(t).map(function(e){return[e,t[e]]})),e},[]).reduce(function(e,t){return 2===t.length?e.push(t):e=e.concat(t),e},[]).reduce(function(e,t){return t[1]instanceof Array?t[1].forEach(function(n){e.push([t[0],n])}):e.push(t),e},[]).map(function(e){return e[1]=encodeURIComponent(e[1]),e.join("=")}).join("&")),t}function n(e){return e&&null!==e&&"function"==typeof e}function i(e,t,i){var r;return n(e)&&(t||(t=[]),i||(i=this),t.push(i),r=e.apply(i,t)),r}function r(e,t){t&&(t=JSON.stringify(t)),this.set(e,t)}function o(e,t){var n="ctlapi_"+e;this[e]=t,"undefined"!=typeof Storage&&(t?sessionStorage.setItem(n,t):sessionStorage.removeItem(n))}function a(e){return JSON.parse(this.get(e))}function s(e){var t="ctlapi_"+e,n=null;return this[e]?n=this[e]:"undefined"!=typeof Storage&&(n=sessionStorage.getItem(t)),n}function c(){for(var e=sessionStorage.length;e--;)sessionStorage.removeItem(sessionStorage.key(e))}function l(e,t){if(null==e&&(e={}),null!=t)for(var n in t)t.hasOwnProperty(n)&&("object"==typeof e[n]&&e.hasOwnProperty(n)&&null!=e[n]?f.extend(e[n],t[n]):e[n]=t[n]);return e}function d(e){return null!=e&&"undefined"!=typeof e}function u(e){return null==e||"undefined"==typeof e}var f=this;this.isValidUrl=e,this.encodeParams=t,this.isFunction=n,this.doCallback=i,this.setObject=r,this.set=o,this.getObject=a,this.get=s,this.removeAll=c,this.extend=l,this.isNotNull=d,this.isNull=u}return new e}(),Ctl_Promise=function(e){function t(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}return t.prototype.then=function(e,t){var n=function(){return e.apply(t,arguments)};this.complete?n(this.error,this.result):this.callbacks.push(n)},t.prototype.done=function(e,t){if(this.complete=!0,this.error=e,this.result=t,this.callbacks){for(var n=0;n<this.callbacks.length;n++)this.callbacks[n](e,t);this.callbacks.length=0}},t.join=function(n){function i(e){return function(t,n){a+=1,s[e]=t,c[e]=n,a===o&&r.done(s,c)}}for(var r=new t,o=n.length,a=0,s=[],c=[],l=0;o>l;l++)e.isFunction(n[l])?n[l]().then(i(l)):n[l].then(i(l));return r},t.chain=function(n,i,r){function o(e,i){n.splice(0,1),n?t.chain(n,e,i).then(function(e,t){a.done(e,t)}):a.done(e,i)}var a=new t;return null===n||0===n.length?a.done(i,r):e.isFunction(n[0])?n[0](i,r).then(o):n[0].then(o),a},t}(Ctl_Utils),Ctl_Ajax=function(e,t){function n(){var e=Array.prototype.slice.call(arguments),t=e.shift();return t.bind(this,e)}function i(){function i(e){var t="";if("string"==typeof e)t=e;else{var n=encodeURIComponent;for(var i in e)e.hasOwnProperty(i)&&(Object.keys(e).indexOf(i)>0&&(t+="&"),t+=n(i)+"="+n(e[i]))}return t}function r(e,n,r,a){var s,c=new t;return o.logger.time(e+" "+n),function(t){if(t.onreadystatechange=function(){4===this.readyState&&(o.logger.timeEnd(e+" "+n),clearTimeout(s),200===this.status&&c.done(null,this),(this.status>=400&&this.status<=451||this.status>=500&&this.status<=511)&&c.done(this,null))},t.onerror=function(e){clearTimeout(s),c.done(e,null)},t.oncomplete=function(t){clearTimeout(s),o.logger.timeEnd(e+" "+n),o.info("%s request to %s returned %s",e,n,this.status)},t.open(e,n),t.responseType="json",a)for(var l=0;l<a.length;l++)a[l][1]&&t.setRequestHeader(a[l][0],a[l][1]);s=setTimeout(function(){t.abort(),c.done({response:"API Call timed out."},null)},3e4),t.send(i(r))}(new XMLHttpRequest),c}var o=this,a="Ajax";o.logger=new e(a),this.request=r,this.get=n(r,"GET"),this.post=n(r,"POST"),this.put=n(r,"PUT"),this["delete"]=n(r,"DELETE")}return new i}(Ctl_Logger,Ctl_Promise),Ctlmodelrequest_BaseRequest=function(e){function t(){this.requestHeaders=[["Content-Type","application/x-www-form-urlencoded"],["Accept","application/json"],["Authorization",this.accessToken?"Bearer "+this.accessToken:""]]}return t.prototype={getRequestHeaders:function(){return this.requestHeaders},getCtlServerURL:function(){var t=e.useConfig,n=e.settings[t];return n?n.ctlServerURL:e.settings.intg.ctlServerURL}},t}(Ctlspeakeasy_Config),Ctlmodelrequest_SubscriptionServiceIdentitiesRequest=function(e,t){function n(){t.call(this)}return n.prototype=Object.create(t.prototype),n.prototype.getRequestUrl=function(){return this.getCtlServerURL()+e.settings.getSubscriptionServiceIdentitiesURI},n.prototype.type="GET",n}(Ctlspeakeasy_Config,Ctlmodelrequest_BaseRequest),Ctlmodelrequest_SubscriptionServiceCatalogRequest=function(e,t){function n(e,n){t.call(this),this.serviceName=e,this.publicId=n}return n.prototype=Object.create(t.prototype),n.prototype.getRequestUrl=function(){return this.getCtlServerURL()+e.settings.getSubscriptionServiceCatalogURI.replace("{service}",this.serviceName).replace("{publicId}",this.publicId)},n.prototype.type="GET",n}(Ctlspeakeasy_Config,Ctlmodelrequest_BaseRequest),Ctl_Subscription=function(e,t,n,i,r,o){function a(){function t(){var e=new r;return n.request(e.type,e.getRequestUrl(),null,e.getRequestHeaders())}function a(e,t){var i=new o(e,t);return n.request(i.type,i.getRequestUrl(),null,i.getRequestHeaders())}function s(e){i.setObject(u.storageKeywords.serviceName,e.productName),i.setObject(u.storageKeywords.services+"_"+e.productName,e)}function c(){var e=i.getObject(u.storageKeywords.serviceName);return i.getObject(u.storageKeywords.services+"_"+e)}function l(e){i.set(u.storageKeywords.serviceCatalog.publicId,e)}function d(){return i.get(u.storageKeywords.serviceCatalog.publicId)}var u=(new e("Subscription"),{storageKeywords:{services:"services",serviceName:"serviceName",serviceCatalog:{publicId:"publicId",domain:"domain",id:"id",webSocketEndpoints:"webSocketEndpoints",voipTnCipherRef:"voipTnCipherRef"}}});this.getSubscriptionServices=t,this.getSubscriptionServiceDetails=a,this.getServiceCatalog=c,this.setServiceCatalog=s,this.setPublicId=l,this.getPublicId=d}return new a}(Ctl_Logger,Ctl_Promise,Ctl_Ajax,Ctl_Utils,Ctlmodelrequest_SubscriptionServiceIdentitiesRequest,Ctlmodelrequest_SubscriptionServiceCatalogRequest),Ctl_Error=function(){function e(e,t,n){this.type=e,this.code=t,this.message=n}return e.Types={LOGIN:"LOGIN",NOTIFICATION:"NOTIFICATION",MEDIA:"MEDIA",CALLING:"CALLING",OTHER:"OTHER"},e}(),function(e,t){function n(e){var t,n,i,o,a,s,c,l,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=0,f=0,p="",E=[];if(!e)return e;e=r(e+"");do t=e.charCodeAt(u++),n=e.charCodeAt(u++),i=e.charCodeAt(u++),l=t<<16|n<<8|i,o=l>>18&63,a=l>>12&63,s=l>>6&63,c=63&l,E[f++]=d.charAt(o)+d.charAt(a)+d.charAt(s)+d.charAt(c);while(u<e.length);switch(p=E.join(""),e.length%3){case 1:p=p.slice(0,-2)+"==";break;case 2:p=p.slice(0,-1)+"="}return p}function i(e){var t,n,i,r,a,s,c,l,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=0,f=0,p="",E=[];if(!e)return e;e+="";do r=d.indexOf(e.charAt(u++)),a=d.indexOf(e.charAt(u++)),s=d.indexOf(e.charAt(u++)),c=d.indexOf(e.charAt(u++)),l=r<<18|a<<12|s<<6|c,t=l>>16&255,n=l>>8&255,i=255&l,64==s?E[f++]=String.fromCharCode(t):64==c?E[f++]=String.fromCharCode(t,n):E[f++]=String.fromCharCode(t,n,i);while(u<e.length);return p=E.join(""),p=o(p)}function r(e){var t,n,i=e+"",r="",o=0;t=n=0,o=i.length;for(var a=0;o>a;a++){var s=i.charCodeAt(a),c=null;128>s?n++:c=s>127&&2048>s?String.fromCharCode(s>>6|192)+String.fromCharCode(63&s|128):String.fromCharCode(s>>12|224)+String.fromCharCode(s>>6&63|128)+String.fromCharCode(63&s|128),null!==c&&(n>t&&(r+=i.substring(t,n)),r+=c,t=n=a+1)}return n>t&&(r+=i.substring(t,i.length)),r}function o(e){var t=[],n=0,i=0,r=0,o=0,a=0;for(e+="";n<e.length;)r=e.charCodeAt(n),128>r?(t[i++]=String.fromCharCode(r),n++):r>191&&224>r?(o=e.charCodeAt(n+1),t[i++]=String.fromCharCode((31&r)<<6|63&o),n+=2):(o=e.charCodeAt(n+1),a=e.charCodeAt(n+2),t[i++]=String.fromCharCode((15&r)<<12|(63&o)<<6|63&a),n+=3);return t.join("")}function a(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function s(e,t,n,i){i.serviceManagerMap||(i.serviceManagerMap=new T),i.serviceManagerMap.get(e)||i.serviceManagerMap.add(e,new T),i.serviceManagerMap.get(e).add(t,n)}function c(e,t,n){s(e,t,n,b)}function l(){return O.split("@")[1]}function d(){return O}function u(){return y?y:O}function f(){return"4.1.1"}function p(){return F}function E(e){F=e===!0?!0:!1}function S(){var e="";return b.protocol&&b.restUrl&&b.restPort?e+b.protocol+"://"+b.restUrl+":"+b.restPort:e}function C(e,t,n){return n===!1?S()+"/rest/version/"+(e?e:"latest")+t:g.notification?S()+"/rest/version/"+(e?e:"latest")+(g.notification.isAnonymous()?"/anonymous/":"/user/")+g.getUser()+t:S()+"/rest/version/"+(e?e:"latest")+"/user/"+g.getUser()+t}var g,T=function(){var e={},t=0;this.size=function(){return t},this.add=function(n,i){return t++,e[n]=i,this},this.get=function(t){return e[t]},this.remove=function(n){return t--,delete e[n]},this.clear=function(){var n;for(n in e)e.hasOwnProperty(n)&&delete e[n]&&t--},this.entries=function(){return e}},I=function(){function e(e){var t,n,i;for(t in o)if(o[t]&&o.hasOwnProperty(t))for(i=o[t].length,n=0;i>n;n++)if(o[t][n].token===e)return o[t].splice(n,1),e;return!1}function t(e,t,n,s){var c,l=i,d=!1;if("string"!=typeof e)throw new Error("First parameter must be a string topic name.");if("function"!=typeof t)throw new Error("Second parameter must be a function.");if("undefined"!=typeof n){if("number"!=typeof n)throw new Error("Priority must be a number.");if(n>i||r>n)throw new Error("Priority must be between 1-10.");l=n}return s===!0&&(d=s),o[e]||(o[e]=[]),c=(++a).toString(),o[e].push({token:c,prio:l,func:t,temp:d}),o[e].sort(function(e,t){return parseFloat(t.prio)-parseFloat(e.prio)}),c}function n(t,n){var i,r,a,s;if(0===arguments.length)throw new Error("First parameter must be a string topic name.");for(a=Array.prototype.slice.call(arguments),s=a.shift(),i=o[s],r=i?i.length:0;r--;)i[r].func.apply(null,a),i[r].temp&&e(i[r].token)}var i=10,r=1,o={},a=-1;this.publish=n,this.subscribe=t,this.unsubscribe=e},v=new I,m={WEBRTC:{PLUGIN_ID:"fcsPlugin",MEDIA_STATE:{NOT_FOUND:"notfound",SEND_RECEIVE:"sendrecv",SEND_ONLY:"sendonly",RECEIVE_ONLY:"recvonly",INACTIVE:"inactive"},RTC_SIGNALING_STATE:{STABLE:"stable",HAVE_LOCAL_OFFER:"have-local-offer",HAVE_REMOTE_OFFER:"have-remote-offer",HAVE_LOCAL_PRANSWER:"have-local-pranswer",HAVE_REMOTE_PRANSWER:"have-remote-pranswer",CLOSED:"closed"},RTC_SDP_TYPE:{OFFER:"offer",ANSWER:"answer",PRANSWER:"pranswer"},ERROR:{ICE_ICELITE:"ICE_ICELITE"}},STRING:{NEW_LINE:"\n",CARRIAGE_RETURN:"\r",VIDEO:"video",AUDIO:"audio"},SDP:{A_LINE:"a=",M_LINE:"m=",CRYPTO:"crypto",FINGERPRINT:"fingerprint",ICE_UFRAG:"ice-ufrag:",ICE_PWD:"ice-pwd:",NACK:"nack",NACKPLI:"nack pli",SETUP_ACTIVE:"a=setup:active",SETUP_PASSIVE:"a=setup:passive",SETUP_ACTPASS:"a=setup:actpass"},HTTP_METHOD:{GET:"GET",POST:"POST",PUT:"PUT",DELETE:"DELETE",OPTIONS:"OPTIONS"},WEBSOCKET:{PROTOCOL:{SECURE:"wss",NONSECURE:"ws"},DEFAULT_PORT:"8581",STATUS:{OPENED:1,ALREADY_OPENED:2,CREATE_ERROR:3,CONNECTION_ERROR:4,NOT_FOUND:5,CONNECTION_CLOSED:6}},LONG_POLLING:{STATUS:{TRIGGERED_CONNECT:1}},NOTIFICATION:{STATUS:{NOT_STARTED:3,CONFIGURATION_ERROR:4,STOP_FOR_LP_TO_WS_UPGRADE:5}},EVENT:{XHR_REQUEST_NOT_INITIALIZED:"XHR_REQUEST_NOT_INITIALIZED",DEVICE_SUBSCRIPTION_STARTED:"DEVICE_SUBSCRIPTION_STARTED",DEVICE_SUBSCRIPTION_ENDED:"DEVICE_SUBSCRIPTION_ENDED",CONNECTION_REESTABLISHED:"CONNECTION_REESTABLISHED",CONNECTION_LOST:"CONNECTION_LOST",TOKEN_AUTH_STARTED:"TOKEN_AUTH_STARTED",BASIC_AUTH_STARTED:"BASIC_AUTH_STARTED",TOKEN_NOT_FOUND:"TOKEN_NOT_FOUND",SESSION_EXPIRED:"SESSION_EXPIRED",NOTIFICATION_CHANNEL_LOST:"NOTIFICATION_CHANNEL_LOST",FCS_SETUP_COMPLETED:"FCS_SETUP_COMPLETED",WEBSOCKET_CONNECTED:"WEBSOCKET_CONNECTED",WEBSOCKET_DISCONNECTED:"WEBSOCKET_DISCONNECTED",FORCE_CONNECTIVITY_CHECK:"FORCE_CONNECTIVITY_CHECK"},SUBSCRIPTION_EVENT:{TOKEN_OR_SESSION_LOSS:"TOKEN_OR_SESSION_LOSS",SUBSCRIPTION_SUCCESS:"SUBSCRIPTION_SUCCESS",EXTEND_SUCCESS:"EXTEND_SUCCESS",EXTEND_FAILURE:"EXTEND_FAILURE",REGULAR_EXTEND_PROCESSING:"REGULAR_EXTEND_PROCESSING",STOP_SUCCESS:"STOP_SUCCESS",STOP_FAILURE:"STOP_FAILURE",CONNECTION_LOSS:"CONNECTION_LOSS",SET_NOTIFICATION_ONERROR:"SET_NOTIFICATION_ONERROR",SET_NOTIFICATION_ONSUCCESS:"SET_NOTIFICATION_ONSUCCESS",TRIGGER_LONG_POLLING:"TRIGGER_LONG_POLLING",RESTART_SUBSCRIPTION_REQUEST:"RESTART_SUBSCRIPTION_REQUEST"},NOTIFICATION_EVENT:{NOTIFICATION_SUCCESS:"NOTIFICATION_SUCCESS",NOTIFICATION_FAILURE:"NOTIFICATION_FAILURE"},CACHE:{NOTIFYURL:"NotificationUrl",NOTIFYID:"NotificationId",SUBSCRIBEURL:"SubscriptionUrl",SUBSCRIBEEXPIRY:"SubscriptionExpiry",SUBSCRIBEEXTENDINTERVAL:"SubscriptionExtendInterval",USERNAME:"USERNAME",PASSWORD:"PASSWORD",SESSION:"SESSION"},TIMEOUT:{INTERVAL_TO_PREVENT_CONFLICTS:5e3,DEFAULT_CONNECTIVITY_CHECK_INTERVAL:1e4}},R=function(n){function i(){return U.getLogger("jQrestful")}function r(e,t,n,i){var r=e;return i&&(r.data=i),n&&(r.errorThrown=n),t&&(r.status=t.status,r.statusText=t.statusText,r.responseText=t.responseText,r.readyState=t.readyState),r}function o(e,n){var r,o;switch(i().error("parseError:'"+n+"' Status:'"+e.status+"' ResponseText:'"+e.responseText+"'"),e.responseText&&-1!==e.responseText.search("statusCode")&&(JSON.parse(e.responseText).subscribeResponse!==t?o=JSON.parse(e.responseText).subscribeResponse.statusCode:JSON.parse(e.responseText).authorizationResponse!==t&&(o=JSON.parse(e.responseText).authorizationResponse.statusCode)),o=o?o:e.status){case 401:r=g.Errors.AUTH;break;case 403:r=g.Errors.INCORRECT_LOGIN_PASS;break;case 19:r=g.Errors.LOGIN_LIMIT_CLIENT;break;case 20:r=g.Errors.LOGIN_LIMIT_TABLET;break;case 44:r=g.Errors.FORCE_LOGOUT_ERROR;break;case 46:r=g.Errors.TOKEN_NOT_FOUND;break;case 47:r=g.Errors.SESSION_EXPIRED;break;default:r=g.Errors.NETWORK}return r}function s(e,n,r){return i().error("parseErrorStatusCode:'"+n+"' Status:'"+e.status+"' ResponseText:'"+e.responseText+"'"),e.responseText&&-1!==e.responseText.search("statusCode")&&JSON.parse(e.responseText)[r]!==t?JSON.parse(e.responseText)[r].statusCode:401===e.status||403===e.status?e.status:400}var c=3e4,l=4e4,d={REQUEST_NOT_INITIALIZED:0,REQUEST_DONE:4};this.call=function(u,f,p,E,S,C,T,I){function v(e){try{F=e.status>=200&&e.status<300||304===e.status}catch(t){return t instanceof Error&&"Could not complete the operation due to error c00c023f."===t.description&&w.trace("Ajax request aborted internally. not calling failure callback"),-1}return F}var R,_,N,D,h,A,O,L,y,F,M,V=l,k=f.url,P=k.split("/rest/version/")[1],w=i();f&&f.data&&(R=f.data),b.polling&&(V=1e3*b.polling,V+=b.longpollingTolerans?b.longpollingTolerans:c),P&&-1===P.indexOf("isAlive")&&(_=P.split("/")[3],_||(_=k.substring(k.lastIndexOf("/")+1,k.length)),_=_.split("?")[0],R&&!R.imRequest?w.info("Send ajax request: "+_,R):w.info("Send ajax request: "+_)),"GET"===u&&(D=Y.serialize(R),D.length>0&&(k+=-1===k.indexOf("?")?"?"+D:"&"+D),R=null),N=new XMLHttpRequest,N.onload=function(){L(N)},N.onabort=function(){w.trace("Ajax request aborted internally. not calling failure callback")},N.onerror=function(){w.error("Ajax request error! Handle the error"),y(N)},b.ajaxHook&&(M=e[b.ajaxHook].call(N,e,{type:u,url:k,headers:I,data:R}),M&&(k=M.url?M.url:k,I=M.headers?M.headers:I)),N.open(u,k,g.isAsync()),g.isAsync()&&(N.withCredentials=b.cors?!0:!1,N.timeout=V),h={"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"},h=a(h,I);for(A in h)h.hasOwnProperty(A)&&N.setRequestHeader(A,h[A]);return N.setRequestHeader("X-CtlRTC-SPIDR-FQDN",g.fcsConfig.websocketIP),"string"!=typeof R&&(R=JSON.stringify(R)),N.send(R),O={type:u,url:k,dataType:"json",async:g.isAsync(),jsonp:!1,crossDomain:b.cors?!0:!1,timeout:V},L=function(e){if(e.readyState===d.REQUEST_DONE){if(F=v(e),-1===F)return;if(!F)return void y(e);var n={};try{"string"==typeof e.responseText&&e.responseText.length&&(n=JSON.parse(e.responseText)),"string"==typeof e.responseURL&&-1===e.responseURL.indexOf("isAlive")&&w.info("ajax success: "+e.status+" "+e.statusText,r(O,e,t,n))}catch(i){return i instanceof SyntaxError?w.error("Failed to parse json ajax response into object:"+e.responseText,r(O,e,t,n)):w.error("Unknown error:"+e.status+" "+e.statusText,r(O,e,t,n)),void y(e)}S&&"function"==typeof S&&(n=S(n)),p&&"function"==typeof p&&p(n)}},y=function(e){return w.error("ajax error: "+e.status+" "+e.statusText,r(O,e,e.statusText)),410===e.status?(w.error("410 Gone received"),void Y.callFunctionIfExist(g.notification.onGoneReceived)):(e.readyState===d.REQUEST_NOT_INITIALIZED&&(n.publish(m.EVENT.XHR_REQUEST_NOT_INITIALIZED),w.debug("Ajax request cannot be sent, this is a connection problem.")),void(E&&"function"==typeof E?E("addressBookResponse"===T?s(e,e.statusText,T):C&&"function"==typeof C?C(e,e.statusText):o(e,e.statusText)):w.trace("Error handler is not defined or not a function")))},g.isAsync()?4===N.readyState?setTimeout(function(){L(N)}):N.onreadystatechange=function(){-1===v(N)}:L(N),N}},_=function(e){return new R(e||v)},N=new _,D=function(e,t){function i(e){f=e.session}function r(){f=null}function o(e){d=e.username}function a(e){d=e.username,u=e.password,p=e.authname}function s(e){return e||(e={}),e.Accept||(e.Accept="application/json"),e["Content-Type"]||(e["Content-Type"]="application/json"),f?(e["x-session"]=f,delete e.Authorization):(p&&u?e.Authorization="basic "+n(p+":"+u):d&&u&&(e.Authorization="basic "+n(d+":"+u)),delete e["x-session"]),e}function c(n,i,r,o,a,s,c,l){var d=function(e){e===g.Errors.TOKEN_NOT_FOUND?(t.publish(m.EVENT.TOKEN_NOT_FOUND),f=null):e===g.Errors.SESSION_EXPIRED&&(t.publish(m.EVENT.SESSION_EXPIRED),f=null),o&&"function"==typeof o&&o(e)};return e.call(n,i,r,d,a,s,c,l)}function l(e,t,n,i,r,o,a,s){return a||(a={}),a.Accept||(a.Accept="application/json"),a["Content-Type"]||(a["Content-Type"]="application/json"),a["x-session"]&&delete a["x-session"],a.Authorization&&delete a.Authorization,a["x-token"]||(a["x-token"]=s),c(S,e,t,n,i,r,o,a)}var d,u,f,p,E="PUT",S="POST",C="GET",T="DELETE";this.call=function(e,t,n,i,r,o,a,l){return l=s(l),c(e,t,n,i,r,o,a,l)},this.sendPostRequest=function(e,t,n,i,r,o,a,d){return d?l(e,t,n,i,r,o,a,d):(a=s(a),c(S,e,t,n,i,r,o,a))},this.sendGetRequest=function(e,t,n,i,r,o,a){return a=s(a),c(C,e,t,n,i,r,o,a)},this.sendDeleteRequest=function(e,t,n,i,r,o,a){return a=s(a),c(T,e,t,n,i,r,o,a)},this.sendPutRequest=function(e,t,n,i,r,o,a){return a=s(a),c(E,e,t,n,i,r,o,a)},t.subscribe(m.EVENT.TOKEN_AUTH_STARTED,o,9),t.subscribe(m.EVENT.BASIC_AUTH_STARTED,a,10),t.subscribe(m.EVENT.DEVICE_SUBSCRIPTION_STARTED,i),t.subscribe(m.EVENT.DEVICE_SUBSCRIPTION_ENDED,r)},h=function(e,t){return new D(e||N,t||v)},A=new h,b={polling:30,iceCandidateCollectionTimeoutInterval:3e3,codecsToReplace:[{name:"opus",value:"109"}],pluginMode:{mode:"auto"}},O=null,L=null,y=null,F=!0,M=null,V=function(e,t,n){var i=null,r=null,o={},a=!0;this.isAsync=function(){return a},this.setAsync=function(e){a=e},this.getUser=d,this.getAuthUser=u,this.getDomain=l,this.getVersion=f,this.getDevice=function(){return i},this.setUserAuth=function(e,n,r){O=e,L=n,i=null;var o={username:e,password:n};"string"==typeof r&&r.trim().length>0?(o.authname=r,y=r):y=null,t.publish(m.EVENT.BASIC_AUTH_STARTED,o)},this.setTokenAuth=function(e,n){O=e,M=n,t.publish(m.EVENT.TOKEN_AUTH_STARTED,{username:e,token:n})},this.setDeviceAuth=function(e){i=e,O=null},this.AuthenticationType={USER:1,DEVICE:2},this.Errors={NETWORK:1,AUTH:2,STATE:3,PRIV:4,UNKNOWN:9,LOGIN_LIMIT_CLIENT:10,INCORRECT_LOGIN_PASS:11,INVALID_LOGIN:12,FORCE_LOGOUT_ERROR:13,LOGIN_LIMIT_TABLET:14,TOKEN_NOT_FOUND:15,SESSION_EXPIRED:16,VIDEO_SESSION_NOT_AVAILABLE:17,PENDING_REQUEST:18,NOT_ALLOWED_SERVICE:19,NOT_ALLOWED_METHOD:20,NOT_ALLOWED_INSTANCE:21,INVALID_PARAMETER:22,CONNECTION_ISSUE:23,MEDIA_NOT_FOUND:24,MEDIA_NOT_ALLOWED:25,CALL_FAILED:26,CALL_ENDED:27},this.setup=function(e){var n;for(n in e)e.hasOwnProperty(n)&&(b[n]=e[n]);t.publish(m.EVENT.FCS_SETUP_COMPLETED,b)},this.setPluginVersion=function(e){r=e},this.getPluginVersion=function(){return r},this.getServices=function(){return o},this.setServices=function(e){var t;if(e)for(t=0;t<e.length;t++)switch(e[t]){case"CallDisplay":o.callDisplay=!0;break;case"CallDisposition":o.callDisposition=!0;break;case"RestfulClient":o.restfulClient=!0;break;case"call":o.callControl=!0,o.remoteCallControl=!1;break;case"CallControl":o.callControl=!0,o.remoteCallControl=!1;break;case"RCC":o.callControl=!1,o.remoteCallControl=!0;break;case"CallMe":o.callMe=!0;break;case"Directory":o.directory=!0;break;case"ClickToCall":o.clickToCall=!0;break;case"Presence":o.presence=!0;break;case"AddressBook":o.contacts=!0;break;case"CallLog":o.history=!0;break;case"Custom":o.custom=!0;break;case"IM":o.IM=!0;break;case"Route":o.routes=!0;break;case"DataChannel":o.dataChannel=!0}},this.getUserLocale=function(t,n){e.sendGetRequest({url:C(1,"/localization",!1)},function(e){Y.callFunctionIfExist(t,e)},n)},this.isConnected=p},k=function(t,n,i){return new V(t||A,n||v,i||e)};g=new k,e.fcs=g,g.fcsConfig=b;var P=function(){function e(e){function n(e,n,r){if(i){var s={};if(s.user=d(),s.timestamp=(new Date).getTime(),s.logger=a,s.level=e,s.message=n,s.args=r,o)try{o(s.logger,s.level,s)}catch(c){return t}}return!1}var a=e;this.getName=function(){return a},this.trace=function(e,t){return n(r.TRACE,e,t)},this.debug=function(e,t){return n(r.DEBUG,e,t)},this.info=function(e,t){return n(r.INFO,e,t)},this.warn=function(e,t){return n(r.WARN,e,t)},this.error=function(e,t){return n(r.ERROR,e,t)},this.fatal=function(e,t){return n(r.FATAL,e,t)}}var n={},i=!1,r={OFF:"OFF",FATAL:"FATAL",ERROR:"ERROR",WARN:"WARN",INFO:"INFO",DEBUG:"DEBUG",TRACE:"TRACE",ALL:"ALL"},o=null;this.initLogging=function(e,t){return e&&"function"==typeof e?(o=e,i=t===!0?!0:!1,!0):!1},this.Level=r,this.isEnabled=function(){return i},this.getLogger=function(t){var i,r;return r=t&&0!==t.trim().length?t:"Default",n[r]?i=n[r]:(i=new e(r),n[i.getName()]=i),i}},w=function(){return new P},U=new w;g.logManager=U;var W=function(e,t,n){var i,r,o,a=e.getLogger("ServiceInvokeManager"),s=null,c=null,l=null;this.invoke=function(e,d,u,f,p){function E(e){return a.error("Service mapping error : "+e),"function"==typeof o?void o({errorText:e}):void 0}if(r=f,o=p,"object"!=typeof u||null===u){if(a.info("Data parameter not object!"),u)return a.error("Wrong parameter for data object "+u+" .The process cannot be made"),void E(n.INVALID_PARAMETER);u={},a.info("Data parameter undefined.Created object for data parameter.")}return i=u.serviceName?u.serviceName:"spidr",(s=t.serviceManagerMap.get(e))?"string"!=typeof i?void E(n.NOT_ALLOWED_SERVICE):(l=s.get(i))?(c=l[d])?(a.debug("Called Invoke Method - instance : "+e+" service : "+i+" method : "+d),c(u,r,o)):void E(n.NOT_ALLOWED_METHOD):void E(n.NOT_ALLOWED_SERVICE):void E(n.NOT_ALLOWED_INSTANCE)}},x=new W(U,b,g.Errors),H=function(){var e,n=function(){var e,t,n,i,r,o={},a=document.cookie,s=0;if(""===a)return o;for(e=a.split("; ");s<e.length;s+=1)t=e[s],n=t.indexOf("="),i=t.substring(0,n),r=t.substring(n+1),r=decodeURIComponent(r),o[i]=r;return o}(),i=[];for(e in n)n.hasOwnProperty(e)&&i.push(e);this.length=i.length,this.key=function(e){return 0>e||e>=i.length?null:i[e]},this.getItem=function(e){if(1!==arguments.length)throw new Error("Provide one argument");return n[e]||null},this.setItem=function(e,r){if(2!==arguments.length)throw new Error("Provide two arguments");n[e]===t&&(i.push(e),this.length++),n[e]=r;var o=e+"="+encodeURIComponent(r),a=new Date,s=new Date(a.getTime()+2592e6);o+="; max-age="+s,o+="; path=/",document.cookie=o},this.removeItem=function(e){if(1!==arguments.length)throw new Error("Provide one argument");var r,o=0;if(n[e]!==t){for(delete n[e],r=i.length;r>o;o+=1)if(i[o]===e){i.splice(o,1);break}this.length--,document.cookie=e+"=; max-age=0"}},this.clear=function(){for(var e=0;e<i.length;e++)document.cookie=i[e]+"=; max-age=0";n={},i=[],this.length=0}},B="undefined"!=typeof e.localStorage?e.localStorage:new H;e.cache=B;var G=function(e){var n=e.getLogger("utils");this.getProperty=function(e,t){return"undefined"==typeof e[t]?null:e[t]},this.callFunctionIfExist=function(){var e,t=Array.prototype.slice.call(arguments);if(e=t.shift(),"function"==typeof e)try{return e.apply(null,t)}catch(i){n.error("Exception occured:\n"+i.stack)}},this.compose=function(e,t){var n;for(n in e)"function"!=typeof e[n]||t[n]||(t[n]=e[n].bind(e))},this.parseAddress=function(e,n){var i="";return e.indexOf("sip:",0)>-1&&(e=e.replace("sip:","")),n===t||null===n?e.indexOf("@",0)>-1?"sip:"+e:e:(n.firstName&&""!==n.firstName&&(i+=n.firstName),n.lastName&&""!==n.lastName&&(i+=""===i?n.lastName:" "+n.lastName),""===i?e.indexOf("@",0)>-1?"sip:"+e:e:i+"<"+(e.indexOf("@",0)>-1?"sip:"+e:e)+">")},this.getTimestamp=function(){return(new Date).getTime()},this.Queue=function(){var e;this.enqueue=function(t){"undefined"==typeof e&&(e=[]),e.push(t)},this.dequeue=function(){return e.shift()},this.peek=function(){return e[0]},this.size=function(){return"undefined"==typeof e?0:e.length}},this.getQueue=function(){return new this.Queue},this.getInteger=function(e){return isNaN(e)||null===e||e===t?0:parseInt(e)},this.serialize=function(e){var t,n="";for(t in e)e.hasOwnProperty(t)&&(n.length>0&&(n+="&"),n+=encodeURI(t+"="+e[t]));return n}};Function.prototype.bind||(Function.prototype.bind=function(e){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),n=this,i=function(){},r=function(){return n.apply(this instanceof i&&e?this:e,t.concat(Array.prototype.slice.call(arguments)))};return i.prototype=this.prototype,r.prototype=new i,r});var Y=new G(U),j=function(e,t){var r=this,o="JSL/VHVybkNyZWRlbnRpYWxz";r.get=function(){return JSON.parse(i(e.getItem(o)))},r.save=function(i){e.setItem(o,n(JSON.stringify(i))),t.callFunctionIfExist(r.onCredentialsReceived)},r.remove=function(){e.removeItem(o)}},q=new j(B,Y),J=function(e,n,i){function r(e,n,r){var o;if(null!==e&&e!==t)return(o=e.match(/m=audio [\w\W]*?(\r|\n)/))?(o=o[0].split(" "),o.shift(),o.shift(),o.shift(),-1===o.indexOf(n)?e:-1!==e.indexOf(r)?e:(e=e.split(i.SDP.M_LINE+i.STRING.VIDEO),e[0]=e[0]+r+c+s,e=e[1]?e[0]+i.SDP.M_LINE+i.STRING.VIDEO+e[1]:e[0])):e}var o,a=e.getLogger("sdpParser"),s="\n",c="\r";this.init=function(e){o=this,o.sessionDescription={},o.mediaDescriptions=[],o.sdp=e,o.parseSDP(),o.setSessionDescriptionAttributes(),o.setMediaDescriptionsAttributes()},this.parseSDP=function(){var e,t=[],n=1;for(t=o.sdp.split(/^(?=m=)/m),o.sessionDescription.data=t[0],n;n<t.length;n++)e={},e.data=t[n],o.mediaDescriptions.push(e)},this.setSessionDescriptionAttributes=function(){var e,t=0,n=o.sessionDescription.data.split(/\r\n|\r|\n/);for(t;t<n.length;t++)n[t].match("^e=")?o.sessionDescription.email=n[t].split("=")[1]:n[t].match("^c=")&&(e=n[t].split("=")[1],o.sessionDescription.connection=e,o.sessionDescription.ip=e.split(" ")[2])},this.setMediaDescriptionsAttributes=function(){var e,t,n,i,r=0;for(e in o.mediaDescriptions)if(o.mediaDescriptions.hasOwnProperty(e)){t=o.mediaDescriptions[e].data.split(/\r\n|\r|\n/),this.mediaDescriptions[e].direction="sendrecv";for(r in t)t.hasOwnProperty(r)&&(t[r].match("^m=")?(n=t[r].split("=")[1],o.mediaDescriptions[e].media=n,o.mediaDescriptions[e].port=n.split(" ")[1]):t[r].match("^a=sendrecv")||t[r].match("^a=sendonly")||t[r].match("^a=recvonly")||t[r].match("^a=inactive")?o.mediaDescriptions[e].direction=t[r].split("=")[1]:t[r].match("^c=")&&(i=t[r].split("=")[1],o.mediaDescriptions[e].connection=i,o.mediaDescriptions[e].ip=i.split(" ")[2]))}},this.isHold=function(e){var t,n,i=!1,r=0;for(r in o.mediaDescriptions)if(o.mediaDescriptions.hasOwnProperty(r)&&(n=this.mediaDescriptions[r],n.ip?t=n.ip:o.sessionDescription.ip&&(t=o.sessionDescription.ip),0!==n.port)){if(!("inactive"===n.direction||"sendonly"===n.direction&&e||"recvonly"===n.direction&&!e||"0.0.0.0"===t)){i=!1;break}i=!0}return i},this.isRemoteHold=function(){return this.isHold(!0)},this.isLocalHold=function(){return this.isHold(!1)},this.getSessionDescription=function(){
return o.sessionDescription},this.getMediaDescriptions=function(){return o.mediaDescriptions},this.isSdpHas=function(e,n){var r=!1;return null===e||e===t?r:-1!==e.indexOf(i.SDP.M_LINE+n)?r=!0:r},this.isSdpHasAudio=function(e){return this.isSdpHas(e,i.STRING.AUDIO)},this.isSdpHasVideo=function(e){return this.isSdpHas(e,i.STRING.VIDEO)},this.isSdpHasUfrag=function(e){var n=!1;return null===e||e===t?n:-1!==e.indexOf(i.SDP.A_LINE+i.SDP.ICE_UFRAG)?n=!0:n},this.isSdpHasMediaWithExpectedPort=function(e,n,r){return null===e||e===t?!1:-1!==e.indexOf(i.SDP.M_LINE+n+" "+r)},this.isSdpHasAudioWithZeroPort=function(e){return this.isSdpHasMediaWithExpectedPort(e,i.STRING.AUDIO,0)},this.isSdpHasVideoWithZeroPort=function(e){return this.isSdpHasMediaWithExpectedPort(e,i.STRING.VIDEO,0)},this.isSdpHasAudioWithOnePort=function(e){return this.isSdpHasMediaWithExpectedPort(e,i.STRING.AUDIO,1)},this.isSdpHasVideoWithOnePort=function(e){return this.isSdpHasMediaWithExpectedPort(e,i.STRING.VIDEO,1)},this.isSdpHasAudioWithNinePort=function(e){return this.isSdpHasMediaWithExpectedPort(e,i.STRING.AUDIO,9)},this.isSdpHasVideoWithNinePort=function(e){return this.isSdpHasMediaWithExpectedPort(e,i.STRING.VIDEO,9)},this.replaceZeroVideoPortWithOne=function(e){return null===e||e===t?e:(this.isSdpHasVideoWithZeroPort(e)&&(e=e.replace(i.SDP.M_LINE+i.STRING.VIDEO+" 0 ",i.SDP.M_LINE+i.STRING.VIDEO+" 1 ")),e)},this.getSdpDirection=function(e,t){var n,r,o="",s=[],c=i.WEBRTC.MEDIA_STATE.INACTIVE;if(r=function(e){a.info("getSdpDirection: type= "+t+" state= "+e)},!this.isSdpHas(e,t))return r(c),c;if(this.isSdpHasMediaWithExpectedPort(e,t,0))return r(c),c;for(s=e.split(/^(?=m=)/m),n=0;n<s.length;n++)if(o=s[n],-1!==o.indexOf(i.SDP.M_LINE+t))return-1!==o.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.SEND_RECEIVE)?(c=i.WEBRTC.MEDIA_STATE.SEND_RECEIVE,r(c),c):-1!==o.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.SEND_ONLY)?(c=i.WEBRTC.MEDIA_STATE.SEND_ONLY,r(c),c):-1!==o.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.RECEIVE_ONLY)?(c=i.WEBRTC.MEDIA_STATE.RECEIVE_ONLY,r(c),c):-1!==o.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.INACTIVE)?(r(c),c):c=i.WEBRTC.MEDIA_STATE.SEND_RECEIVE;return c=i.WEBRTC.MEDIA_STATE.NOT_FOUND,r(c),c},this.getAudioSdpDirection=function(e){return this.getSdpDirection(e,i.STRING.AUDIO)},this.getVideoSdpDirection=function(e){return this.getSdpDirection(e,i.STRING.VIDEO)},this.isAudioSdpDirectionInactive=function(e){return this.getAudioSdpDirection(e)===i.WEBRTC.MEDIA_STATE.INACTIVE},this.isAudioSdpDirectionSendrecv=function(e){return this.getAudioSdpDirection(e)===i.WEBRTC.MEDIA_STATE.SEND_RECEIVE},this.isAudioSdpDirectionSendonly=function(e){return this.getAudioSdpDirection(e)===i.WEBRTC.MEDIA_STATE.SEND_ONLY},this.isAudioSdpDirectionRecvonly=function(e){return this.getAudioSdpDirection(e)===i.WEBRTC.MEDIA_STATE.RECEIVE_ONLY},this.isSdpContainsAudioDirection=function(e){return this.getAudioSdpDirection(e)!==i.WEBRTC.MEDIA_STATE.NOT_FOUND},this.isVideoSdpDirectionInactive=function(e){return this.getVideoSdpDirection(e)===i.WEBRTC.MEDIA_STATE.INACTIVE},this.isVideoSdpDirectionSendrecv=function(e){return this.getVideoSdpDirection(e)===i.WEBRTC.MEDIA_STATE.SEND_RECEIVE},this.isVideoSdpDirectionSendonly=function(e){return this.getVideoSdpDirection(e)===i.WEBRTC.MEDIA_STATE.SEND_ONLY},this.isVideoSdpDirectionRecvonly=function(e){return this.getVideoSdpDirection(e)===i.WEBRTC.MEDIA_STATE.RECEIVE_ONLY},this.isSdpContainsVideoDirection=function(e){return this.getVideoSdpDirection(e)!==i.WEBRTC.MEDIA_STATE.NOT_FOUND},this.changeDirection=function(e,n,r,o){var s,c,l="",d=[],u="changeDirection: before= "+n+" after= "+r;if(n===r)return e;if(o===t||null===o)a.info(u+" for all media types");else{if(n!==this.getSdpDirection(e,o))return e;a.info(u+" type= "+o)}for(d=e.split(/^(?=m=)/m),c=0;c<d.length;c++)s=d[c],(o===t||null===o||-1!==s.indexOf(i.SDP.M_LINE+o))&&(s=s.replace(i.SDP.A_LINE+n,i.SDP.A_LINE+r)),l+=s;return l},this.updateSdpDirection=function(e,t,n){a.info("updateSdpDirection: type= "+t+" direction= "+n);var i=this.getSdpDirection(e,t);return this.changeDirection(e,i,n,t)},this.updateAudioSdpDirection=function(e,t){a.info("updateSdpDirection: type= "+i.STRING.AUDIO+" direction= "+t);var n=this.getSdpDirection(e,i.STRING.AUDIO);return this.changeDirection(e,n,t,i.STRING.AUDIO)},this.updateVideoSdpDirection=function(e,t){a.info("updateSdpDirection: type= "+i.STRING.VIDEO+" direction= "+t);var n=this.getSdpDirection(e,i.STRING.VIDEO);return this.changeDirection(e,n,t,i.STRING.VIDEO)},this.updateAudioSdpDirectionToInactive=function(e){return this.updateAudioSdpDirection(e,i.WEBRTC.MEDIA_STATE.INACTIVE)},this.updateVideoSdpDirectionToInactive=function(e){return this.updateVideoSdpDirection(e,i.WEBRTC.MEDIA_STATE.INACTIVE)},this.isSdpHasDirection=function(e){var n,r,o,a;return null===e||e===t?!1:(n=e.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.SEND_RECEIVE,0),r=e.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.SEND_ONLY,0),o=e.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.RECEIVE_ONLY,0),a=e.indexOf(i.SDP.A_LINE+i.WEBRTC.MEDIA_STATE.INACTIVE,0),n+1+(r+1)+(o+1)+(a+1)===0?!1:!0)},this.isSdpEnabled=function(e,n){var r,o="isSdpEnabled for type "+n+": ",s=!1;return null===e||e===t?!1:this.isSdpHasMediaWithExpectedPort(e,n,0)?(a.info(o+s),s):n===i.STRING.VIDEO&&(r=this.getVideoSdpDirection(e),r===i.WEBRTC.MEDIA_STATE.RECEIVE_ONLY||r===i.WEBRTC.MEDIA_STATE.INACTIVE)?(a.info(o+s),s):(this.isSdpHas(e,n)&&(s=!0),a.info(o+s),s)},this.isAudioSdpEnabled=function(e){return this.isSdpEnabled(e,i.STRING.AUDIO)},this.isVideoSdpEnabled=function(e){return this.isSdpEnabled(e,i.STRING.VIDEO)},this.isSdpVideoReceiveEnabled=function(e){var n,r="isSdpVideoReceiveEnabled: ",o=!1;return null===e||e===t?!1:-1!==e.indexOf(i.SDP.M_LINE+i.STRING.VIDEO+" 0")?(a.info(r+o),o):(n=this.getVideoSdpDirection(e),n===i.WEBRTC.MEDIA_STATE.SEND_ONLY||n===i.WEBRTC.MEDIA_STATE.INACTIVE?(a.info(r+o),o):-1!==e.indexOf(i.SDP.M_LINE+i.STRING.VIDEO)?(o=!0,a.info(r+o),o):(a.info(r+o),o))},this.updateH264Level=function(e){var t,n,r,o,a,s="",c="",l=[],d=/\r\n|\r|\n/m,u="";for(l=e.split(/^(?=m=)/m),t=0;t<l.length;t++){if(c=l[t],-1!==c.indexOf(i.SDP.M_LINE+i.STRING.VIDEO)){for(n=c.split(d),r=0;r<n.length;r++)o=n[r],o&&-1!==o.indexOf("a=rtpmap:")&&-1!==o.indexOf("H264")?(a=o.split(/\:| /m),o=o+i.STRING.CARRIAGE_RETURN+i.STRING.NEW_LINE,o=o+"a=fmtp:"+a[1]+" profile-level-id=428014;",o=o+i.STRING.CARRIAGE_RETURN+i.STRING.NEW_LINE):o&&""!==o&&(o=o+i.STRING.CARRIAGE_RETURN+i.STRING.NEW_LINE),u+=o;c=u}s+=c}return s},this.updateH264LevelTo42E01F=function(e,n){return null===e||e===t?e:(n&&(a.debug("Updating the H264 profile-level-id to 42e01f"),e=e.replace(/profile-level-id=4280/g,"profile-level-id=42e0")),e)},this.isSdpVideoCandidateEnabled=function(e){var t="isSdpVideoCandidateEnabled: ",n=!1;return this.isSdpHasVideoWithZeroPort(e)||this.isVideoSdpDirectionInactive(e)?(a.info(t+n),n):this.isSdpHasVideo(e)?(a.info(t+n),n):(n=!0,a.info(t+n),!0)},this.deleteFingerprintFromSdp=function(e,n){if(null===e||e===t)return e;if(n)return e;for(;-1!==e.indexOf("a=fingerprint:");)e=e.replace(/(a=fingerprint:[\w\W]*?(:\r|\n))/,"");for(;-1!==e.indexOf("a=setup:");)e=e.replace(/(a=setup:[\w\W]*?(:\r|\n))/,"");return e},this.deleteCryptoFromSdp=function(e,n){if(null!==e&&e!==t){if(!n)return e;for(;-1!==e.indexOf("a=crypto:");)e=e.replace(/(a=crypto:[\w\W]*?(:\r|\n))/,"");return e}},this.deleteCryptoZeroFromSdp=function(e){if(null===e||e===t)return e;for(;-1!==e.indexOf("a=crypto:0");)e=e.replace(/(a=crypto:0[\w\W]*?(:\r|\n))/,"");return e},this.updateAudioCodec=function(e){var i,r,o,a,l,d,u,f="",p="",E=[],S=/\r\n|\r|\n/m,C="",g=[];if(g=n.codecsToRemove,g===t)return e;for(E=e.split(/^(?=m=)/m),i=0;i<E.length;i++){if(p=E[i],this.isSdpHasAudio(p)){for(r=p.split(S),o=0;o<r.length;o++){for(a=r[o],u=0;u<g.length;u++)l=g[u],a&&this.isSdpHasAudio(a)?(d=new RegExp(" "+l,"g"),a=a.replace(d,""),0===u&&(a=a+c+s)):a&&-1!==a.indexOf("a=fmtp:"+l)?a=a.replace(/a=fmtp[\w\W]*/,""):a&&-1!==a.indexOf("a=rtcp-fb:"+l)?a=a.replace(/a=rtcp-fb[\w\W]*/,""):a&&-1!==a.indexOf("a=rtpmap:"+l)?a=a.replace(/a=rtpmap[\w\W]*/,""):a&&""!==a&&0===u&&(a=a+c+s);C+=a}p=C}f+=p}return f},this.updateVideoCodec=function(e){var i,r,o,a,l,d,u,f="",p="",E=[],S=/\r\n|\r|\n/m,C="",g=[];if(g=n.codecsToRemoveForVideo,g===t)return e;for(E=e.split(/^(?=m=)/m),i=0;i<E.length;i++){if(p=E[i],this.isSdpHasVideo(p)){for(r=p.split(S),o=0;o<r.length;o++){for(a=r[o],u=0;u<g.length;u++)l=g[u],a&&this.isSdpHasVideo(a)?(d=new RegExp(" "+l,"g"),a=a.replace(d,""),0===u&&(a=a+c+s)):a&&-1!==a.indexOf("a=fmtp:"+l)?a=a.replace(/a=fmtp[\w\W]*/,""):a&&-1!==a.indexOf("a=rtcp-fb:"+l)?a=a.replace(/a=rtcp-fb[\w\W]*/,""):a&&-1!==a.indexOf("a=rtpmap:"+l)?a=a.replace(/a=rtpmap[\w\W]*/,""):a&&""!==a&&0===u&&(a=a+c+s);C+=a}p=C}f+=p}return f},this.removeAudioCodec=function(e,t){var n,i,r,o,a,l,d="",u="",f=[],p=/\r\n|\r|\n/m,E="";for(f=e.split(/^(?=m=)/m),n=0;n<f.length;n++){if(u=f[n],this.isSdpHasAudio(u)){for(i=u.split(p),r=0;r<i.length;r++)o=i[r],o&&this.isSdpHasAudio(o)?(l=new RegExp(" "+t+"($| )","m"),a=i[r].split(/RTP[\w\W]*/),o=o.replace(/(\m=audio+)\s(\w+)/,""),o=o.trim(),o=o.replace(l," "),o=a[0]+o+c+s):o&&-1!==o.indexOf("a=fmtp:"+t)?o=o.replace(/a=fmtp[\w\W]*/,""):o&&-1!==o.indexOf("a=rtpmap:"+t)?o=o.replace(/a=rtpmap[\w\W]*/,""):o&&-1!==o.indexOf("a=rtcp-fb:"+t)?o=o.replace(/a=rtcp-fb[\w\W]*/,""):o&&""!==o&&(o=o+c+s),E+=o;u=E}d+=u}return d},this.removeRTXCodec=function(e){var n,i,r;return null===e||e===t?e:(i=this.getVp8Ssrc(e),a.debug("vp8SSRC = "+i),r=this.getRtxSsrc(e),a.debug("rtxSSRC = "+r),e=this.removeSsrcId(e,r),e=e.replace(/(a=ssrc-group:FID[\w\W]*?(:\r|\n))/g,""),-1===e.indexOf("rtx/90000")?e:(n=this.getRTXPayloadType(e),a.debug("removeRTXCodec : Removing rtx video codec "+n),e=this.removeVideoCodec(e,n)))},this.getVp8Ssrc=function(e){var n,i,r,o,s=/\r\n|\r|\n/m;if(null===e||e===t)return-1;if(-1===e.indexOf("a=ssrc-group:FID "))return-1;for(n=e.split("a=ssrc-group:FID "),i=n[1].split(s),r=i[0].split(" "),o=0;o<r.length;o++)a.debug("ssrcArray["+o+"] : "+r[o]);return r[0]},this.getRtxSsrc=function(e){var n,i,r,o,s=/\r\n|\r|\n/m;if(null===e||e===t)return-1;if(-1===e.indexOf("a=ssrc-group:FID "))return-1;for(n=e.split("a=ssrc-group:FID "),i=n[1].split(s),r=i[0].split(" "),o=0;o<r.length;o++)a.debug("ssrcArray["+o+"] : "+r[o]);return r[1]},this.removeSsrcId=function(e,n){var i,r,o,a="",l=/\r\n|\r|\n/m,d="";if(null===e||e===t)return e;for(i=e.split(l),r=0;r<i.length;r++)o=i[r],o&&-1!==o.indexOf("a=ssrc:"+n)?o=o.replace(/a=ssrc:[\w\W]*/,""):o&&""!==o&&(o=o+c+s),d+=o;return a=d},this.removeG722Codec=function(e){return e},this.getPayloadTypeOf=function(e,t){var n,i,r,o=[];if(-1===t.indexOf(e))return-1;for(i=t.match(/(a=rtpmap[\w\W]*?(:\r|\n))/g),r=0;r<i.length;r++)-1!==i[r].search(new RegExp(e,"i"))&&(n=i[r].match(/^[^\d]*(\d+)/g),n=n[0].split(":"),o.push(n[1]));return a.debug("getPayloadTypeOf("+e+") = "+o[0]),o.length<2?o[0]:o},this.replaceTelephoneEventPayloadType=function(e,t,n){var i,r,o,s,c,l,d,u="",f="";if(!e||-1===e.indexOf("telephone-event"))return e;if(r=/^\.*(a=rtpmap:)(\d*)( telephone-event[ \w+ ]*[ \/+ ]*[ \w+ ]*)\r\n?/m,t===n)return e;for(i=e,r=new RegExp("^\\.*a=rtpmap:"+n+" telephone-event[ \\/+ ]*([ \\w+ ]*)\\r\n","m"),o=i.match(r),f=null!==o&&o.length>=2&&""!==o[1]?o[1]:8e3,i=i.replace(r,"a=rtpmap:"+t+" telephone-event/"+f+"\r\n"),r=new RegExp("^\\.*(m=audio )[ \\w+ ]*[ \\/+ ]*[ \\w+ ]*( "+n+")","mg"),o=i.match(r),null!==o&&o.length>=1&&""!==o[0]&&(s=o[0],s=s.replace(n,t),i=i.replace(r,s)),c=i.split(/^(?=m=)/m),l=0;l<c.length;l++)d=c[l],this.isSdpHasAudio(d)&&(r=new RegExp("^\\.*a=fmtp:"+n,"mg"),d=d.replace(r,"a=fmtp:"+t)),u+=d;return""!==u&&(i=u),a.debug("replaceTelephoneEventPayloadType: newcode "+n+" is replaced with oldcode "+t),i},this.replaceOpusCodec=function(e){var t,n,i,r,o,s,c="",l=109,d="";if(!e||-1===e.indexOf("opus"))return e;for(t=/^\.*(a=rtpmap:)(\d*)( opus)/m,n=e.match(t),null!==n&&n.length>=3&&""!==n[2]?c=n[2]:a.warn("sdp has opus without codec number"),e=e.replace(t,"a=rtpmap:"+l+" opus"),t=new RegExp("^\\.*(m=audio )[ \\w+ ]*[ \\/+ ]*[ \\w+ ]*( "+c+")","mg"),n=e.match(t),null!==n&&n.length>=1&&""!==n[0]&&(i=n[0],i=i.replace(c,l),e=e.replace(t,i)),r=e.split(/^(?=m=)/m),o=0;o<r.length;o++)s=r[o],this.isSdpHasAudio(s)&&(t=new RegExp("^\\.*a=fmtp:"+c,"mg"),s=s.replace(t,"a=fmtp:"+l)),d+=s;return""!==d&&(e=d),a.debug("replaceOpusCodec: new codec= "+l),e},this.getG7228000PayloadType=function(e){return this.getPayloadTypeOf("G722/8000",e)},this.getVP8PayloadType=function(e){return this.getPayloadTypeOf("VP8/90000",e)},this.getG72216000PayloadType=function(e){return this.getPayloadTypeOf("G722/16000",e)},this.getRTXPayloadType=function(e){return this.getPayloadTypeOf("rtx/90000",e)},this.getH264PayloadType=function(e){return this.getPayloadTypeOf("H264/90000",e)},this.isSdpHasTelephoneEventWithRate=function(e,n){return null===e||e===t?!1:-1!==e.indexOf("telephone-event/"+n)},this.isSdpHasTelephoneEvent=function(e){return null===e||e===t?!1:-1!==e.indexOf("telephone-event/")},this.isSdpHasVP8Codec=function(e){return null===e||e===t?!1:-1!==e.indexOf("VP8/90000")},this.isSdpHasH264Codec=function(e){return null===e||e===t?!1:-1!==e.indexOf("H264/90000")},this.checkSupportedVideoCodecs=function(e,n,r){var o;return null===e||e===t?e:this.isVideoCodecsSupported(e,r)?e:(n?(o=this.removeAllVideoCodecs(e),o=this.addVP8Codec(o,n),o=this.updateSdpVideoPort(o,!1),o=this.performVideoPortZeroWorkaround(o)):this.isSdpHasVP8Codec(e)?o=this.removeVideoDescription(e):-1!==e.indexOf(i.SDP.M_LINE+i.STRING.VIDEO+" 0 ",0)?o=this.addVP8Codec(e,o):(o=this.updateSdpVideoPort(e,!1),o=this.addVP8Codec(o,o)),o)},this.isVideoCodecsSupported=function(e,t){return this.isSdpHasVP8Codec(e)?!0:t&&this.isSdpHasH264Codec(e)?!0:!1},this.removeAllVideoCodecs=function(e){var n,i,r,o,s;if(null===e||e===t)return e;if(n=new RegExp("^\\.*(m=video )(\\d*)( RTP/SAVPF )([ \\w+ ]*[ \\/+ ]*[ \\w+ ])\\r\n","m"),o=e,i=o.match(n),null!==i&&i.length>=5&&""!==i[0])for(r=i[4].split(" "),s=0;s<r.length;s++)a.debug("codec["+s+"] : "+r[s]),o=this.removeVideoCodec(o,r[s]);return o},this.removeVideoCodec=function(e,n){var i,r,o,a,l,d="",u="",f=[],p=/\r\n|\r|\n/m,E="";if(null===e||e===t||!n)return e;for(f=e.split(/^(?=m=)/m),i=0;i<f.length;i++){if(u=f[i],this.isSdpHasVideo(u)){for(r=u.split(p),o=0;o<r.length;o++)a=r[o],a&&this.isSdpHasVideo(a)?(l=new RegExp(" "+n,"g"),a=a.replace(l,""),a=a+c+s):a&&-1!==a.indexOf("a=fmtp:"+n)?a=a.replace(/a=fmtp[\w\W]*/,""):a&&-1!==a.indexOf("a=rtpmap:"+n)?a=a.replace(/a=rtpmap[\w\W]*/,""):a&&-1!==a.indexOf("a=rtcp-fb:"+n)?a=a.replace(/a=rtcp-fb[\w\W]*/,""):a&&""!==a&&(a=a+c+s),E+=a;u=E}d+=u}return d},this.addVP8Codec=function(e,t){var n,r,o,a,l,d,u,f,p,E,S="",C="",g=[],T=/\r\n|\r|\n/m,I="";if(this.isSdpHasVP8Codec(e))return e;for(g=e.split(/^(?=m=)/m),n=0;n<g.length;n++){if(C=g[n],this.isSdpHasVideo(C)){if(t&&this.isSdpHasVideo(t)&&this.isSdpHasVP8Codec(t))a=this.getVP8PayloadType(t),-1!==C.indexOf("a=rtpmap:"+a)&&this.removeSdpLineContainingText(C,"a=rtpmap:"+a);else{for(l=100;-1!==C.indexOf("a=rtpmap:"+l);)l+=1;a=l}for(r=C.split(T),o=0;o<r.length;o++)d=r[o],d&&this.isSdpHasVideo(d)?(-1===d.indexOf(a)&&(d=d+" "+a),d=d+c+s+"a=rtpmap:"+a+" VP8/90000"+c+s):d&&""!==d&&(d=d+c+s),I+=d;C=I}S+=C}return u=this.checkICEParams(S,"video",i.SDP.ICE_UFRAG),2>u&&(p=this.getICEParams(S,i.SDP.ICE_UFRAG,!1),p&&(S=this.restoreICEParams(S,"video",i.SDP.ICE_UFRAG,p))),f=this.checkICEParams(S,"video",i.SDP.ICE_PWD),2>f&&(E=this.getICEParams(S,i.SDP.ICE_PWD,!1),E&&(S=this.restoreICEParams(S,"video",i.SDP.ICE_PWD,E))),S},this.removeSdpLineContainingText=function(e,n){var i,r;if(null===e||e===t||!n)return e;for(r=e.split(s),e=r[0]+s,i=1;i<r.length-1;i++)-1!==r[i].indexOf(n)?a.debug("removed line which contains "+n):e+=r[i]+s;return e},this.removeVideoDescription=function(e){var n,i="",r="",o=[];if(null===e||e===t)return e;for(o=e.split(/^(?=m=)/m),n=0;n<o.length;n++)r=o[n],this.isSdpHasVideo(r)?a.debug("removeVideoDescription : m=video description removed"):i+=r;return i},this.updateSdpVideoPort=function(e,n){var r,o;return null===e||e===t?e:(a.debug("updateSdpVideoPort: status= "+n),r=e,n?o=i.SDP.M_LINE+i.STRING.VIDEO+" 1":(o=i.SDP.M_LINE+i.STRING.VIDEO+" 0",r=this.updateSdpDirection(r,i.STRING.VIDEO,i.WEBRTC.MEDIA_STATE.INACTIVE)),this.isSdpHasVideo(r)&&(r=r.replace(/m=video [0-9]+/,o)),r)},this.performVideoPortZeroWorkaround=function(e){return null===e||e===t?e:this.isSdpHasVideoWithZeroPort(e)?(e=this.addSdpMissingCryptoLine(e),e=this.replaceZeroVideoPortWithOne(e),e=this.updateVideoSdpDirectionToInactive(e)):e},this.addSdpMissingCryptoLine=function(e){var t,n,r,o=null,s=/\r\n|\r|\n/m;if(-1===e.indexOf(i.SDP.M_LINE+i.STRING.VIDEO+" 0 ",0))return e;for(t=e.split(i.SDP.M_LINE+i.STRING.VIDEO),n=t[0].split(s),r=0;r<n.length;r++)if(-1!==n[r].indexOf(i.SDP.A_LINE+i.SDP.CRYPTO)||-1!==n[r].indexOf(i.SDP.A_LINE+i.SDP.FINGERPRINT)){o=n[r];break}return null===o?e:(-1!==t[0].indexOf(i.SDP.A_LINE+i.SDP.CRYPTO)?-1===t[1].indexOf(i.SDP.A_LINE+i.SDP.CRYPTO,0)&&(t[1]+=o+"\n",a.debug("addSdpMissingCryptoLine : crypto line is added : "+o)):-1!==t[0].indexOf(i.SDP.A_LINE+i.SDP.FINGERPRINT,0)&&-1===t[1].indexOf(i.SDP.A_LINE+i.SDP.FINGERPRINT,0)&&(t[1]+=o+"\na=setup:passive\n",a.debug("addSdpMissingCryptoLine : dtls lines are added : "+o+"and a=setup:passive"),a.debug("dtls enabled: known issue by webrtc may be fixed! Check it")),e=t.join(i.SDP.M_LINE+i.STRING.VIDEO))},this.checkICEParams=function(e,n,r){var o,a;if(null===e||e===t)return 0;if(o=e.split("m=video"),o.length<2)return 0;switch(r){case i.SDP.ICE_UFRAG:a="audio"===n?o[0].split("a=ice-ufrag:"):o[1].split("a=ice-ufrag:");break;case i.SDP.ICE_PWD:a="audio"===n?o[0].split("a=ice-pwd:"):o[1].split("a=ice-pwd:");break;default:return 0}return a.length},this.getICEParams=function(e,n,r){var o,a,s,c;if(null!==e&&e!==t){switch(n){case i.SDP.ICE_UFRAG:o=e.split("a=ice-ufrag:");break;case i.SDP.ICE_PWD:o=e.split("a=