centrifuge
Advanced tools
Comparing version 1.0.0 to 1.1.0
{ | ||
"name": "centrifuge", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"ignore": [ | ||
@@ -18,3 +18,4 @@ "node_modules", | ||
"sockjs", | ||
"websocket" | ||
"websocket", | ||
"centrifugo" | ||
], | ||
@@ -21,0 +22,0 @@ "license": "MIT", |
@@ -601,2 +601,6 @@ ;(function () { | ||
function errorExists(data) { | ||
return "error" in data && data.error !== null && data.error !== ""; | ||
} | ||
function Centrifuge(options) { | ||
@@ -611,2 +615,3 @@ this._sockjs = false; | ||
this._subscriptions = {}; | ||
this._lastMessageID = {}; | ||
this._messages = []; | ||
@@ -942,2 +947,9 @@ this._isBatching = false; | ||
if (!isString(self._config.user)) { | ||
self._debug("user expected to be string"); | ||
} | ||
if (!isString(self._config.info)) { | ||
self._debug("info expected to be string"); | ||
} | ||
var centrifugeMessage = { | ||
@@ -954,2 +966,8 @@ 'method': 'connect', | ||
centrifugeMessage["params"]["token"] = self._config.token; | ||
if (!isString(self._config.timestamp)) { | ||
self._debug("timestamp expected to be string"); | ||
} | ||
if (!isString(self._config.token)) { | ||
self._debug("token expected to be string"); | ||
} | ||
} | ||
@@ -1019,3 +1037,3 @@ self.send(centrifugeMessage); | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
if (!message.body) { | ||
@@ -1050,3 +1068,3 @@ return; | ||
centrifugeProto._disconnectResponse = function (message) { | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
this.disconnect(); | ||
@@ -1060,3 +1078,3 @@ } else { | ||
centrifugeProto._subscribeResponse = function (message) { | ||
if (message.error !== null) { | ||
if (errorExists(message)) { | ||
this.trigger('error', [message]); | ||
@@ -1073,5 +1091,15 @@ } | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('subscribe:success', [body]); | ||
subscription.trigger('ready', [body]); | ||
var messages = body["messages"]; | ||
if (messages && messages.length > 0) { | ||
for (var i in messages.reverse()) { | ||
this._messageResponse({body: messages[i]}); | ||
} | ||
} else { | ||
if ("last" in body) { | ||
this._lastMessageID[channel] = body["last"]; | ||
} | ||
} | ||
} else { | ||
@@ -1090,5 +1118,5 @@ subscription.trigger('subscribe:error', [message.error]); | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('unsubscribe', [body]); | ||
this._centrifuge._removeSubscription(channel); | ||
this._removeSubscription(channel); | ||
} | ||
@@ -1104,3 +1132,3 @@ }; | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('publish:success', [body]); | ||
@@ -1120,3 +1148,3 @@ } else { | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('presence', [body]); | ||
@@ -1137,3 +1165,3 @@ subscription.trigger('presence:success', [body]); | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('history', [body]); | ||
@@ -1174,2 +1202,4 @@ subscription.trigger('history:success', [body]); | ||
} | ||
// keep last uid received from channel. | ||
this._lastMessageID[channel] = body["uid"]; | ||
subscription.trigger('message', [body]); | ||
@@ -1277,2 +1307,17 @@ }; | ||
centrifugeProto._recover = function(channel) { | ||
return channel in this._lastMessageID; | ||
}; | ||
centrifugeProto._getLastID = function(channel) { | ||
var lastUID = this._lastMessageID[channel]; | ||
if (lastUID) { | ||
this._debug("last uid found and sent for channel", channel); | ||
return lastUID; | ||
} else { | ||
this._debug("no last uid found for channel", channel); | ||
return ""; | ||
} | ||
}; | ||
/* PUBLIC API */ | ||
@@ -1406,2 +1451,7 @@ | ||
}; | ||
var recover = self._recover(channel); | ||
if (recover === true) { | ||
centrifugeMessage["params"]["recover"] = true; | ||
centrifugeMessage["params"]["last"] = self._getLastID(channel); | ||
} | ||
self.send(centrifugeMessage); | ||
@@ -1600,2 +1650,7 @@ } else { | ||
} else { | ||
var recover = this._centrifuge._recover(this.channel); | ||
if (recover === true) { | ||
centrifugeMessage["params"]["recover"] = true; | ||
centrifugeMessage["params"]["last"] = this._centrifuge._getLastID(this.channel); | ||
} | ||
this._centrifuge.send(centrifugeMessage); | ||
@@ -1602,0 +1657,0 @@ } |
@@ -1,1 +0,1 @@ | ||
(function(){"use strict";function e(e,t){return e.prototype=Object.create(t.prototype),e.prototype.constructor=e,t.prototype}function t(){}function n(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}function i(e){return function(){return this[e].apply(this,arguments)}}function s(e,t){for(var n=t||{},i=2;i<arguments.length;++i){var o=arguments[i];if(void 0!==o&&null!==o)for(var c in o){var u=r(o,c),h=r(n,c);if(u!==t&&void 0!==u)if(e&&"object"==typeof u&&null!==u)if(u instanceof Array)n[c]=s(e,h instanceof Array?h:[],u);else{var a="object"!=typeof h||h instanceof Array?{}:h;n[c]=s(e,a,u)}else n[c]=u}}return n}function r(e,t){try{return e[t]}catch(n){return void 0}}function o(e,t){return-1!==e.indexOf(t,e.length-t.length)}function c(e,t){return 0===e.lastIndexOf(t,0)}function u(e){return"/"==e.substring(e.length-1)&&(e=e.substring(0,e.length-1)),e}function h(e){return void 0===e||null===e?!1:"string"==typeof e||e instanceof String}function a(e){return void 0===e||null===e?!1:"function"==typeof e}function f(e,t){if(window.console){var n=window.console[e];a(n)&&n.apply(window.console,t)}}function l(e){this._sockjs=!1,this._sockjsVersion=null,this._status="disconnected",this._reconnect=!0,this._transport=null,this._messageId=0,this._clientId=null,this._subscriptions={},this._messages=[],this._isBatching=!1,this._isAuthBatching=!1,this._authChannels={},this._refreshTimeout=null,this._retry=null,this._config={retry:1e3,maxRetry:1e4,info:"",debug:!1,insecure:!1,server:null,privateChannelPrefix:"$",protocols_whitelist:["websocket","xdr-streaming","xhr-streaming","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],transports:["websocket","xdr-streaming","xhr-streaming","eventsource","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],refreshEndpoint:"/centrifuge/refresh",refreshHeaders:{},refreshParams:{},refreshTransport:"ajax",authEndpoint:"/centrifuge/auth",authHeaders:{},authParams:{},authTransport:"ajax"},e&&this.configure(e)}function g(e,t){this._centrifuge=e,this.channel=t}Object.create||(Object.create=function(){function e(){}return function(t){if(1!=arguments.length)throw new Error("Object.create implementation only accepts one parameter.");return e.prototype=t,new e}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(e){if(null==this)throw new TypeError;var t,n,i=Object(this),s=i.length>>>0;if(0===s)return-1;if(t=0,arguments.length>1&&(t=Number(arguments[1]),t!=t?t=0:0!=t&&1/0!=t&&t!=-1/0&&(t=(t>0||-1)*Math.floor(Math.abs(t)))),t>=s)return-1;for(n=t>=0?t:Math.max(s-Math.abs(t),0);s>n;n++)if(n in i&&i[n]===e)return n;return-1});var d=t.prototype;d.getListeners=function(e){var t,n,i=this._getEvents();if("object"==typeof e){t={};for(n in i)i.hasOwnProperty(n)&&e.test(n)&&(t[n]=i[n])}else t=i[e]||(i[e]=[]);return t},d.flattenListeners=function(e){var t,n=[];for(t=0;t<e.length;t+=1)n.push(e[t].listener);return n},d.getListenersAsObject=function(e){var t,n=this.getListeners(e);return n instanceof Array&&(t={},t[e]=n),t||n},d.addListener=function(e,t){var i,s=this.getListenersAsObject(e),r="object"==typeof t;for(i in s)s.hasOwnProperty(i)&&-1===n(s[i],t)&&s[i].push(r?t:{listener:t,once:!1});return this},d.on=i("addListener"),d.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},d.once=i("addOnceListener"),d.defineEvent=function(e){return this.getListeners(e),this},d.defineEvents=function(e){for(var t=0;t<e.length;t+=1)this.defineEvent(e[t]);return this},d.removeListener=function(e,t){var i,s,r=this.getListenersAsObject(e);for(s in r)r.hasOwnProperty(s)&&(i=n(r[s],t),-1!==i&&r[s].splice(i,1));return this},d.off=i("removeListener"),d.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},d.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},d.manipulateListeners=function(e,t,n){var i,s,r=e?this.removeListener:this.addListener,o=e?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(i=n.length;i--;)r.call(this,t,n[i]);else for(i in t)t.hasOwnProperty(i)&&(s=t[i])&&("function"==typeof s?r.call(this,i,s):o.call(this,i,s));return this},d.removeEvent=function(e){var t,n=typeof e,i=this._getEvents();if("string"===n)delete i[e];else if("object"===n)for(t in i)i.hasOwnProperty(t)&&e.test(t)&&delete i[t];else delete this._events;return this},d.emitEvent=function(e,t){var n,i,s,r,o=this.getListenersAsObject(e);for(s in o)if(o.hasOwnProperty(s))for(i=o[s].length;i--;)n=o[s][i],n.once===!0&&this.removeListener(e,n.listener),r=n.listener.apply(this,t||[]),r===this._getOnceReturnValue()&&this.removeListener(e,n.listener);return this},d.trigger=i("emitEvent"),d.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},d.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},d._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},d._getEvents=function(){return this._events||(this._events={})},e(l,t),l._authCallbacks={},l._nextAuthCallbackID=1;var _=l.prototype;_._jsonp=function(e,t,n,i,s){n.length>0&&this._log("Only AJAX request allows to send custom headers, it's not possible with JSONP."),self._debug("sending JSONP request to",e);var r=l._nextAuthCallbackID.toString();l._nextAuthCallbackID++;var o=window.document,c=o.createElement("script");l._authCallbacks[r]=function(e){s(!1,e),delete l[r]};var u="";for(var h in t)u.length>0&&(u+="&"),u+=encodeURIComponent(h)+"="+encodeURIComponent(t[h]);var a="Centrifuge._authCallbacks['"+r+"']";c.src=this._config.authEndpoint+"?callback="+encodeURIComponent(a)+"&data="+encodeURIComponent(JSON.stringify(i))+"&"+u;var f=o.getElementsByTagName("head")[0]||o.documentElement;f.insertBefore(c,f.firstChild)},_._ajax=function(e,t,n,i,s){var r=this;r._debug("sending AJAX request to",e);var o=window.XMLHttpRequest?new window.XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c="";for(var u in t)c.length>0&&(c+="&"),c+=encodeURIComponent(u)+"="+encodeURIComponent(t[u]);c.length>0&&(c="?"+c),o.open("POST",e+c,!0),o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.setRequestHeader("Content-Type","application/json");for(var h in n)o.setRequestHeader(h,n[h]);return o.onreadystatechange=function(){if(4===o.readyState)if(200===o.status){var e,t=!1;try{e=JSON.parse(o.responseText),t=!0}catch(n){s(!0,"JSON returned from webapp was invalid, yet status code was 200. Data was: "+o.responseText)}t&&s(!1,e)}else r._log("Couldn't get auth info from your webapp",o.status),s(!0,o.status)},setTimeout(function(){o.send(JSON.stringify(i))},20),o},_._log=function(){f("info",arguments)},_._debug=function(){this._config.debug===!0&&f("debug",arguments)},_._configure=function(e){if(this._debug("Configuring centrifuge object with",e),e||(e={}),this._config=s(!1,this._config,e),!this._config.url)throw"Missing required configuration parameter 'url' specifying server URL";if(!this._config.user&&""!==this._config.user){if(!this._config.insecure)throw"Missing required configuration parameter 'user' specifying user's unique ID in your application";this._debug("user not found but this is OK for insecure mode - anonymous access will be used"),this._config.user=""}if(!this._config.timestamp){if(!this._config.insecure)throw"Missing required configuration parameter 'timestamp'";this._debug("token not found but this is OK for insecure mode")}if(!this._config.token){if(!this._config.insecure)throw"Missing required configuration parameter 'token' specifying the sign of authorization request";this._debug("timestamp not found but this is OK for insecure mode")}if(this._config.url=u(this._config.url),o(this._config.url,"connection")){if(this._debug("client will connect to SockJS endpoint"),"undefined"==typeof SockJS)throw"include SockJS client library before Centrifuge javascript client library or use raw Websocket connection endpoint";this._sockjs=!0,this._sockjsVersion=SockJS.version}else o(this._config.url,"connection/websocket")?(this._debug("client will connect to raw Websocket endpoint"),this._config.url=this._config.url.replace("http://","ws://"),this._config.url=this._config.url.replace("https://","wss://")):(this._debug("client will detect connection endpoint itself"),"undefined"==typeof SockJS?(this._debug("no SockJS found, client will connect to raw Websocket endpoint"),this._config.url+="/connection/websocket",this._config.url=this._config.url.replace("http://","ws://"),this._config.url=this._config.url.replace("https://","wss://")):(this._debug("SockJS found, client will connect to SockJS endpoint"),this._config.url+="/connection",this._sockjs=!0,this._sockjsVersion=SockJS.version))},_._setStatus=function(e){this._status!==e&&(this._debug("Status",this._status,"->",e),this._status=e)},_._isDisconnected=function(){return this._isConnected()===!1},_._isConnected=function(){return"connected"===this._status},_._isConnecting=function(){return"connecting"===this._status},_._nextMessageId=function(){return++this._messageId},_._clearSubscriptions=function(){this._subscriptions={}},_._resetRetry=function(){this._debug("reset retry timeout"),this._retry=null},_._getRetry=function(){return this._retry=null===this._retry?this._config.retry+Math.round(1e3*Math.random()):this._retry+Math.round(1e3*Math.random()),this._retry>this._config.maxRetry&&(this._retry=this._config.maxRetry),this._retry},_._send=function(e){for(var t=0;t<e.length;++t){var n=e[t];n.uid=""+this._nextMessageId(),this._clientId&&(n.clientId=this._clientId),this._debug("Send",n),this._transport.send(JSON.stringify(n))}},_._connect=function(e){if(!this.isConnected()){this._clientId=null,this._reconnect=!0,this._clearSubscriptions(),this._setStatus("connecting");var t=this;if(e&&this.on("connect",e),this._sockjs===!0){var n={};c(this._sockjsVersion,"1.")?n.transports=this._config.transports:(this._log("SockJS <= 0.3.4 is deprecated, use SockJS >= 1.0.0 instead"),n.protocols_whitelist=this._config.protocols_whitelist),null!==this._config.server&&(n.server=this._config.server),this._transport=new SockJS(this._config.url,null,n)}else this._transport=new WebSocket(this._config.url);this._setStatus("connecting"),this._transport.onopen=function(){t._resetRetry();var e={method:"connect",params:{user:t._config.user,info:t._config.info}};t._config.insecure||(e.params.timestamp=t._config.timestamp,e.params.token=t._config.token),t.send(e)},this._transport.onerror=function(e){t._debug(e)},this._transport.onclose=function(){if(t._setStatus("disconnected"),t.trigger("disconnect"),t._reconnect===!0){var e=t._getRetry();t._debug("reconnect after "+e+" milliseconds"),window.setTimeout(function(){t._reconnect===!0&&t._connect.call(t)},e)}},this._transport.onmessage=function(e){var n;n=JSON.parse(e.data),t._debug("Received",n),t._receive(n)}}},_._disconnect=function(){this._clientId=null,this._setStatus("disconnected"),this._subscriptions={},this._reconnect=!1,this._transport.close()},_._getSubscription=function(e){var t;return t=this._subscriptions[e],t?t:null},_._removeSubscription=function(e){try{delete this._subscriptions[e]}catch(t){this._debug("nothing to delete for channel ",e)}try{delete this._authChannels[e]}catch(t){this._debug("nothing to delete from authChannels for channel ",e)}},_._connectResponse=function(e){if(!this.isConnected())if(null===e.error){if(!e.body)return;if(e.body.expires){var t=e.body.expired;if(t)return void this.refresh()}if(this._clientId=e.body.client,this._setStatus("connected"),this.trigger("connect",[e]),this._refreshTimeout&&window.clearTimeout(this._refreshTimeout),e.body.expires){var n=this;this._refreshTimeout=window.setTimeout(function(){n.refresh.call(n)},1e3*e.body.ttl)}}else this.trigger("error",[e]),this.trigger("connect:error",[e])},_._disconnectResponse=function(e){null===e.error?this.disconnect():(this.trigger("error",[e]),this.trigger("disconnect:error",[e.error]))},_._subscribeResponse=function(e){null!==e.error&&this.trigger("error",[e]);var t=e.body;if(null!==t){var n=t.channel,i=this.getSubscription(n);i&&(null===e.error?(i.trigger("subscribe:success",[t]),i.trigger("ready",[t])):(i.trigger("subscribe:error",[e.error]),i.trigger("error",[e])))}},_._unsubscribeResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&null===e.error&&(i.trigger("unsubscribe",[t]),this._centrifuge._removeSubscription(n))},_._publishResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(null===e.error?i.trigger("publish:success",[t]):(i.trigger("publish:error",[e.error]),this.trigger("error",[e])))},_._presenceResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(null===e.error?(i.trigger("presence",[t]),i.trigger("presence:success",[t])):(i.trigger("presence:error",[e.error]),this.trigger("error",[e])))},_._historyResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(null===e.error?(i.trigger("history",[t]),i.trigger("history:success",[t])):(i.trigger("history:error",[e.error]),this.trigger("error",[e])))},_._joinResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&i.trigger("join",[t])},_._leaveResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&i.trigger("leave",[t])},_._messageResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);null!==i&&i.trigger("message",[t])},_._refreshResponse=function(e){if(this._refreshTimeout&&window.clearTimeout(this._refreshTimeout),e.body.expires){var t=this,n=e.body.expired;if(n)return void(t._refreshTimeout=window.setTimeout(function(){t.refresh.call(t)},3e3+Math.round(1e3*Math.random())));this._clientId=e.body.client,t._refreshTimeout=window.setTimeout(function(){t.refresh.call(t)},1e3*e.body.ttl)}},_._dispatchMessage=function(e){if(void 0!==e&&null!==e){var t=e.method;if(t)switch(t){case"connect":this._connectResponse(e);break;case"disconnect":this._disconnectResponse(e);break;case"subscribe":this._subscribeResponse(e);break;case"unsubscribe":this._unsubscribeResponse(e);break;case"publish":this._publishResponse(e);break;case"presence":this._presenceResponse(e);break;case"history":this._historyResponse(e);break;case"join":this._joinResponse(e);break;case"leave":this._leaveResponse(e);break;case"ping":break;case"refresh":this._refreshResponse(e);break;case"message":this._messageResponse(e)}}},_._receive=function(e){if(Object.prototype.toString.call(e)===Object.prototype.toString.call([])){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];this._dispatchMessage(n)}}else Object.prototype.toString.call(e)===Object.prototype.toString.call({})&&this._dispatchMessage(e)},_._flush=function(){var e=this._messages.slice(0);this._messages=[],this._send(e)},_._ping=function(){var e={method:"ping",params:{}};this.send(e)},_.getClientId=function(){return this._clientId},_.isConnected=_._isConnected,_.isConnecting=_._isConnecting,_.isDisconnected=_._isDisconnected,_.configure=function(e){this._configure.call(this,e)},_.connect=_._connect,_.disconnect=_._disconnect,_.getSubscription=_._getSubscription,_.ping=_._ping,_.send=function(e){this._isBatching===!0?this._messages.push(e):this._send([e])},_.startBatching=function(){this._isBatching=!0},_.stopBatching=function(e){e=e||!1,this._isBatching=!1,e===!0&&this.flush()},_.flush=function(){this._flush()},_.startAuthBatching=function(){this._isAuthBatching=!0},_.stopAuthBatching=function(e){this._isAuthBatching=!1;var t=this._authChannels;this._authChannels={};var n=[];for(var i in t){var s=this.getSubscription(i);s&&n.push(i)}if(0==n.length)return void(e&&e());var r={client:this.getClientId(),channels:n},o=this,c=function(t,i){if(t===!0){o._debug("authorization request failed");for(var s in n){var r=n[s];o._subscribeResponse({error:"authorization request failed",body:{channel:r}})}return void(e&&e())}for(var s in n){var r=n[s],c=i[r];if(c)if(c.status&&200!==c.status)o._subscribeResponse({error:c.status,body:{channel:r}});else{var u={method:"subscribe",params:{channel:r,client:o.getClientId(),info:c.info,sign:c.sign}};o.send(u)}else o._subscribeResponse({error:404,body:{channel:r}})}e&&e()},u=this._config.authTransport.toLowerCase();if("ajax"===u)this._ajax(this._config.authEndpoint,this._config.authParams,this._config.authHeaders,r,c);else{if("jsonp"!==u)throw"Unknown auth transport "+u;this._jsonp(this._config.authEndpoint,this._config.authParams,this._config.authHeaders,r,c)}},_.subscribe=function(e,t){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(!h(e))throw"Illegal argument type: channel must be a string";if(this.isDisconnected())throw"Can not subscribe in disconnected state";var n=this.getSubscription(e);if(null!==n)return n;var i=new g(this,e);return this._subscriptions[e]=i,i.subscribe(t),i},_.unsubscribe=function(e){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(!h(e))throw"Illegal argument type: channel must be a string";if(!this.isDisconnected()){var t=this.getSubscription(e);null!==t&&t.unsubscribe()}},_.publish=function(e,t,n){var i=this.getSubscription(e);return null===i?(this._debug("subscription not found for channel "+e),null):(i.publish(t,n),i)},_.presence=function(e,t){var n=this.getSubscription(e);return null===n?(this._debug("subscription not found for channel "+e),null):(n.presence(t),n)},_.history=function(e,t){var n=this.getSubscription(e);return null===n?(this._debug("subscription not found for channel "+e),null):(n.history(t),n)},_.refresh=function(){var e=this;this._debug("refresh credentials");var t=function(t,n){if(t===!0)return e._debug("error getting connect parameters",n),e._refreshTimeout&&window.clearTimeout(e._refreshTimeout),void(e._refreshTimeout=window.setTimeout(function(){e.refresh.call(e)},3e3));if(e._config.user=n.user,e._config.timestamp=n.timestamp,e._config.info=n.info,e._config.token=n.token,e.isDisconnected())e._debug("credentials refreshed, connect from scratch"),e._connect();else{e._debug("send refreshed credentials");var i={method:"refresh",params:{user:e._config.user,timestamp:e._config.timestamp,info:e._config.info,token:e._config.token}};e.send(i)}},n=this._config.refreshTransport.toLowerCase();if("ajax"===n)this._ajax(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,{},t);else{if("jsonp"!==n)throw"Unknown refresh transport "+n;this._jsonp(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,{},t)}},e(g,t);var p=g.prototype;p.getChannel=function(){return this.channel},p.getCentrifuge=function(){return this._centrifuge},p.subscribe=function(e){var t={method:"subscribe",params:{channel:this.channel}};c(this.channel,this._centrifuge._config.privateChannelPrefix)?this._centrifuge._isAuthBatching?this._centrifuge._authChannels[this.channel]=!0:(this._centrifuge.startAuthBatching(),this.subscribe(e),this._centrifuge.stopAuthBatching()):this._centrifuge.send(t),e&&this.on("message",e)},p.unsubscribe=function(){this._centrifuge._removeSubscription(this.channel);var e={method:"unsubscribe",params:{channel:this.channel}};this._centrifuge.send(e)},p.publish=function(e,t){var n={method:"publish",params:{channel:this.channel,data:e}};t&&this.on("publish:success",t),this._centrifuge.send(n)},p.presence=function(e){var t={method:"presence",params:{channel:this.channel}};e&&this.on("presence",e),this._centrifuge.send(t)},p.history=function(e){var t={method:"history",params:{channel:this.channel}};e&&this.on("history",e),this._centrifuge.send(t)},"function"==typeof define&&define.amd?define(function(){return l}):"object"==typeof module&&module.exports?module.exports=l:this.Centrifuge=l}).call(this); | ||
(function(){"use strict";function e(e,t){return e.prototype=Object.create(t.prototype),e.prototype.constructor=e,t.prototype}function t(){}function n(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}function i(e){return function(){return this[e].apply(this,arguments)}}function s(e,t){for(var n=t||{},i=2;i<arguments.length;++i){var o=arguments[i];if(void 0!==o&&null!==o)for(var c in o){var a=r(o,c),u=r(n,c);if(a!==t&&void 0!==a)if(e&&"object"==typeof a&&null!==a)if(a instanceof Array)n[c]=s(e,u instanceof Array?u:[],a);else{var h="object"!=typeof u||u instanceof Array?{}:u;n[c]=s(e,h,a)}else n[c]=a}}return n}function r(e,t){try{return e[t]}catch(n){return void 0}}function o(e,t){return-1!==e.indexOf(t,e.length-t.length)}function c(e,t){return 0===e.lastIndexOf(t,0)}function a(e){return"/"==e.substring(e.length-1)&&(e=e.substring(0,e.length-1)),e}function u(e){return void 0===e||null===e?!1:"string"==typeof e||e instanceof String}function h(e){return void 0===e||null===e?!1:"function"==typeof e}function f(e,t){if(window.console){var n=window.console[e];h(n)&&n.apply(window.console,t)}}function l(e){return"error"in e&&null!==e.error&&""!==e.error}function g(e){this._sockjs=!1,this._sockjsVersion=null,this._status="disconnected",this._reconnect=!0,this._transport=null,this._messageId=0,this._clientId=null,this._subscriptions={},this._lastMessageID={},this._messages=[],this._isBatching=!1,this._isAuthBatching=!1,this._authChannels={},this._refreshTimeout=null,this._retry=null,this._config={retry:1e3,maxRetry:1e4,info:"",debug:!1,insecure:!1,server:null,privateChannelPrefix:"$",protocols_whitelist:["websocket","xdr-streaming","xhr-streaming","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],transports:["websocket","xdr-streaming","xhr-streaming","eventsource","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],refreshEndpoint:"/centrifuge/refresh",refreshHeaders:{},refreshParams:{},refreshTransport:"ajax",authEndpoint:"/centrifuge/auth",authHeaders:{},authParams:{},authTransport:"ajax"},e&&this.configure(e)}function _(e,t){this._centrifuge=e,this.channel=t}Object.create||(Object.create=function(){function e(){}return function(t){if(1!=arguments.length)throw new Error("Object.create implementation only accepts one parameter.");return e.prototype=t,new e}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(e){if(null==this)throw new TypeError;var t,n,i=Object(this),s=i.length>>>0;if(0===s)return-1;if(t=0,arguments.length>1&&(t=Number(arguments[1]),t!=t?t=0:0!=t&&1/0!=t&&t!=-1/0&&(t=(t>0||-1)*Math.floor(Math.abs(t)))),t>=s)return-1;for(n=t>=0?t:Math.max(s-Math.abs(t),0);s>n;n++)if(n in i&&i[n]===e)return n;return-1});var d=t.prototype;d.getListeners=function(e){var t,n,i=this._getEvents();if("object"==typeof e){t={};for(n in i)i.hasOwnProperty(n)&&e.test(n)&&(t[n]=i[n])}else t=i[e]||(i[e]=[]);return t},d.flattenListeners=function(e){var t,n=[];for(t=0;t<e.length;t+=1)n.push(e[t].listener);return n},d.getListenersAsObject=function(e){var t,n=this.getListeners(e);return n instanceof Array&&(t={},t[e]=n),t||n},d.addListener=function(e,t){var i,s=this.getListenersAsObject(e),r="object"==typeof t;for(i in s)s.hasOwnProperty(i)&&-1===n(s[i],t)&&s[i].push(r?t:{listener:t,once:!1});return this},d.on=i("addListener"),d.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},d.once=i("addOnceListener"),d.defineEvent=function(e){return this.getListeners(e),this},d.defineEvents=function(e){for(var t=0;t<e.length;t+=1)this.defineEvent(e[t]);return this},d.removeListener=function(e,t){var i,s,r=this.getListenersAsObject(e);for(s in r)r.hasOwnProperty(s)&&(i=n(r[s],t),-1!==i&&r[s].splice(i,1));return this},d.off=i("removeListener"),d.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},d.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},d.manipulateListeners=function(e,t,n){var i,s,r=e?this.removeListener:this.addListener,o=e?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(i=n.length;i--;)r.call(this,t,n[i]);else for(i in t)t.hasOwnProperty(i)&&(s=t[i])&&("function"==typeof s?r.call(this,i,s):o.call(this,i,s));return this},d.removeEvent=function(e){var t,n=typeof e,i=this._getEvents();if("string"===n)delete i[e];else if("object"===n)for(t in i)i.hasOwnProperty(t)&&e.test(t)&&delete i[t];else delete this._events;return this},d.emitEvent=function(e,t){var n,i,s,r,o=this.getListenersAsObject(e);for(s in o)if(o.hasOwnProperty(s))for(i=o[s].length;i--;)n=o[s][i],n.once===!0&&this.removeListener(e,n.listener),r=n.listener.apply(this,t||[]),r===this._getOnceReturnValue()&&this.removeListener(e,n.listener);return this},d.trigger=i("emitEvent"),d.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},d.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},d._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},d._getEvents=function(){return this._events||(this._events={})},e(g,t),g._authCallbacks={},g._nextAuthCallbackID=1;var p=g.prototype;p._jsonp=function(e,t,n,i,s){n.length>0&&this._log("Only AJAX request allows to send custom headers, it's not possible with JSONP."),self._debug("sending JSONP request to",e);var r=g._nextAuthCallbackID.toString();g._nextAuthCallbackID++;var o=window.document,c=o.createElement("script");g._authCallbacks[r]=function(e){s(!1,e),delete g[r]};var a="";for(var u in t)a.length>0&&(a+="&"),a+=encodeURIComponent(u)+"="+encodeURIComponent(t[u]);var h="Centrifuge._authCallbacks['"+r+"']";c.src=this._config.authEndpoint+"?callback="+encodeURIComponent(h)+"&data="+encodeURIComponent(JSON.stringify(i))+"&"+a;var f=o.getElementsByTagName("head")[0]||o.documentElement;f.insertBefore(c,f.firstChild)},p._ajax=function(e,t,n,i,s){var r=this;r._debug("sending AJAX request to",e);var o=window.XMLHttpRequest?new window.XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c="";for(var a in t)c.length>0&&(c+="&"),c+=encodeURIComponent(a)+"="+encodeURIComponent(t[a]);c.length>0&&(c="?"+c),o.open("POST",e+c,!0),o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.setRequestHeader("Content-Type","application/json");for(var u in n)o.setRequestHeader(u,n[u]);return o.onreadystatechange=function(){if(4===o.readyState)if(200===o.status){var e,t=!1;try{e=JSON.parse(o.responseText),t=!0}catch(n){s(!0,"JSON returned from webapp was invalid, yet status code was 200. Data was: "+o.responseText)}t&&s(!1,e)}else r._log("Couldn't get auth info from your webapp",o.status),s(!0,o.status)},setTimeout(function(){o.send(JSON.stringify(i))},20),o},p._log=function(){f("info",arguments)},p._debug=function(){this._config.debug===!0&&f("debug",arguments)},p._configure=function(e){if(this._debug("Configuring centrifuge object with",e),e||(e={}),this._config=s(!1,this._config,e),!this._config.url)throw"Missing required configuration parameter 'url' specifying server URL";if(!this._config.user&&""!==this._config.user){if(!this._config.insecure)throw"Missing required configuration parameter 'user' specifying user's unique ID in your application";this._debug("user not found but this is OK for insecure mode - anonymous access will be used"),this._config.user=""}if(!this._config.timestamp){if(!this._config.insecure)throw"Missing required configuration parameter 'timestamp'";this._debug("token not found but this is OK for insecure mode")}if(!this._config.token){if(!this._config.insecure)throw"Missing required configuration parameter 'token' specifying the sign of authorization request";this._debug("timestamp not found but this is OK for insecure mode")}if(this._config.url=a(this._config.url),o(this._config.url,"connection")){if(this._debug("client will connect to SockJS endpoint"),"undefined"==typeof SockJS)throw"include SockJS client library before Centrifuge javascript client library or use raw Websocket connection endpoint";this._sockjs=!0,this._sockjsVersion=SockJS.version}else o(this._config.url,"connection/websocket")?(this._debug("client will connect to raw Websocket endpoint"),this._config.url=this._config.url.replace("http://","ws://"),this._config.url=this._config.url.replace("https://","wss://")):(this._debug("client will detect connection endpoint itself"),"undefined"==typeof SockJS?(this._debug("no SockJS found, client will connect to raw Websocket endpoint"),this._config.url+="/connection/websocket",this._config.url=this._config.url.replace("http://","ws://"),this._config.url=this._config.url.replace("https://","wss://")):(this._debug("SockJS found, client will connect to SockJS endpoint"),this._config.url+="/connection",this._sockjs=!0,this._sockjsVersion=SockJS.version))},p._setStatus=function(e){this._status!==e&&(this._debug("Status",this._status,"->",e),this._status=e)},p._isDisconnected=function(){return this._isConnected()===!1},p._isConnected=function(){return"connected"===this._status},p._isConnecting=function(){return"connecting"===this._status},p._nextMessageId=function(){return++this._messageId},p._clearSubscriptions=function(){this._subscriptions={}},p._resetRetry=function(){this._debug("reset retry timeout"),this._retry=null},p._getRetry=function(){return this._retry=null===this._retry?this._config.retry+Math.round(1e3*Math.random()):this._retry+Math.round(1e3*Math.random()),this._retry>this._config.maxRetry&&(this._retry=this._config.maxRetry),this._retry},p._send=function(e){for(var t=0;t<e.length;++t){var n=e[t];n.uid=""+this._nextMessageId(),this._clientId&&(n.clientId=this._clientId),this._debug("Send",n),this._transport.send(JSON.stringify(n))}},p._connect=function(e){if(!this.isConnected()){this._clientId=null,this._reconnect=!0,this._clearSubscriptions(),this._setStatus("connecting");var t=this;if(e&&this.on("connect",e),this._sockjs===!0){var n={};c(this._sockjsVersion,"1.")?n.transports=this._config.transports:(this._log("SockJS <= 0.3.4 is deprecated, use SockJS >= 1.0.0 instead"),n.protocols_whitelist=this._config.protocols_whitelist),null!==this._config.server&&(n.server=this._config.server),this._transport=new SockJS(this._config.url,null,n)}else this._transport=new WebSocket(this._config.url);this._setStatus("connecting"),this._transport.onopen=function(){t._resetRetry(),u(t._config.user)||t._debug("user expected to be string"),u(t._config.info)||t._debug("info expected to be string");var e={method:"connect",params:{user:t._config.user,info:t._config.info}};t._config.insecure||(e.params.timestamp=t._config.timestamp,e.params.token=t._config.token,u(t._config.timestamp)||t._debug("timestamp expected to be string"),u(t._config.token)||t._debug("token expected to be string")),t.send(e)},this._transport.onerror=function(e){t._debug(e)},this._transport.onclose=function(){if(t._setStatus("disconnected"),t.trigger("disconnect"),t._reconnect===!0){var e=t._getRetry();t._debug("reconnect after "+e+" milliseconds"),window.setTimeout(function(){t._reconnect===!0&&t._connect.call(t)},e)}},this._transport.onmessage=function(e){var n;n=JSON.parse(e.data),t._debug("Received",n),t._receive(n)}}},p._disconnect=function(){this._clientId=null,this._setStatus("disconnected"),this._subscriptions={},this._reconnect=!1,this._transport.close()},p._getSubscription=function(e){var t;return t=this._subscriptions[e],t?t:null},p._removeSubscription=function(e){try{delete this._subscriptions[e]}catch(t){this._debug("nothing to delete for channel ",e)}try{delete this._authChannels[e]}catch(t){this._debug("nothing to delete from authChannels for channel ",e)}},p._connectResponse=function(e){if(!this.isConnected())if(l(e))this.trigger("error",[e]),this.trigger("connect:error",[e]);else{if(!e.body)return;if(e.body.expires){var t=e.body.expired;if(t)return void this.refresh()}if(this._clientId=e.body.client,this._setStatus("connected"),this.trigger("connect",[e]),this._refreshTimeout&&window.clearTimeout(this._refreshTimeout),e.body.expires){var n=this;this._refreshTimeout=window.setTimeout(function(){n.refresh.call(n)},1e3*e.body.ttl)}}},p._disconnectResponse=function(e){l(e)?(this.trigger("error",[e]),this.trigger("disconnect:error",[e.error])):this.disconnect()},p._subscribeResponse=function(e){l(e)&&this.trigger("error",[e]);var t=e.body;if(null!==t){var n=t.channel,i=this.getSubscription(n);if(i)if(l(e))i.trigger("subscribe:error",[e.error]),i.trigger("error",[e]);else{i.trigger("subscribe:success",[t]),i.trigger("ready",[t]);var s=t.messages;if(s&&s.length>0)for(var r in s.reverse())this._messageResponse({body:s[r]});else"last"in t&&(this._lastMessageID[n]=t.last)}}},p._unsubscribeResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(l(e)||(i.trigger("unsubscribe",[t]),this._removeSubscription(n)))},p._publishResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(l(e)?(i.trigger("publish:error",[e.error]),this.trigger("error",[e])):i.trigger("publish:success",[t]))},p._presenceResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(l(e)?(i.trigger("presence:error",[e.error]),this.trigger("error",[e])):(i.trigger("presence",[t]),i.trigger("presence:success",[t])))},p._historyResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&(l(e)?(i.trigger("history:error",[e.error]),this.trigger("error",[e])):(i.trigger("history",[t]),i.trigger("history:success",[t])))},p._joinResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&i.trigger("join",[t])},p._leaveResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);i&&i.trigger("leave",[t])},p._messageResponse=function(e){var t=e.body,n=t.channel,i=this.getSubscription(n);null!==i&&(this._lastMessageID[n]=t.uid,i.trigger("message",[t]))},p._refreshResponse=function(e){if(this._refreshTimeout&&window.clearTimeout(this._refreshTimeout),e.body.expires){var t=this,n=e.body.expired;if(n)return void(t._refreshTimeout=window.setTimeout(function(){t.refresh.call(t)},3e3+Math.round(1e3*Math.random())));this._clientId=e.body.client,t._refreshTimeout=window.setTimeout(function(){t.refresh.call(t)},1e3*e.body.ttl)}},p._dispatchMessage=function(e){if(void 0!==e&&null!==e){var t=e.method;if(t)switch(t){case"connect":this._connectResponse(e);break;case"disconnect":this._disconnectResponse(e);break;case"subscribe":this._subscribeResponse(e);break;case"unsubscribe":this._unsubscribeResponse(e);break;case"publish":this._publishResponse(e);break;case"presence":this._presenceResponse(e);break;case"history":this._historyResponse(e);break;case"join":this._joinResponse(e);break;case"leave":this._leaveResponse(e);break;case"ping":break;case"refresh":this._refreshResponse(e);break;case"message":this._messageResponse(e)}}},p._receive=function(e){if(Object.prototype.toString.call(e)===Object.prototype.toString.call([])){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];this._dispatchMessage(n)}}else Object.prototype.toString.call(e)===Object.prototype.toString.call({})&&this._dispatchMessage(e)},p._flush=function(){var e=this._messages.slice(0);this._messages=[],this._send(e)},p._ping=function(){var e={method:"ping",params:{}};this.send(e)},p._recover=function(e){return e in this._lastMessageID},p._getLastID=function(e){var t=this._lastMessageID[e];return t?(this._debug("last uid found and sent for channel",e),t):(this._debug("no last uid found for channel",e),"")},p.getClientId=function(){return this._clientId},p.isConnected=p._isConnected,p.isConnecting=p._isConnecting,p.isDisconnected=p._isDisconnected,p.configure=function(e){this._configure.call(this,e)},p.connect=p._connect,p.disconnect=p._disconnect,p.getSubscription=p._getSubscription,p.ping=p._ping,p.send=function(e){this._isBatching===!0?this._messages.push(e):this._send([e])},p.startBatching=function(){this._isBatching=!0},p.stopBatching=function(e){e=e||!1,this._isBatching=!1,e===!0&&this.flush()},p.flush=function(){this._flush()},p.startAuthBatching=function(){this._isAuthBatching=!0},p.stopAuthBatching=function(e){this._isAuthBatching=!1;var t=this._authChannels;this._authChannels={};var n=[];for(var i in t){var s=this.getSubscription(i);s&&n.push(i)}if(0==n.length)return void(e&&e());var r={client:this.getClientId(),channels:n},o=this,c=function(t,i){if(t===!0){o._debug("authorization request failed");for(var s in n){var r=n[s];o._subscribeResponse({error:"authorization request failed",body:{channel:r}})}return void(e&&e())}for(var s in n){var r=n[s],c=i[r];if(c)if(c.status&&200!==c.status)o._subscribeResponse({error:c.status,body:{channel:r}});else{var a={method:"subscribe",params:{channel:r,client:o.getClientId(),info:c.info,sign:c.sign}},u=o._recover(r);u===!0&&(a.params.recover=!0,a.params.last=o._getLastID(r)),o.send(a)}else o._subscribeResponse({error:404,body:{channel:r}})}e&&e()},a=this._config.authTransport.toLowerCase();if("ajax"===a)this._ajax(this._config.authEndpoint,this._config.authParams,this._config.authHeaders,r,c);else{if("jsonp"!==a)throw"Unknown auth transport "+a;this._jsonp(this._config.authEndpoint,this._config.authParams,this._config.authHeaders,r,c)}},p.subscribe=function(e,t){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(!u(e))throw"Illegal argument type: channel must be a string";if(this.isDisconnected())throw"Can not subscribe in disconnected state";var n=this.getSubscription(e);if(null!==n)return n;var i=new _(this,e);return this._subscriptions[e]=i,i.subscribe(t),i},p.unsubscribe=function(e){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(!u(e))throw"Illegal argument type: channel must be a string";if(!this.isDisconnected()){var t=this.getSubscription(e);null!==t&&t.unsubscribe()}},p.publish=function(e,t,n){var i=this.getSubscription(e);return null===i?(this._debug("subscription not found for channel "+e),null):(i.publish(t,n),i)},p.presence=function(e,t){var n=this.getSubscription(e);return null===n?(this._debug("subscription not found for channel "+e),null):(n.presence(t),n)},p.history=function(e,t){var n=this.getSubscription(e);return null===n?(this._debug("subscription not found for channel "+e),null):(n.history(t),n)},p.refresh=function(){var e=this;this._debug("refresh credentials");var t=function(t,n){if(t===!0)return e._debug("error getting connect parameters",n),e._refreshTimeout&&window.clearTimeout(e._refreshTimeout),void(e._refreshTimeout=window.setTimeout(function(){e.refresh.call(e)},3e3));if(e._config.user=n.user,e._config.timestamp=n.timestamp,e._config.info=n.info,e._config.token=n.token,e.isDisconnected())e._debug("credentials refreshed, connect from scratch"),e._connect();else{e._debug("send refreshed credentials");var i={method:"refresh",params:{user:e._config.user,timestamp:e._config.timestamp,info:e._config.info,token:e._config.token}};e.send(i)}},n=this._config.refreshTransport.toLowerCase();if("ajax"===n)this._ajax(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,{},t);else{if("jsonp"!==n)throw"Unknown refresh transport "+n;this._jsonp(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,{},t)}},e(_,t);var b=_.prototype;b.getChannel=function(){return this.channel},b.getCentrifuge=function(){return this._centrifuge},b.subscribe=function(e){var t={method:"subscribe",params:{channel:this.channel}};if(c(this.channel,this._centrifuge._config.privateChannelPrefix))this._centrifuge._isAuthBatching?this._centrifuge._authChannels[this.channel]=!0:(this._centrifuge.startAuthBatching(),this.subscribe(e),this._centrifuge.stopAuthBatching());else{var n=this._centrifuge._recover(this.channel);n===!0&&(t.params.recover=!0,t.params.last=this._centrifuge._getLastID(this.channel)),this._centrifuge.send(t)}e&&this.on("message",e)},b.unsubscribe=function(){this._centrifuge._removeSubscription(this.channel);var e={method:"unsubscribe",params:{channel:this.channel}};this._centrifuge.send(e)},b.publish=function(e,t){var n={method:"publish",params:{channel:this.channel,data:e}};t&&this.on("publish:success",t),this._centrifuge.send(n)},b.presence=function(e){var t={method:"presence",params:{channel:this.channel}};e&&this.on("presence",e),this._centrifuge.send(t)},b.history=function(e){var t={method:"history",params:{channel:this.channel}};e&&this.on("history",e),this._centrifuge.send(t)},"function"==typeof define&&define.amd?define(function(){return g}):"object"==typeof module&&module.exports?module.exports=g:this.Centrifuge=g}).call(this); |
@@ -0,1 +1,7 @@ | ||
1.1.0 | ||
===== | ||
* support for `recover` option (introduced in Centrifugo v1.2.0) | ||
* fix removing subscription when unsubscribing from channel | ||
1.0.0 | ||
@@ -2,0 +8,0 @@ ===== |
{ | ||
"name": "centrifuge", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "Centrifuge javascript client", | ||
@@ -27,4 +27,5 @@ "main": "centrifuge.js", | ||
"sockjs", | ||
"websocket" | ||
"websocket", | ||
"centrifugo" | ||
] | ||
} |
@@ -25,2 +25,4 @@ /** | ||
this.centrifuge = null; | ||
var options = jQuery.extend(defaults, custom_options); | ||
@@ -198,3 +200,3 @@ | ||
function init() { | ||
this.init = function() { | ||
@@ -264,5 +266,7 @@ if (!Centrifuge) { | ||
centrifuge.connect(); | ||
} | ||
this.centrifuge = centrifuge; | ||
return this; | ||
}; | ||
return init(); | ||
return this.init(); | ||
@@ -269,0 +273,0 @@ } |
@@ -1,1 +0,1 @@ | ||
!function(e){e.extend({centrifuge_dom:function(n){function t(e){h.debug===!0&&console.log(e)}function r(e){var n,t=0;for(n in e)e.hasOwnProperty(n)&&t++;return t}function o(e){return h.fullMessage===!1?e.data:e}function i(e){return h.fullMessage===!1?e.body:e}function u(e){return h.fullMessage===!1?e.error:e}function c(e,n){var r=e.attr(h.channelAttr),o=n.getSubscription(r);return null===o&&t("no subscription found for channel "+r),o}function f(e){e.on("connect",function(){t("connected to Centrifuge"),g(e)}),e.on("error",function(e){t(e)}),e.on("disconnect",function(){t("disconnected from Centrifuge"),v()})}function a(e){x.on(h.eventPrefix+"publish",function(n){var t=$(this),r=c(t,e);r&&r.publish(n)}),x.on(h.eventPrefix+"presence",function(){var n=$(this),t=c(n,e);t&&t.presence(function(e){n.trigger("centrifuge-presence-message",o(e))})}),x.on(h.eventPrefix+"history",function(){var n=$(this),t=c(n,e);t&&t.history(function(e){n.trigger("centrifuge-history-message",o(e))})}),x.on(h.eventPrefix+"unsubscribe",function(){var n=$(this),t=c(n,e);t&&t.unsubscribe()})}function s(e,n){var r=p[e],c=n.subscribe(e,function(e){t(e);var n=r.attr(h.messageEventNameAttr),i=h.eventPrefix+(n||"message");r.trigger(i,o(e))});c.on("subscribe:success",function(e){var n=h.eventPrefix+"subscribe:success";r.trigger(n,i(e))}),c.on("subscribe:error",function(e){t(e);var n=h.eventPrefix+"subscribe:error";r.trigger(n,u(e))}),c.on("join",function(e){t(e);var n=h.eventPrefix+"join";r.trigger(n,o(e))}),c.on("leave",function(e){t(e);var n=h.eventPrefix+"leave";r.trigger(n,o(e))})}function l(e){var n=p[e];n.trigger(h.eventPrefix+"disconnect")}function g(e){for(var n in p)s(n,e)}function v(){for(var e in p)l(e)}function d(){x.each(function(n,t){var r=e(t),o=r.attr(h.channelAttr);p[o]=r})}function m(){if(!Centrifuge)return void console.log("No Centrifuge javascript client found");if(0===x.length)return void t("No Centrifuge handlers found on this page, nothing to do");var e=$(h.tokenSelector).attr(h.valueAttrName);if(!e)return void console.log("Centrifuge token not found");var n=$(h.userSelector).attr(h.valueAttrName);if(!n)return void console.log("Centrifuge user not found");var o=$(h.timestampSelector).attr(h.valueAttrName);if(!o)return void console.log("Centrifuge timestamp not found");var i;if(null===h.url&&(i=$(h.urlSelector).attr(h.valueAttrName)),!i)return void console.log("Centrifuge connection url not found");var u=$(h.infoSelector).attr(h.valueAttrName);u||(t("Centrifuge info not used, token must be generated without info part."),u=null);var c=new Centrifuge({url:i,token:e,user:n,timestamp:o,info:u});return d(c),0===r(p)?void t("No valid handlers found on page, no need in connection to Centrifuge"):(f(c),a(c),void c.connect())}var b={url:null,selector:".centrifuge",urlSelector:"#centrifuge-address",tokenSelector:"#centrifuge-token",userSelector:"#centrifuge-user",timestampSelector:"#centrifuge-timestamp",infoSelector:"#centrifuge-info",valueAttrName:"data-centrifuge-value",channelAttr:"data-centrifuge-channel",messageEventNameAttr:"data-centrifuge-message",eventPrefix:"centrifuge.",fullMessage:!0,debug:!1},h=e.extend(b,n),p={},x=e(h.selector);return m()}})}(jQuery); | ||
!function(e){e.extend({centrifuge_dom:function(n){function t(e){m.debug===!0&&console.log(e)}function r(e){var n,t=0;for(n in e)e.hasOwnProperty(n)&&t++;return t}function i(e){return m.fullMessage===!1?e.data:e}function o(e){return m.fullMessage===!1?e.body:e}function u(e){return m.fullMessage===!1?e.error:e}function c(e,n){var r=e.attr(m.channelAttr),i=n.getSubscription(r);return null===i&&t("no subscription found for channel "+r),i}function f(e){e.on("connect",function(){t("connected to Centrifuge"),g(e)}),e.on("error",function(e){t(e)}),e.on("disconnect",function(){t("disconnected from Centrifuge"),v()})}function s(e){p.on(m.eventPrefix+"publish",function(n){var t=$(this),r=c(t,e);r&&r.publish(n)}),p.on(m.eventPrefix+"presence",function(){var n=$(this),t=c(n,e);t&&t.presence(function(e){n.trigger("centrifuge-presence-message",i(e))})}),p.on(m.eventPrefix+"history",function(){var n=$(this),t=c(n,e);t&&t.history(function(e){n.trigger("centrifuge-history-message",i(e))})}),p.on(m.eventPrefix+"unsubscribe",function(){var n=$(this),t=c(n,e);t&&t.unsubscribe()})}function a(e,n){var r=b[e],c=n.subscribe(e,function(e){t(e);var n=r.attr(m.messageEventNameAttr),o=m.eventPrefix+(n||"message");r.trigger(o,i(e))});c.on("subscribe:success",function(e){var n=m.eventPrefix+"subscribe:success";r.trigger(n,o(e))}),c.on("subscribe:error",function(e){t(e);var n=m.eventPrefix+"subscribe:error";r.trigger(n,u(e))}),c.on("join",function(e){t(e);var n=m.eventPrefix+"join";r.trigger(n,i(e))}),c.on("leave",function(e){t(e);var n=m.eventPrefix+"leave";r.trigger(n,i(e))})}function l(e){var n=b[e];n.trigger(m.eventPrefix+"disconnect")}function g(e){for(var n in b)a(n,e)}function v(){for(var e in b)l(e)}function d(){p.each(function(n,t){var r=e(t),i=r.attr(m.channelAttr);b[i]=r})}var h={url:null,selector:".centrifuge",urlSelector:"#centrifuge-address",tokenSelector:"#centrifuge-token",userSelector:"#centrifuge-user",timestampSelector:"#centrifuge-timestamp",infoSelector:"#centrifuge-info",valueAttrName:"data-centrifuge-value",channelAttr:"data-centrifuge-channel",messageEventNameAttr:"data-centrifuge-message",eventPrefix:"centrifuge.",fullMessage:!0,debug:!1};this.centrifuge=null;var m=e.extend(h,n),b={},p=e(m.selector);return this.init=function(){if(!Centrifuge)return void console.log("No Centrifuge javascript client found");if(0===p.length)return void t("No Centrifuge handlers found on this page, nothing to do");var e=$(m.tokenSelector).attr(m.valueAttrName);if(!e)return void console.log("Centrifuge token not found");var n=$(m.userSelector).attr(m.valueAttrName);if(!n)return void console.log("Centrifuge user not found");var i=$(m.timestampSelector).attr(m.valueAttrName);if(!i)return void console.log("Centrifuge timestamp not found");var o;if(null===m.url&&(o=$(m.urlSelector).attr(m.valueAttrName)),!o)return void console.log("Centrifuge connection url not found");var u=$(m.infoSelector).attr(m.valueAttrName);u||(t("Centrifuge info not used, token must be generated without info part."),u=null);var c=new Centrifuge({url:o,token:e,user:n,timestamp:i,info:u});return d(c),0===r(b)?void t("No valid handlers found on page, no need in connection to Centrifuge"):(f(c),s(c),c.connect(),this.centrifuge=c,this)},this.init()}})}(jQuery); |
@@ -601,2 +601,6 @@ ;(function () { | ||
function errorExists(data) { | ||
return "error" in data && data.error !== null && data.error !== ""; | ||
} | ||
function Centrifuge(options) { | ||
@@ -611,2 +615,3 @@ this._sockjs = false; | ||
this._subscriptions = {}; | ||
this._lastMessageID = {}; | ||
this._messages = []; | ||
@@ -942,2 +947,9 @@ this._isBatching = false; | ||
if (!isString(self._config.user)) { | ||
self._debug("user expected to be string"); | ||
} | ||
if (!isString(self._config.info)) { | ||
self._debug("info expected to be string"); | ||
} | ||
var centrifugeMessage = { | ||
@@ -954,2 +966,8 @@ 'method': 'connect', | ||
centrifugeMessage["params"]["token"] = self._config.token; | ||
if (!isString(self._config.timestamp)) { | ||
self._debug("timestamp expected to be string"); | ||
} | ||
if (!isString(self._config.token)) { | ||
self._debug("token expected to be string"); | ||
} | ||
} | ||
@@ -1019,3 +1037,3 @@ self.send(centrifugeMessage); | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
if (!message.body) { | ||
@@ -1050,3 +1068,3 @@ return; | ||
centrifugeProto._disconnectResponse = function (message) { | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
this.disconnect(); | ||
@@ -1060,3 +1078,3 @@ } else { | ||
centrifugeProto._subscribeResponse = function (message) { | ||
if (message.error !== null) { | ||
if (errorExists(message)) { | ||
this.trigger('error', [message]); | ||
@@ -1073,5 +1091,15 @@ } | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('subscribe:success', [body]); | ||
subscription.trigger('ready', [body]); | ||
var messages = body["messages"]; | ||
if (messages && messages.length > 0) { | ||
for (var i in messages.reverse()) { | ||
this._messageResponse({body: messages[i]}); | ||
} | ||
} else { | ||
if ("last" in body) { | ||
this._lastMessageID[channel] = body["last"]; | ||
} | ||
} | ||
} else { | ||
@@ -1090,5 +1118,5 @@ subscription.trigger('subscribe:error', [message.error]); | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('unsubscribe', [body]); | ||
this._centrifuge._removeSubscription(channel); | ||
this._removeSubscription(channel); | ||
} | ||
@@ -1104,3 +1132,3 @@ }; | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('publish:success', [body]); | ||
@@ -1120,3 +1148,3 @@ } else { | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('presence', [body]); | ||
@@ -1137,3 +1165,3 @@ subscription.trigger('presence:success', [body]); | ||
} | ||
if (message.error === null) { | ||
if (!errorExists(message)) { | ||
subscription.trigger('history', [body]); | ||
@@ -1174,2 +1202,4 @@ subscription.trigger('history:success', [body]); | ||
} | ||
// keep last uid received from channel. | ||
this._lastMessageID[channel] = body["uid"]; | ||
subscription.trigger('message', [body]); | ||
@@ -1277,2 +1307,17 @@ }; | ||
centrifugeProto._recover = function(channel) { | ||
return channel in this._lastMessageID; | ||
}; | ||
centrifugeProto._getLastID = function(channel) { | ||
var lastUID = this._lastMessageID[channel]; | ||
if (lastUID) { | ||
this._debug("last uid found and sent for channel", channel); | ||
return lastUID; | ||
} else { | ||
this._debug("no last uid found for channel", channel); | ||
return ""; | ||
} | ||
}; | ||
/* PUBLIC API */ | ||
@@ -1406,2 +1451,7 @@ | ||
}; | ||
var recover = self._recover(channel); | ||
if (recover === true) { | ||
centrifugeMessage["params"]["recover"] = true; | ||
centrifugeMessage["params"]["last"] = self._getLastID(channel); | ||
} | ||
self.send(centrifugeMessage); | ||
@@ -1600,2 +1650,7 @@ } else { | ||
} else { | ||
var recover = this._centrifuge._recover(this.channel); | ||
if (recover === true) { | ||
centrifugeMessage["params"]["recover"] = true; | ||
centrifugeMessage["params"]["last"] = this._centrifuge._getLastID(this.channel); | ||
} | ||
this._centrifuge.send(centrifugeMessage); | ||
@@ -1602,0 +1657,0 @@ } |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
159469
3268