Your IP : 3.131.37.236


Current Path : /home/bitrix/initial_sites/home-comfort.in.ua/bitrix/js/pull/client/
Upload File :
Current File : /home/bitrix/initial_sites/home-comfort.in.ua/bitrix/js/pull/client/pull.client.min.js

(function(){if(!window.BX){window.BX={}}else if(window.BX.PullClient){return}var e=window.BX;var t=window.protobuf;var n=19;var o=60;var i=30*60;var s=24*60*60;var r=6e4;var c="bx-pull-session";var a=20;var u={WebSocket:"webSocket",LongPolling:"longPolling"};var l={Online:"online",Offline:"offline",Connecting:"connect"};var h={Unknown:0,Client:1,Backend:2};var f={Server:"server",Client:"client",Online:"online",Status:"status",Revision:"revision"};var p={NORMAL_CLOSURE:1e3,SERVER_DIE:1001,CONFIG_REPLACED:3e3,CHANNEL_EXPIRED:3001,SERVER_RESTARTED:3002,CONFIG_EXPIRED:3003,MANUAL:3004};var d={CHANNEL_EXPIRE:"CHANNEL_EXPIRE",CONFIG_EXPIRE:"CONFIG_EXPIRE",SERVER_RESTART:"SERVER_RESTART"};var g=t.roots["push-server"]["Response"];var m=t.roots["push-server"]["ResponseBatch"];var y=t.roots["push-server"]["Request"];var v=t.roots["push-server"]["RequestBatch"];var b=t.roots["push-server"]["IncomingMessagesRequest"];var S=t.roots["push-server"]["IncomingMessage"];var k=t.roots["push-server"]["Receiver"];var E=function(t){t=t||{};var n=this;this.userId=t.userId?t.userId:typeof e.message!=="undefined"&&e.message.USER_ID?e.message.USER_ID:0;this.siteId=t.siteId?t.siteId:typeof e.message!=="undefined"&&e.message.SITE_ID?e.message.SITE_ID:"none";this.restClient=typeof t.restClient!=="undefined"?t.restClient:e.rest;this.enabled=typeof t.serverEnabled!=="undefined"?t.serverEnabled==="Y"||t.serverEnabled===true:typeof e.message!=="undefined"&&e.message.pull_server_enabled==="Y";this.unloading=false;this.starting=false;this.debug=false;this.connectionAttempt=0;this.connectionType="";this.reconnectTimeout=null;this.restoreWebSocketTimeout=null;this.skipCheckRevision=t.skipCheckRevision===true;this._subscribers={};this.watchTagsQueue={};this.watchUpdateInterval=174e4;this.watchForceUpdateInterval=5e3;if(typeof t.configTimestamp!=="undefined"){this.configTimestamp=t.configTimestamp}else if(typeof e.message!=="undefined"&&e.message.pull_config_timestamp){this.configTimestamp=e.message.pull_config_timestamp}else{this.configTimestamp=0}this.session={mid:null,tag:null,time:null,history:{},messageCount:0};this._connectors={webSocket:null,longPolling:null};Object.defineProperty(this,"connector",{get:function(){return n._connectors[n.connectionType]}});this.isSecure=document.location.href.indexOf("https")===0;this.config=null;this.storage=new R({userId:this.userId,siteId:this.siteId});this.sharedConfig=new C({onWebSocketBlockChanged:this.onWebSocketBlockChanged.bind(this),storage:this.storage});this.channelManager=new _({restClient:this.restClient});this.notificationPopup=null;this.checkInterval=null;this.offlineTimeout=null;this.isManualDisconnect=false};E.prototype.subscribe=function(e){e=e||{};e.type=e.type||f.Server;if(e.type==f.Server||e.type==f.Client){if(typeof this._subscribers[e.type]==="undefined"){this._subscribers[e.type]={}}if(typeof this._subscribers[e.type][e.moduleId]==="undefined"){this._subscribers[e.type][e.moduleId]=[]}this._subscribers[e.type][e.moduleId].push(e.callback);return function(){this._subscribers[e.type][e.moduleId]=this._subscribers[e.type][e.moduleId].filter(function(t){return t!==e.callback})}.bind(this)}else{if(typeof this._subscribers[e.type]==="undefined"){this._subscribers[e.type]=[]}this._subscribers[e.type].push(e.callback);return function(){this._subscribers[e.type]=this._subscribers[e.type].filter(function(t){return t!==e.callback})}.bind(this)}};E.prototype.sendEvent=function(e){e=e||{};if(e.type==f.Server||e.type==f.Client){if(typeof this._subscribers[e.type]==="undefined"){this._subscribers[e.type]={}}if(typeof this._subscribers[e.type][e.moduleId]==="undefined"){this._subscribers[e.type][e.moduleId]=[]}if(this._subscribers[e.type][e.moduleId].length<=0){return true}this._subscribers[e.type][e.moduleId].forEach(function(t){t(e.data)})}else{if(typeof this._subscribers[e.type]==="undefined"){this._subscribers[e.type]=[]}if(this._subscribers[e.type].length<=0){return true}this._subscribers[e.type].forEach(function(t){t(e.data)})}return true};E.prototype.init=function(){this._connectors.webSocket=new P({parent:this,onOpen:this.onWebSocketOpen.bind(this),onMessage:this.parseResponse.bind(this),onDisconnect:this.onWebSocketDisconnect.bind(this),onError:this.onWebSocketError.bind(this)});this._connectors.longPolling=new T({parent:this,onOpen:this.onLongPollingOpen.bind(this),onMessage:this.parseResponse.bind(this),onDisconnect:this.onLongPollingDisconnect.bind(this),onError:this.onLongPollingError.bind(this)});this.connectionType=this.isWebSocketAllowed()?u.WebSocket:u.LongPolling;window.addEventListener("beforeunload",this.onBeforeUnload.bind(this));window.addEventListener("offline",this.onOffline.bind(this));window.addEventListener("online",this.onOnline.bind(this));if(e&&e.addCustomEvent){e.addCustomEvent("BXLinkOpened",this.connect.bind(this))}if(e&&e.desktop){e.desktop.addCustomEvent("BXLoginSuccess",function(){this.restart(1e3,"Desktop login")}.bind(this))}};E.prototype.start=function(t){if(this.starting||this.isConnected()){return}if(!this.userId&&typeof e.message!=="undefined"&&e.message.USER_ID){this.userId=e.message.USER_ID}if(this.siteId==="none"&&typeof e.message!=="undefined"&&e.message.SITE_ID){this.siteId=e.message.SITE_ID}var n=new e.Promise;if(O.isPlainObject(t)){this.config=t}if(!this.enabled){n.reject({ex:{error:"PULL_DISABLED",error_description:"Push & Pull server is disabled"}});return n}var o=this;var i=(new Date).getTime();var s=this.storage.get(c);if(O.isPlainObject(s)&&s.hasOwnProperty("ttl")&&s.ttl>=i){this.session.mid=s.mid}this.starting=true;this.loadConfig().catch(function(e){o.starting=false;o.sendPullStatus(l.Offline);o.stopCheckConfig();console.error(O.getDateForLog()+": Pull: could not read push-server config. ",e);n.reject(e)}).then(function(e){o.setConfig(e);o.init();o.connect();o.updateWatch();o.startCheckConfig();n.resolve(true)});return n};E.prototype.setLastMessageId=function(e){this.session.mid=e};E.prototype.setPublicIds=function(e){return this.channelManager.setPublicIds(e)};E.prototype.sendMessage=function(e,t,n,o,i){return this.sendMessageBatch([{users:e,moduleId:t,command:n,params:o,expiry:i}])};E.prototype.sendMessageBatch=function(e){if(!this.isPublishingEnabled()){console.error("Client publishing is not supported or is disabled");return false}var t=[];var n={};for(var o=0;o<e.length;o++){for(var i=0;i<e[o].users.length;i++){n[e[o].users[i]]=true}}this.channelManager.getPublicIds(Object.keys(n)).then(function(n){e.forEach(function(e){var o={module_id:e.moduleId,command:e.command,params:e.params};var i=S.create({receivers:this.createMessageReceivers(e.users,n),body:JSON.stringify(o),expiry:e.expiry||0});t.push(i)},this);var o=v.create({requests:[{incomingMessages:{messages:t}}]});var i=v.encode(o).finish();return this.connector.send(i)}.bind(this))};E.prototype.createMessageReceivers=function(e,t){var n=[];for(var o=0;o<e.length;o++){var i=e[o];if(!t[i]||!t[i].publicId){throw new Error("Could not determine public id for user "+i)}n.push(k.create({id:this.encodeId(t[i].publicId),signature:this.encodeId(t[i].signature)}))}return n};E.prototype.restart=function(t,n){var o=this;this.disconnect(t,n);this.storage.remove("bx-pull-config");this.config=null;this.loadConfig().catch(function(t){console.error(O.getDateForLog()+": Pull: could not read push-server config",t);o.sendPullStatus(l.Offline);clearTimeout(o.reconnectTimeout);if(t.status==401||t.status==403){o.stopCheckConfig();if(e&&e.onCustomEvent){e.onCustomEvent(window,"onPullError",["AUTHORIZE_ERROR"])}}}).then(function(e){o.setConfig(e);o.connect();o.updateWatch();o.startCheckConfig()})};E.prototype.loadConfig=function(){var t=new e.Promise;if(!this.config){this.config={api:{},channels:{},server:{timeShift:0}};var n=this.storage.get("bx-pull-config");if(this.isConfigActual(n)&&this.checkRevision(n.api.revision_web)){t.resolve(n);return t}else{this.storage.remove("bx-pull-config")}}else if(this.isConfigActual(this.config)&&this.checkRevision(this.config.api.revision_web)){t.resolve(this.config);return t}else{this.config={api:{},channels:{},server:{timeShift:0}}}this.restClient.callBatch({serverTime:["server.time"],configGet:["pull.config.get",{CACHE:"N"}]},function(e){if(!e){t.reject(new Error("Network error while getting new config"));return false}var n=0;if(e.serverTime&&!e.serverTime.error()){n=Math.floor((O.getTimestamp()-new Date(e.serverTime.data()).getTime())/1e3)}if(e.configGet.error()){var o=e.configGet.error();if(o.getError().error=="AUTHORIZE_ERROR"||o.getError().error=="WRONG_AUTH_TYPE"){o.status=403}t.reject(o)}else if(e.configGet){var i=e.configGet.data();i.server.timeShift=n;t.resolve(i)}},false,false,"pull.config");return t};E.prototype.isConfigActual=function(e){if(!O.isPlainObject(e)){return false}if(e.server.config_timestamp<this.configTimestamp){return false}var t=new Date;var n=Object.keys(e.channels).length;if(n===0){return false}for(var o in e.channels){if(!e.channels.hasOwnProperty(o)){continue}var i=e.channels[o];var s=new Date(i.end);if(s<t){return false}}return true};E.prototype.startCheckConfig=function(){if(this.checkInterval){clearInterval(this.checkInterval)}this.checkInterval=setInterval(this.checkConfig.bind(this),r)};E.prototype.stopCheckConfig=function(){if(this.checkInterval){clearInterval(this.checkInterval)}this.checkInterval=null};E.prototype.checkConfig=function(){if(this.isConfigActual(this.config)){if(!this.checkRevision(this.config.api.revision_web)){return false}}else{console.log(O.getDateForLog()+": Stale config detected. Restarting");this.restart(p.CONFIG_EXPIRED,"Config update required")}};E.prototype.setConfig=function(e){for(var t in e){if(e.hasOwnProperty(t)&&this.config.hasOwnProperty(t)){this.config[t]=e[t]}}this.storage.set("bx-pull-config",e)};E.prototype.isWebSocketSupported=function(){return typeof window.WebSocket!=="undefined"};E.prototype.isWebSocketAllowed=function(){if(this.sharedConfig.isWebSocketBlocked()){return false}return this.isWebSocketEnabled()};E.prototype.isWebSocketEnabled=function(){if(!this.isWebSocketSupported()){return false}return this.config.server.websocket_enabled===true};E.prototype.isPublishingSupported=function(){return this.getServerVersion()>3};E.prototype.isPublishingEnabled=function(){if(!this.isPublishingSupported()){return false}return this.config.server.publish_enabled===true};E.prototype.isProtobufSupported=function(){return this.getServerVersion()>3&&!O.browser.IsIe()};E.prototype.disconnect=function(e,t){if(this.connector){this.isManualDisconnect=true;this.connector.disconnect(e,t)}};E.prototype.stop=function(e,t){this.disconnect(e,t);this.stopCheckConfig()};E.prototype.reconnect=function(e,t,n){this.disconnect(e,t);n=n||1;this.scheduleReconnect(n)};E.prototype.restoreWebSocketConnection=function(){if(this.connectionType==u.WebSocket){return true}this._connectors.webSocket.connect()};E.prototype.scheduleReconnect=function(e){if(!this.enabled)return false;if(!e){if(this.connectionAttempt>3&&this.connectionType===u.WebSocket){this.sharedConfig.setWebSocketBlocked(true);this.connectionType=u.LongPolling;this.connectionAttempt=1;e=1}else{e=this.getConnectionAttemptDelay(this.connectionAttempt)}}if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout)}console.log(O.getDateForLog()+": Pull: scheduling reconnection in "+e+" seconds; attempt # "+this.connectionAttempt);this.reconnectTimeout=setTimeout(this.connect.bind(this),e*1e3)};E.prototype.scheduleRestoreWebSocketConnection=function(){console.log(O.getDateForLog()+": Pull: scheduling restoration of websocket connection in "+i+" seconds");var e=this;if(this.restoreWebSocketTimeout){return}this.restoreWebSocketTimeout=setTimeout(function(){e.restoreWebSocketTimeout=0;e.restoreWebSocketConnection()},i*1e3)};E.prototype.connect=function(){if(!this.enabled||this.connector.connected){return false}if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout)}this.sendPullStatus(l.Connecting);this.connectionAttempt++;this.connector.connect()};E.prototype.parseResponse=function(e){var t;var n=this.extractMessages(e);var o=[];if(n.length===0){this.session.mid=null;return}for(var i=0;i<n.length;i++){var s=n[i];this.session.mid=s.mid||null;this.session.tag=s.tag||null;this.session.time=s.time||null;o.push(s.text);if(!this.session.history[s.text.module_id]){this.session.history[s.text.module_id]={}}if(!this.session.history[s.text.module_id][s.text.command]){this.session.history[s.text.module_id][s.text.command]=0}this.session.history[s.text.module_id][s.text.command]++;this.session.messageCount++}this.broadcastMessages(o)};E.prototype.extractMessages=function(e){if(e instanceof ArrayBuffer){return this.extractProtobufMessages(e)}else if(O.isNotEmptyString(e)){return this.extractPlainTextMessages(e)}};E.prototype.extractProtobufMessages=function(e){var t=[];try{var n=m.decode(new Uint8Array(e));for(var o=0;o<n.responses.length;o++){var i=n.responses[o];if(i.command!="outgoingMessages"){continue}var s=n.responses[o].outgoingMessages.messages;for(var r=0;r<s.length;r++){var c=s[r];var a;try{a=JSON.parse(c.body)}catch(e){console.error(O.getDateForLog()+": Pull: Could not parse message body",e);continue}if(!a.extra){a.extra={}}a.extra.sender={type:c.sender.type};if(c.sender.id instanceof Uint8Array){a.extra.sender.id=this.decodeId(c.sender.id)}var u={mid:this.decodeId(c.id),text:a};t.push(u)}}}catch(e){console.error(O.getDateForLog()+": Pull: Could not parse message",e)}return t};E.prototype.extractPlainTextMessages=function(e){var t=[];var n=e.match(/#!NGINXNMS!#(.*?)#!NGINXNME!#/gm);if(n===null){text="\n========= PULL ERROR ===========\n"+"Error type: parseResponse error parsing message\n"+"\n"+"Data string: "+e+"\n"+"================================\n\n";console.warn(text);return t}for(var o=0;o<n.length;o++){n[o]=n[o].substring(12,n[o].length-12);if(n[o].length<=0){continue}try{var i=JSON.parse(n[o])}catch(e){continue}t.push(i)}return t};E.prototype.decodeId=function(e){if(!(e instanceof Uint8Array)){throw new Error("encodedId should be an instance of Uint8Array")}var t="";for(var n=0;n<e.length;n++){var o=e[n].toString(16);if(o.length===1){t+="0"}t+=o}return t};E.prototype.encodeId=function(e){if(!e){return new Uint8Array}var t=[];for(var n=0;n<e.length;n+=2){t.push(parseInt(e.substr(n,2),16))}return new Uint8Array(t)};E.prototype.broadcastMessages=function(t){t.forEach(function(t){var n=t.module_id=t.module_id.toLowerCase();var o=t.command;if(!t.extra){t.extra={}}if(t.extra.server_time_unix){t.extra.server_time_ago=(O.getTimestamp()-t.extra.server_time_unix*1e3)/1e3-(this.config.server.timeShift?this.config.server.timeShift:0);t.extra.server_time_ago=t.extra.server_time_ago>0?t.extra.server_time_ago:0}this.logMessage(t);try{if(t.extra.sender&&t.extra.sender.type===h.Client){if(typeof e.onCustomEvent!=="undefined"){e.onCustomEvent(window,"onPullClientEvent-"+n,[o,t.params,t.extra],true);e.onCustomEvent(window,"onPullClientEvent",[n,o,t.params,t.extra],true)}this.sendEvent({type:f.Client,moduleId:n,data:{command:o,params:O.clone(t.params),extra:O.clone(t.extra)}})}else if(n==="pull"){this.handleInternalPullEvent(o,t)}else if(n=="online"){if(t.extra.server_time_ago<240){if(typeof e.onCustomEvent!=="undefined"){e.onCustomEvent(window,"onPullOnlineEvent",[o,t.params,t.extra],true)}this.sendEvent({type:f.Online,data:{command:o,params:O.clone(t.params),extra:O.clone(t.extra)}})}}else{if(typeof e.onCustomEvent!=="undefined"){e.onCustomEvent(window,"onPullEvent-"+n,[o,t.params,t.extra],true);e.onCustomEvent(window,"onPullEvent",[n,o,t.params,t.extra],true)}this.sendEvent({type:f.Server,moduleId:n,data:{command:o,params:O.clone(t.params),extra:O.clone(t.extra)}})}}catch(n){if(typeof console=="object"){console.warn("\n========= PULL ERROR ===========\n"+"Error type: broadcastMessages execute error\n"+"Error event: ",n,"\n"+"Message: ",t,"\n"+"================================\n");if(typeof e.debug!=="undefined"){e.debug(n)}}}if(t.extra&&t.extra.revision_web){this.checkRevision(t.extra.revision_web)}},this)};E.prototype.logMessage=function(e){if(!this.debug){return}if(e.extra.sender&&e.extra.sender.type===h.Client){console.info("onPullClientEvent-"+e.module_id,e.command,e.params,e.extra)}else if(e.moduleId=="online"){console.info("onPullOnlineEvent",e.command,e.params,e.extra)}else{console.info("onPullEvent",e.module_id,e.command,e.params,e.extra)}};E.prototype.onLongPollingOpen=function(){this.unloading=false;this.starting=false;this.connectionAttempt=0;this.isManualDisconnect=false;this.sendPullStatus(l.Online);if(this.offlineTimeout){clearTimeout(this.offlineTimeout);this.offlineTimeout=null}console.log(O.getDateForLog()+": Pull: Long polling connection with push-server opened");if(this.isWebSocketEnabled()){this.scheduleRestoreWebSocketConnection()}};E.prototype.onWebSocketBlockChanged=function(e){var t=e.isWebSocketBlocked;if(t&&this.connectionType===u.WebSocket&&!this.isConnected()){clearTimeout(this.reconnectTimeout);this.connectionAttempt=0;this.connectionType=u.LongPolling;this.scheduleReconnect(1)}else if(!t&&this.connectionType===u.LongPolling){clearTimeout(this.reconnectTimeout);clearTimeout(this.restoreWebSocketTimeout);this.connectionAttempt=0;this.connectionType=u.WebSocket;this.scheduleReconnect(1)}};E.prototype.onWebSocketOpen=function(){this.unloading=false;this.starting=false;this.connectionAttempt=0;this.isManualDisconnect=false;this.sendPullStatus(l.Online);this.sharedConfig.setWebSocketBlocked(false);if(this.connectionType==u.LongPolling){this.connectionType=u.WebSocket;this._connectors.longPolling.disconnect()}if(this.offlineTimeout){clearTimeout(this.offlineTimeout);this.offlineTimeout=null}console.log(O.getDateForLog()+": Pull: Websocket connection with push-server opened")};E.prototype.onWebSocketDisconnect=function(e){if(this.connectionType===u.WebSocket){if(e.code!=p.CONFIG_EXPIRED&&e.code!=p.CHANNEL_EXPIRED&&e.code!=p.CONFIG_REPLACED){this.sendPullStatus(l.Offline)}else{this.offlineTimeout=setTimeout(function(){this.sendPullStatus(l.Offline)}.bind(this),5e3)}}if(!e){e={}}console.log(O.getDateForLog()+": Pull: Websocket connection with push-server closed. Code: "+e.code+", reason: "+e.reason);if(!this.isManualDisconnect){this.scheduleReconnect()}this.isManualDisconnect=false};E.prototype.onWebSocketError=function(e){this.starting=false;if(this.connectionType===u.WebSocket){this.sendPullStatus(l.Offline)}console.error(O.getDateForLog()+": Pull: WebSocket connection error",e);this.scheduleReconnect()};E.prototype.onLongPollingDisconnect=function(e){if(this.connectionType===u.LongPolling){if(e.code!=p.CONFIG_EXPIRED&&e.code!=p.CHANNEL_EXPIRED&&e.code!=p.CONFIG_REPLACED){this.sendPullStatus(l.Offline)}else{this.offlineTimeout=setTimeout(function(){this.sendPullStatus(l.Offline)}.bind(this),5500)}}if(!e){e={}}console.log(O.getDateForLog()+": Pull: Long polling connection with push-server closed. Code: "+e.code+", reason: "+e.reason);if(!this.isManualDisconnect){this.scheduleReconnect()}this.isManualDisconnect=false};E.prototype.onLongPollingError=function(e){this.starting=false;if(this.connectionType===u.LongPolling){this.sendPullStatus(l.Offline)}console.error(O.getDateForLog()+": Pull: Long polling connection error",e);this.scheduleReconnect()};E.prototype.isConnected=function(){return this.connector?this.connector.connected:false};E.prototype.onBeforeUnload=function(){this.unloading=true;var e=O.clone(this.session);e.ttl=(new Date).getTime()+a*1e3;this.storage.set(c,JSON.stringify(e),a);this.reconnect(p.NORMAL_CLOSURE,"onbeforeunload",15)};E.prototype.onOffline=function(){this.disconnect("1000","offline")};E.prototype.onOnline=function(){this.connect()};E.prototype.handleInternalPullEvent=function(e,t){switch(e.toUpperCase()){case d.CHANNEL_EXPIRE:{if(t.params.action=="reconnect"){this.config.channels[t.params.channel.type]=t.params.new_channel;console.info("Pull: new config for "+t.params.channel.type+" channel set:\n",this.config.channels[t.params.channel.type]);this.reconnect(p.CONFIG_REPLACED,"config was replaced")}else{this.restart(p.CHANNEL_EXPIRED,"channel expired")}break}case d.CONFIG_EXPIRE:{this.restart(p.CONFIG_EXPIRED,"config expired");break}case d.SERVER_RESTART:{this.reconnect(p.SERVER_RESTARTED,"server was restarted",15);break}default:}};E.prototype.checkRevision=function(t){if(this.skipCheckRevision){return true}t=parseInt(t);if(t>0&&t!=n){this.enabled=false;if(typeof e.message!=="undefined"){this.showNotification(e.message("PULL_OLD_REVISION"))}this.disconnect(p.NORMAL_CLOSURE,"check_revision");if(typeof e.onCustomEvent!=="undefined"){e.onCustomEvent(window,"onPullRevisionUp",[t,n])}this.sendEvent({type:f.Revision,data:{server:t,client:n}});console.log(O.getDateForLog()+": Pull revision changed from "+n+" to "+t+". Reload required");return false}return true};E.prototype.showNotification=function(t){var n=this;if(this.notificationPopup||typeof e.PopupWindow==="undefined")return;this.notificationPopup=new e.PopupWindow("bx-notifier-popup-confirm",null,{zIndex:200,autoHide:false,closeByEsc:false,overlay:true,content:e.create("div",{props:{className:"bx-messenger-confirm"},html:t}),buttons:[new e.PopupWindowButton({text:e.message("JS_CORE_WINDOW_CLOSE"),className:"popup-window-button-decline",events:{click:function(e){n.notificationPopup.close()}}})],events:{onPopupClose:function(){this.destroy()},onPopupDestroy:function(){n.notificationPopup=null}}});this.notificationPopup.show()};E.prototype.getRevision=function(){return this.config.api.revision_web};E.prototype.getServerVersion=function(){return this.config.server.version};E.prototype.getConfig=function(){return this.config};E.prototype.getDebugInfo=function(){if(!console||!console.info||!JSON||!JSON.stringify)return false;var e;if(this.config&&this.config.channels&&this.config.channels.private){e="ChannelID: "+this.config.channels.private.id+"\n"+"ChannelDie: "+this.config.channels.private.end+"\n"+"ChannelDieShared: "+this.config.channels.shared.end}else{e="Config error: config is not loaded"}var t=JSON.stringify(this.watchTagsQueue);var n="\n========= PULL DEBUG ===========\n"+"UserId: "+this.userId+" "+(this.userId>0?"":"(guest)")+"\n"+"Browser online: "+(navigator.onLine?"Y":"N")+"\n"+"Connect: "+(this.isConnected()?"Y":"N")+"\n"+"WebSocket support: "+(this.isWebSocketSupported()?"Y":"N")+"\n"+"WebSocket connect: "+(this._connectors.webSocket&&this._connectors.webSocket.connected?"Y":"N")+"\n"+"WebSocket mode: "+(this._connectors.webSocket&&this._connectors.webSocket.socket?this._connectors.webSocket.socket.url.search("binaryMode=true")!=-1?"protobuf":"text":"-")+"\n"+"Try connect: "+(this.reconnectTimeout?"Y":"N")+"\n"+"Try number: "+this.connectionAttempt+"\n"+"\n"+"Path: "+(this.connector?this.connector.path:"-")+"\n"+e+"\n"+"\n"+"Last message: "+(this.session.mid>0?this.session.mid:"-")+"\n"+"Session history: "+JSON.stringify(this.session.history)+"\n"+"Watch tags: "+(t=="{}"?"-":t)+"\n"+"================================\n";return console.info(n)};E.prototype.capturePullEvent=function(e){if(e===undefined){e=true}this.debug=e};E.prototype.getConnectionPath=function(e){var t;switch(e){case u.WebSocket:t=this.isSecure?this.config.server.websocket_secure:this.config.server.websocket;break;case u.LongPolling:t=this.isSecure?this.config.server.long_pooling_secure:this.config.server.long_polling;break;default:throw new Error("Unknown connection type "+e)}if(!O.isNotEmptyString(t)){return false}var o=[];["private","shared"].forEach(function(e){if(typeof this.config.channels[e]!=="undefined"){o.push(this.config.channels[e].id)}},this);if(o.length===0){return false}var i={CHANNEL_ID:o.join("/")};if(this.isProtobufSupported()){i.binaryMode="true"}if(this.session.mid){i.mid=this.session.mid}if(this.session.tag){i.tag=this.session.tag}if(this.session.time){i.time=this.session.time}i.revision=n;return t+"?"+O.buildQueryString(i)};E.prototype.getPublicationPath=function(){var e=this.isSecure?this.config.server.publish_secure:this.config.server.publish;if(!e){return""}var t=[];for(var n in this.config.channels){if(!this.config.channels.hasOwnProperty(n)){continue}t.push(this.config.channels[n].id)}var o={CHANNEL_ID:t.join("/")};return e+"?"+O.buildQueryString(o)};E.prototype.getConnectionAttemptDelay=function(e){var t;if(e<1){t=.5}else if(e<3){t=15}else if(e<5){t=45}else if(e<10){t=600}else{t=3600}return t+t*Math.random()*.2};E.prototype.sendPullStatus=function(t){if(this.unloading){return}if(typeof e.onCustomEvent!=="undefined"){e.onCustomEvent(window,"onPullStatus",[t])}this.sendEvent({type:f.Status,data:{status:t}})};E.prototype.extendWatch=function(e,t){if(!e||this.watchTagsQueue[e]){return false}this.watchTagsQueue[e]=true;if(t){this.updateWatch(t)}};E.prototype.updateWatch=function(e){clearTimeout(this.watchUpdateTimeout);this.watchUpdateTimeout=setTimeout(function(){var e=Object.keys(this.watchTagsQueue);if(e.length>0){this.restClient.callMethod("pull.watch.extend",{tags:e}).then(function(e){var t=e.data();for(var n in t){if(t.hasOwnProperty(n)&&!t[n]){this.clearWatch(n)}}this.updateWatch()}.bind(this)).catch(function(){this.updateWatch()}.bind(this))}else{this.updateWatch()}}.bind(this),e?this.watchForceUpdateInterval:this.watchUpdateInterval)};E.prototype.clearWatch=function(e){delete this.watchTagsQueue[e]};E.prototype.setPrivateVar=function(){};E.prototype.returnPrivateVar=function(){};E.prototype.expireConfig=function(){};E.prototype.updateChannelID=function(){};E.prototype.tryConnect=function(){};E.prototype.tryConnectDelay=function(){};E.prototype.tryConnectSet=function(){};E.prototype.updateState=function(){};E.prototype.setUpdateStateStepCount=function(){};E.prototype.supportWebSocket=function(){return this.isWebSocketSupported()};E.prototype.isWebSoketConnected=function(){return this.isConnected()&&this.connectionType==u.WebSocket};E.prototype.getPullServerStatus=function(){return this.isConnected()};E.prototype.closeConfirm=function(){if(this.notificationPopup){this.notificationPopup.destroy()}};var C=function(e){e=e||{};this.storage=e.storage||new R;this.ttl=24*60*60;this.lsKeys={websocketBlocked:"bx-pull-websocket-blocked"};this.callbacks={onWebSocketBlockChanged:O.isFunction(e.onWebSocketBlockChanged)?e.onWebSocketBlockChanged:function(){}};window.addEventListener("storage",this.onLocalStorageSet.bind(this))};C.prototype.onLocalStorageSet=function(e){if(this.storage.compareKey(e.key,this.lsKeys.websocketBlocked)&&e.newValue!=e.oldValue){this.callbacks.onWebSocketBlockChanged({isWebSocketBlocked:this.isWebSocketBlocked()})}};C.prototype.isWebSocketBlocked=function(){return this.storage.get(this.lsKeys.websocketBlocked,0)>O.getTimestamp()};C.prototype.setWebSocketBlocked=function(e){this.storage.set(this.lsKeys.websocketBlocked,e?O.getTimestamp()+this.ttl:0)};var w=function(e,t){var n=function(){};n.prototype=t.prototype;e.prototype=new n;e.prototype.constructor=e;e.superclass=t.prototype;if(t.prototype.constructor==Object.prototype.constructor){t.prototype.constructor=t}};var I=function(e){this.parent=e.parent;this.callbacks={onOpen:O.isFunction(e.onOpen)?e.onOpen:function(){},onDisconnect:O.isFunction(e.onDisconnect)?e.onDisconnect:function(){},onError:O.isFunction(e.onError)?e.onError:function(){},onMessage:O.isFunction(e.onMessage)?e.onMessage:function(){}};this._connected=false;this.connectionType="";this.disconnectCode="";this.disconnectReason="";Object.defineProperty(this,"connected",{get:function(){return this._connected},set:function(e){if(e==this._connected)return;this._connected=e;if(this._connected){this.callbacks.onOpen()}else{this.callbacks.onDisconnect({code:this.disconnectCode,reason:this.disconnectReason})}}});Object.defineProperty(this,"path",{get:function(){return this.parent.getConnectionPath(this.connectionType)}})};var P=function(e){P.superclass.constructor.apply(this,arguments);this.connectionType=u.WebSocket;this.socket=null;this.onSocketOpenHandler=this.onSocketOpen.bind(this);this.onSocketCloseHandler=this.onSocketClose.bind(this);this.onSocketErrorHandler=this.onSocketError.bind(this);this.onSocketMessageHandler=this.onSocketMessage.bind(this)};w(P,I);P.prototype.connect=function(){if(this.socket){if(this.socket.readyState===1){return true}else{this.socket.removeEventListener("open",this.onSocketOpenHandler);this.socket.removeEventListener("close",this.onSocketCloseHandler);this.socket.removeEventListener("error",this.onSocketErrorHandler);this.socket.removeEventListener("message",this.onSocketMessageHandler);this.socket.close();this.socket=null}}this.createSocket()};P.prototype.disconnect=function(e,t){if(this.socket!==null){this.socket.removeEventListener("open",this.onSocketOpenHandler);this.socket.removeEventListener("close",this.onSocketCloseHandler);this.socket.removeEventListener("error",this.onSocketErrorHandler);this.socket.removeEventListener("message",this.onSocketMessageHandler);this.socket.close(e,t)}this.socket=null;this.disconnectCode=e;this.disconnectReason=t;this.connected=false};P.prototype.createSocket=function(){if(this.socket){throw new Error("Socket already exists")}if(!this.path){throw new Error("Websocket connection path is not defined")}this.socket=new WebSocket(this.path);this.socket.binaryType="arraybuffer";this.socket.addEventListener("open",this.onSocketOpenHandler);this.socket.addEventListener("close",this.onSocketCloseHandler);this.socket.addEventListener("error",this.onSocketErrorHandler);this.socket.addEventListener("message",this.onSocketMessageHandler)};P.prototype.send=function(e){if(!this.socket||this.socket.readyState!==1){console.error(O.getDateForLog()+": Pull: WebSocket is not connected");return false}this.socket.send(e)};P.prototype.onSocketOpen=function(){this.connected=true};P.prototype.onSocketClose=function(e){this.socket=null;this.disconnectCode=e.code;this.disconnectReason=e.reason;this.connected=false};P.prototype.onSocketError=function(e){this.callbacks.onError(e)};P.prototype.onSocketMessage=function(e){this.callbacks.onMessage(e.data)};P.prototype.destroy=function(){if(this.socket){this.socket.close();this.socket=null}};var T=function(e){T.superclass.constructor.apply(this,arguments);this.active=false;this.connectionType=u.LongPolling;this.requestTimeout=null;this.failureTimeout=null;this.xhr=this.createXhr();this.requestAborted=false};w(T,I);T.prototype.createXhr=function(){var e=new XMLHttpRequest;if(this.parent.isProtobufSupported()){e.responseType="arraybuffer"}e.addEventListener("readystatechange",this.onXhrReadyStateChange.bind(this));return e};T.prototype.connect=function(){this.active=true;this.performRequest()};T.prototype.disconnect=function(e,t){this.active=false;if(this.failureTimeout){clearTimeout(this.failureTimeout);this.failureTimeout=null}if(this.requestTimeout){clearTimeout(this.requestTimeout);this.requestTimeout=null}if(this.xhr){this.requestAborted=true;this.xhr.abort()}this.disconnectCode=e;this.disconnectReason=t;this.connected=false};T.prototype.performRequest=function(){var e=this;if(!this.active)return;if(!this.path){throw new Error("Long polling connection path is not defined")}if(this.xhr.readyState!==0&&this.xhr.readyState!==4){return}clearTimeout(this.failureTimeout);clearTimeout(this.requestTimeout);this.failureTimeout=setTimeout(function(){e.connected=true},5e3);this.requestTimeout=setTimeout(this.onRequestTimeout.bind(this),o*1e3);this.xhr.open("GET",this.path);this.xhr.send()};T.prototype.onRequestTimeout=function(){this.requestAborted=true;this.xhr.abort();this.performRequest()};T.prototype.onXhrReadyStateChange=function(e){if(this.xhr.readyState===4){if(!this.requestAborted||this.xhr.status==200){this.onResponse(this.xhr.response)}this.requestAborted=false}};T.prototype.send=function(e){var t=this.parent.getPublicationPath();if(!t){console.error(O.getDateForLog()+": Pull: publication path is empty");return false}var n=new XMLHttpRequest;n.open("POST",t);n.send(e)};T.prototype.onResponse=function(e){if(this.failureTimeout){clearTimeout(this.failureTimeout);this.failureTimeout=0}if(this.requestTimeout){clearTimeout(this.requestTimeout);this.requestTimeout=0}if(this.xhr.status==200){this.connected=true;if(O.isNotEmptyString(e)||e instanceof ArrayBuffer){this.callbacks.onMessage(e)}else{this.parent.session.mid=null}this.performRequest()}else if(this.xhr.status==304){this.connected=true;if(this.xhr.getResponseHeader("Expires")==="Thu, 01 Jan 1973 11:11:01 GMT"){var t=this.xhr.getResponseHeader("Last-Message-Id");if(O.isNotEmptyString(t)){this.parent.setLastMessageId(t)}}this.performRequest()}else{this.callbacks.onError("Could not connect to the server");this.connected=false}};var _=function(t){this.publicIds={};this.restClient=typeof t.restClient!=="undefined"?t.restClient:e.rest};_.prototype.getPublicIds=function(t){var n=new e.Promise;var o={};var i=new Date;var s=[];for(var r=0;r<t.length;r++){var c=t[r];if(this.publicIds[c]&&this.publicIds[c]["end"]>i){o[c]=this.publicIds[c]}else{s.push(c)}}if(s.length===0){n.resolve(o);return n}this.restClient.callMethod("pull.channel.public.list",{users:s}).then(function(e){var t=e.data();this.setPublicIds(O.objectValues(t));s.forEach(function(t){e[t]=this.publicIds[t]},this);n.resolve(e)}.bind(this));return n};_.prototype.setPublicIds=function(e){for(var t=0;t<e.length;t++){var n=e[t];var o=n.user_id;this.publicIds[o]={userId:o,publicId:n.public_id,signature:n.signature,start:new Date(n.start),end:new Date(n.end)}}};var R=function(t){t=t||{};this.userId=t.userId?t.userId:typeof e.message!=="undefined"&&e.message.USER_ID?e.message.USER_ID:0;this.siteId=t.siteId?t.siteId:typeof e.message!=="undefined"&&e.message.SITE_ID?e.message.SITE_ID:"none"};R.prototype.set=function(e,t){if(typeof window.localStorage==="undefined"){return false}if(typeof t!="string"){if(t){t=JSON.stringify(t)}}return window.localStorage.setItem(this.getKey(e),t)};R.prototype.get=function(e,t){if(typeof window.localStorage==="undefined"){return t||null}var n=window.localStorage.getItem(this.getKey(e));if(n===null){return t||null}return JSON.parse(n)};R.prototype.remove=function(e){if(typeof window.localStorage==="undefined"){return false}return window.localStorage.removeItem(this.getKey(e))};R.prototype.getKey=function(e){return"bx-pull-"+this.userId+"-"+this.siteId+"-"+e};R.prototype.compareKey=function(e,t){return e===this.getKey(t)};var O={browser:{IsChrome:function(){return navigator.userAgent.toLowerCase().indexOf("chrome")!=-1},IsFirefox:function(){return navigator.userAgent.toLowerCase().indexOf("firefox")!=-1},IsIe:function(){return navigator.userAgent.match(/(Trident\/|MSIE\/)/)!==null}},getTimestamp:function(){return(new Date).getTime()},errorsToString:function(e){if(!this.isArray(e)){return""}else{return e.reduce(function(e,t){if(e!=""){e+="; "}return e+t.code+": "+t.message},"")}},isString:function(e){return e===""?true:e?typeof e=="string"||e instanceof String:false},isArray:function(e){return e&&Object.prototype.toString.call(e)=="[object Array]"},isFunction:function(e){return e===null?false:typeof e=="function"||e instanceof Function},isDomNode:function(e){return e&&typeof e=="object"&&"nodeType"in e},isDate:function(e){return e&&Object.prototype.toString.call(e)=="[object Date]"},isPlainObject:function(e){if(!e||typeof e!=="object"||e.nodeType){return false}var t=Object.prototype.hasOwnProperty;try{if(e.constructor&&!t.call(e,"constructor")&&!t.call(e.constructor.prototype,"isPrototypeOf")){return false}}catch(e){return false}var n;for(n in e){}return typeof n==="undefined"||t.call(e,n)},isNotEmptyString:function(e){return this.isString(e)?e.length>0:false},buildQueryString:function(e){var t="";for(var n in e){if(!e.hasOwnProperty(n)){continue}var o=e[n];if(O.isArray(o)){o.forEach(function(e,o){t+=encodeURIComponent(n+"["+o+"]")+"="+encodeURIComponent(e)+"&"})}else{t+=encodeURIComponent(n)+"="+encodeURIComponent(o)+"&"}}if(t.length>0){t=t.substr(0,t.length-1)}return t},objectValues:function e(t){var n=[];for(var o in t){if(t.hasOwnProperty(o)&&t.propertyIsEnumerable(o)){n.push(t[o])}}return n},clone:function(e,t){var n,o,i;if(t!==false)t=true;if(e===null)return null;if(this.isDomNode(e)){n=e.cloneNode(t)}else if(typeof e=="object"){if(this.isArray(e)){n=[];for(o=0,i=e.length;o<i;o++){if(typeof e[o]=="object"&&t)n[o]=this.clone(e[o],t);else n[o]=e[o]}}else{n={};if(e.constructor){if(this.isDate(e))n=new Date(e);else n=new e.constructor}for(o in e){if(!e.hasOwnProperty(o)){continue}if(typeof e[o]=="object"&&t)n[o]=this.clone(e[o],t);else n[o]=e[o]}}}else{n=e}return n},getDateForLog:function(){var e=new Date;return e.getFullYear()+"-"+O.lpad(e.getMonth(),2,"0")+"-"+O.lpad(e.getDate(),2,"0")+" "+O.lpad(e.getHours(),2,"0")+":"+O.lpad(e.getMinutes(),2,"0")},lpad:function(e,t,n){e=e.toString();n=n||" ";if(e.length>t){return e}var o="";for(var i=0;i<t-e.length;i++){o+=n}return o+e}};if(typeof e.namespace!=="undefined"&&typeof e.PULL==="undefined"){e.PULL=new E}e.PullClient=E;e.PullClient.PullStatus=l;e.PullClient.SubscriptionType=f;e.PullClient.CloseReasons=p})();
//# sourceMappingURL=pull.client.map.js