centrifuge
Advanced tools
Comparing version 0.9.0 to 1.0.0
{ | ||
"name": "centrifuge", | ||
"version": "0.9.0", | ||
"version": "1.0.0", | ||
"ignore": [ | ||
@@ -5,0 +5,0 @@ "node_modules", |
@@ -563,90 +563,2 @@ ;(function () { | ||
// http://krasimirtsonev.com/blog/article/Cross-browser-handling-of-Ajax-requests-in-absurdjs | ||
var AJAX = { | ||
request: function(url, method, ops) { | ||
ops.data = ops.data || {}; | ||
var getParams = function(data, request_url) { | ||
var arr = [], str; | ||
for(var name in data) { | ||
if (typeof data[name] === 'object') { | ||
for (var i in data[name]) { | ||
arr.push(name + '=' + encodeURIComponent(data[name][i])); | ||
} | ||
} else { | ||
arr.push(name + '=' + encodeURIComponent(data[name])); | ||
} | ||
} | ||
str = arr.join('&'); | ||
if(str != '') { | ||
return request_url ? (request_url.indexOf('?') < 0 ? '?' + str : '&' + str) : str; | ||
} | ||
return ''; | ||
}; | ||
var api = { | ||
host: {}, | ||
setHeaders: function(headers) { | ||
for(var name in headers) { | ||
this.xhr && this.xhr.setRequestHeader(name, headers[name]); | ||
} | ||
}, | ||
process: function(ops) { | ||
var self = this; | ||
this.xhr = null; | ||
if (window.ActiveXObject) { | ||
this.xhr = new ActiveXObject('Microsoft.XMLHTTP'); | ||
} | ||
else if (window.XMLHttpRequest) { | ||
this.xhr = new XMLHttpRequest(); | ||
} | ||
if(this.xhr) { | ||
this.xhr.onreadystatechange = function() { | ||
if(self.xhr.readyState == 4 && self.xhr.status == 200) { | ||
var result = self.xhr.responseText; | ||
if (typeof JSON != 'undefined') { | ||
result = JSON.parse(result); | ||
} else { | ||
throw "JSON undefined"; | ||
} | ||
self.doneCallback && self.doneCallback.apply(self.host, [result, self.xhr]); | ||
} else if(self.xhr.readyState == 4) { | ||
self.failCallback && self.failCallback.apply(self.host, [self.xhr]); | ||
} | ||
self.alwaysCallback && self.alwaysCallback.apply(self.host, [self.xhr]); | ||
} | ||
} | ||
if(method == 'get') { | ||
this.xhr.open("GET", url + getParams(ops.data, url), true); | ||
} else { | ||
this.xhr.open(method, url, true); | ||
this.setHeaders({ | ||
'X-Requested-With': 'XMLHttpRequest', | ||
'Content-type': 'application/x-www-form-urlencoded' | ||
}); | ||
} | ||
if(ops.headers && typeof ops.headers == 'object') { | ||
this.setHeaders(ops.headers); | ||
} | ||
setTimeout(function() { | ||
method == 'get' ? self.xhr.send() : self.xhr.send(getParams(ops.data)); | ||
}, 20); | ||
return this; | ||
}, | ||
done: function(callback) { | ||
this.doneCallback = callback; | ||
return this; | ||
}, | ||
fail: function(callback) { | ||
this.failCallback = callback; | ||
return this; | ||
}, | ||
always: function(callback) { | ||
this.alwaysCallback = callback; | ||
return this; | ||
} | ||
}; | ||
return api.process(ops); | ||
} | ||
}; | ||
function endsWith(value, suffix) { | ||
@@ -704,4 +616,6 @@ return value.indexOf(suffix, value.length - suffix.length) !== -1; | ||
this._refreshTimeout = null; | ||
this._retry = null; | ||
this._config = { | ||
retry: 3000, | ||
retry: 1000, | ||
maxRetry: 10000, | ||
info: "", | ||
@@ -711,2 +625,3 @@ debug: false, | ||
server: null, | ||
privateChannelPrefix: "$", | ||
protocols_whitelist: [ | ||
@@ -735,7 +650,10 @@ 'websocket', | ||
], | ||
privateChannelPrefix: "$", | ||
refreshEndpoint: "/centrifuge/refresh", | ||
refreshHeaders: {}, | ||
refreshParams: {}, | ||
refreshTransport: "ajax", | ||
authEndpoint: "/centrifuge/auth", | ||
authHeaders: {}, | ||
refreshHeaders: {} | ||
authParams: {}, | ||
authTransport: "ajax" | ||
}; | ||
@@ -749,4 +667,97 @@ if (options) { | ||
Centrifuge._authCallbacks = {}; | ||
Centrifuge._nextAuthCallbackID = 1; | ||
var centrifugeProto = Centrifuge.prototype; | ||
centrifugeProto._jsonp = function (url, params, headers, data, callback) { | ||
if (headers.length > 0) { | ||
this._log("Only AJAX request allows to send custom headers, it's not possible with JSONP."); | ||
} | ||
self._debug("sending JSONP request to", url); | ||
var callbackName = Centrifuge._nextAuthCallbackID.toString(); | ||
Centrifuge._nextAuthCallbackID++; | ||
var document = window.document; | ||
var script = document.createElement("script"); | ||
Centrifuge._authCallbacks[callbackName] = function (data) { | ||
callback(false, data); | ||
delete Centrifuge[callbackName]; | ||
}; | ||
var query = ""; | ||
for (var i in params) { | ||
if (query.length > 0) { | ||
query += "&"; | ||
} | ||
query += encodeURIComponent(i) + "=" + encodeURIComponent(params[i]); | ||
} | ||
var callback_name = "Centrifuge._authCallbacks['" + callbackName + "']"; | ||
script.src = this._config.authEndpoint + | ||
'?callback=' + encodeURIComponent(callback_name) + | ||
'&data=' + encodeURIComponent(JSON.stringify(data)) + | ||
'&' + query; | ||
var head = document.getElementsByTagName("head")[0] || document.documentElement; | ||
head.insertBefore(script, head.firstChild); | ||
}; | ||
centrifugeProto._ajax = function (url, params, headers, data, callback) { | ||
var self = this; | ||
self._debug("sending AJAX request to", url); | ||
var xhr = (window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")); | ||
var query = ""; | ||
for (var i in params) { | ||
if (query.length > 0) { | ||
query += "&"; | ||
} | ||
query += encodeURIComponent(i) + "=" + encodeURIComponent(params[i]); | ||
} | ||
if (query.length > 0) { | ||
query = "?" + query; | ||
} | ||
xhr.open("POST", url + query, true); | ||
// add request headers | ||
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); | ||
xhr.setRequestHeader("Content-Type", "application/json"); | ||
for (var headerName in headers) { | ||
xhr.setRequestHeader(headerName, headers[headerName]); | ||
} | ||
xhr.onreadystatechange = function () { | ||
if (xhr.readyState === 4) { | ||
if (xhr.status === 200) { | ||
var data, parsed = false; | ||
try { | ||
data = JSON.parse(xhr.responseText); | ||
parsed = true; | ||
} catch (e) { | ||
callback(true, 'JSON returned from webapp was invalid, yet status code was 200. Data was: ' + xhr.responseText); | ||
} | ||
if (parsed) { // prevents double execution. | ||
callback(false, data); | ||
} | ||
} else { | ||
self._log("Couldn't get auth info from your webapp", xhr.status); | ||
callback(true, xhr.status); | ||
} | ||
} | ||
}; | ||
setTimeout(function() { | ||
// method == 'get' ? self.xhr.send() : self.xhr.send(JSON.stringify(ops.data)); | ||
xhr.send(JSON.stringify(data)); | ||
}, 20); | ||
return xhr; | ||
}; | ||
centrifugeProto._log = function () { | ||
@@ -775,6 +786,2 @@ log("info", arguments); | ||
if (!this._config.project) { | ||
throw 'Missing required configuration parameter \'project\' specifying project key in server configuration'; | ||
} | ||
if (!this._config.user && this._config.user !== '') { | ||
@@ -861,2 +868,19 @@ if (!this._config.insecure) { | ||
centrifugeProto._resetRetry = function() { | ||
this._debug("reset retry timeout"); | ||
this._retry = null; | ||
}; | ||
centrifugeProto._getRetry = function() { | ||
if (this._retry === null) { | ||
this._retry = this._config.retry + Math.round(Math.random() * 1000); | ||
} else { | ||
this._retry = this._retry + Math.round(Math.random() * 1000); | ||
} | ||
if (this._retry > this._config.maxRetry) { | ||
this._retry = this._config.maxRetry; | ||
} | ||
return this._retry; | ||
}; | ||
centrifugeProto._send = function (messages) { | ||
@@ -921,2 +945,4 @@ // We must be sure that the messages have a clientId. | ||
self._resetRetry(); | ||
var centrifugeMessage = { | ||
@@ -926,3 +952,2 @@ 'method': 'connect', | ||
'user': self._config.user, | ||
'project': self._config.project, | ||
'info': self._config.info | ||
@@ -947,2 +972,4 @@ } | ||
if (self._reconnect === true) { | ||
var retry = self._getRetry(); | ||
self._debug("reconnect after " + retry + " milliseconds"); | ||
window.setTimeout(function () { | ||
@@ -952,3 +979,3 @@ if (self._reconnect === true) { | ||
} | ||
}, self._config.retry); | ||
}, retry); | ||
} | ||
@@ -1003,6 +1030,8 @@ }; | ||
} | ||
var isExpired = message.body.expired; | ||
if (isExpired) { | ||
this.refresh(); | ||
return; | ||
if (message.body.expires) { | ||
var isExpired = message.body.expired; | ||
if (isExpired) { | ||
this.refresh(); | ||
return; | ||
} | ||
} | ||
@@ -1015,3 +1044,3 @@ this._clientId = message.body.client; | ||
} | ||
if (message.body.ttl !== null) { | ||
if (message.body.expires) { | ||
var self = this; | ||
@@ -1153,4 +1182,12 @@ this._refreshTimeout = window.setTimeout(function() { | ||
} | ||
if (message.body.ttl !== null) { | ||
if (message.body.expires) { | ||
var self = this; | ||
var isExpired = message.body.expired; | ||
if (isExpired) { | ||
self._refreshTimeout = window.setTimeout(function(){ | ||
self.refresh.call(self); | ||
}, 3000 + Math.round(Math.random() * 1000)); | ||
return; | ||
} | ||
this._clientId = message.body.client; | ||
self._refreshTimeout = window.setTimeout(function () { | ||
@@ -1324,3 +1361,3 @@ self.refresh.call(self); | ||
"client": this.getClientId(), | ||
"channels[]": channels | ||
"channels": channels | ||
}; | ||
@@ -1330,6 +1367,19 @@ | ||
AJAX.request(this._config.authEndpoint, "post", { | ||
"headers": this._config.authHeaders, | ||
"data": data | ||
}).done(function(data) { | ||
var cb = function(error, data) { | ||
if (error === true) { | ||
self._debug("authorization request failed"); | ||
for (var i in channels) { | ||
var channel = channels[i]; | ||
self._subscribeResponse({ | ||
"error": "authorization request failed", | ||
"body": { | ||
"channel": channel | ||
} | ||
}); | ||
} | ||
if (callback) { | ||
callback(); | ||
} | ||
return; | ||
} | ||
for (var i in channels) { | ||
@@ -1368,20 +1418,15 @@ var channel = channels[i]; | ||
} | ||
}).fail(function() { | ||
self._debug("authorization request failed"); | ||
for (var i in channels) { | ||
var channel = channels[i]; | ||
self._subscribeResponse({ | ||
"error": "authorization request failed", | ||
"body": { | ||
"channel": channel | ||
} | ||
}); | ||
} | ||
return false; | ||
}).always(function(){ | ||
if (callback) { | ||
callback(); | ||
} | ||
}) | ||
}; | ||
var transport = this._config.authTransport.toLowerCase(); | ||
if (transport === "ajax") { | ||
this._ajax(this._config.authEndpoint, this._config.authParams, this._config.authHeaders, data, cb); | ||
} else if (transport === "jsonp") { | ||
this._jsonp(this._config.authEndpoint, this._config.authParams, this._config.authHeaders, data, cb); | ||
} else { | ||
throw 'Unknown auth transport ' + transport; | ||
} | ||
}; | ||
@@ -1461,18 +1506,29 @@ | ||
centrifugeProto.refresh = function () { | ||
// ask web app for connection parameters - project ID, user ID, | ||
// ask web app for connection parameters - user ID, | ||
// timestamp, info and token | ||
var self = this; | ||
this._debug('refresh'); | ||
AJAX.request(this._config.refreshEndpoint, "post", { | ||
"headers": this._config.refreshHeaders, | ||
"data": {} | ||
}).done(function(data) { | ||
this._debug('refresh credentials'); | ||
var cb = function(error, data) { | ||
if (error === true) { | ||
// 403 or 500 - does not matter - if connection check activated then Centrifugo | ||
// will disconnect client eventually | ||
self._debug("error getting connect parameters", data); | ||
if (self._refreshTimeout) { | ||
window.clearTimeout(self._refreshTimeout); | ||
} | ||
self._refreshTimeout = window.setTimeout(function(){ | ||
self.refresh.call(self); | ||
}, 3000); | ||
return; | ||
} | ||
self._config.user = data.user; | ||
self._config.project = data.project; | ||
self._config.timestamp = data.timestamp; | ||
self._config.info = data.info; | ||
self._config.token = data.token; | ||
if (self._reconnect && self.isDisconnected()) { | ||
self.connect(); | ||
if (self.isDisconnected()) { | ||
self._debug("credentials refreshed, connect from scratch"); | ||
self._connect(); | ||
} else { | ||
self._debug("send refreshed credentials"); | ||
var centrifugeMessage = { | ||
@@ -1482,3 +1538,2 @@ "method": "refresh", | ||
'user': self._config.user, | ||
'project': self._config.project, | ||
'timestamp': self._config.timestamp, | ||
@@ -1491,14 +1546,12 @@ 'info': self._config.info, | ||
} | ||
}).fail(function(xhr){ | ||
// 403 or 500 - does not matter - if connection check activated then Centrifuge | ||
// will disconnect client eventually | ||
self._debug(xhr); | ||
self._debug("error getting connect parameters"); | ||
if (self._refreshTimeout) { | ||
window.clearTimeout(self._refreshTimeout); | ||
} | ||
self._refreshTimeout = window.setTimeout(function(){ | ||
self.refresh.call(self); | ||
}, 3000); | ||
}); | ||
}; | ||
var transport = this._config.refreshTransport.toLowerCase(); | ||
if (transport === "ajax") { | ||
this._ajax(this._config.refreshEndpoint, this._config.refreshParams, this._config.refreshHeaders, {}, cb); | ||
} else if (transport === "jsonp") { | ||
this._jsonp(this._config.refreshEndpoint, this._config.refreshParams, this._config.refreshHeaders, {}, cb); | ||
} else { | ||
throw 'Unknown refresh transport ' + transport; | ||
} | ||
}; | ||
@@ -1505,0 +1558,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,n){for(var i=t||{},o=2;o<arguments.length;++o){var c=arguments[o];if(void 0!==c&&null!==c)for(var u in c){var h=r(c,u),a=r(i,u);if(h!==t&&void 0!==h)if(e&&"object"==typeof h&&null!==h)if(h instanceof Array)i[u]=s(e,a instanceof Array?a:[],h);else{var f="object"!=typeof a||a instanceof Array?{}:a;i[u]=s(e,f,h)}else i[u]=h}}return i}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._config={retry:3e3,info:"",debug:!1,insecure:!1,server:null,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"],privateChannelPrefix:"$",refreshEndpoint:"/centrifuge/refresh",authEndpoint:"/centrifuge/auth",authHeaders:{},refreshHeaders:{}},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&&t!=1/0&&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 p=t.prototype;p.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},p.flattenListeners=function(e){var t,n=[];for(t=0;t<e.length;t+=1)n.push(e[t].listener);return n},p.getListenersAsObject=function(e){var t,n=this.getListeners(e);return n instanceof Array&&(t={},t[e]=n),t||n},p.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},p.on=i("addListener"),p.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},p.once=i("addOnceListener"),p.defineEvent=function(e){return this.getListeners(e),this},p.defineEvents=function(e){for(var t=0;t<e.length;t+=1)this.defineEvent(e[t]);return this},p.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},p.off=i("removeListener"),p.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},p.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},p.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},p.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},p.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},p.trigger=i("emitEvent"),p.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},p.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},p._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},p._getEvents=function(){return this._events||(this._events={})};var d={request:function(e,t,n){n.data=n.data||{};var i=function(e,t){var n,i=[];for(var s in e)if("object"==typeof e[s])for(var r in e[s])i.push(s+"="+encodeURIComponent(e[s][r]));else i.push(s+"="+encodeURIComponent(e[s]));return n=i.join("&"),""!=n?t?t.indexOf("?")<0?"?"+n:"&"+n:n:""},s={host:{},setHeaders:function(e){for(var t in e)this.xhr&&this.xhr.setRequestHeader(t,e[t])},process:function(n){var s=this;return this.xhr=null,window.ActiveXObject?this.xhr=new ActiveXObject("Microsoft.XMLHTTP"):window.XMLHttpRequest&&(this.xhr=new XMLHttpRequest),this.xhr&&(this.xhr.onreadystatechange=function(){if(4==s.xhr.readyState&&200==s.xhr.status){var e=s.xhr.responseText;if("undefined"==typeof JSON)throw"JSON undefined";e=JSON.parse(e),s.doneCallback&&s.doneCallback.apply(s.host,[e,s.xhr])}else 4==s.xhr.readyState&&s.failCallback&&s.failCallback.apply(s.host,[s.xhr]);s.alwaysCallback&&s.alwaysCallback.apply(s.host,[s.xhr])}),"get"==t?this.xhr.open("GET",e+i(n.data,e),!0):(this.xhr.open(t,e,!0),this.setHeaders({"X-Requested-With":"XMLHttpRequest","Content-type":"application/x-www-form-urlencoded"})),n.headers&&"object"==typeof n.headers&&this.setHeaders(n.headers),setTimeout(function(){"get"==t?s.xhr.send():s.xhr.send(i(n.data))},20),this},done:function(e){return this.doneCallback=e,this},fail:function(e){return this.failCallback=e,this},always:function(e){return this.alwaysCallback=e,this}};return s.process(n)}};e(l,t);var _=l.prototype;_._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.project)throw"Missing required configuration parameter 'project' specifying project key in server configuration";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={}},_._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(){var e={method:"connect",params:{user:t._config.user,project:t._config.project,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(){t._setStatus("disconnected"),t.trigger("disconnect"),t._reconnect===!0&&window.setTimeout(function(){t._reconnect===!0&&t._connect.call(t)},t._config.retry)},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;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),null!==e.body.ttl){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),null!==e.body.ttl){var t=this;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;d.request(this._config.authEndpoint,"post",{headers:this._config.authHeaders,data:r}).done(function(e){for(var t in n){var i=n[t],s=e[i];if(s)if(s.status&&200!==s.status)o._subscribeResponse({error:s.status,body:{channel:i}});else{var r={method:"subscribe",params:{channel:i,client:o.getClientId(),info:s.info,sign:s.sign}};o.send(r)}else o._subscribeResponse({error:404,body:{channel:i}})}}).fail(function(){o._debug("authorization request failed");for(var e in n){var t=n[e];o._subscribeResponse({error:"authorization request failed",body:{channel:t}})}return!1}).always(function(){e&&e()})},_.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"),d.request(this._config.refreshEndpoint,"post",{headers:this._config.refreshHeaders,data:{}}).done(function(t){if(e._config.user=t.user,e._config.project=t.project,e._config.timestamp=t.timestamp,e._config.info=t.info,e._config.token=t.token,e._reconnect&&e.isDisconnected())e.connect();else{var n={method:"refresh",params:{user:e._config.user,project:e._config.project,timestamp:e._config.timestamp,info:e._config.info,token:e._config.token}};e.send(n)}}).fail(function(t){e._debug(t),e._debug("error getting connect parameters"),e._refreshTimeout&&window.clearTimeout(e._refreshTimeout),e._refreshTimeout=window.setTimeout(function(){e.refresh.call(e)},3e3)})},e(g,t);var b=g.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}};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)},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 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 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); |
@@ -0,1 +1,11 @@ | ||
1.0.0 | ||
===== | ||
One backwards incompatible change here. Centrifuge-js now sends JSON (`application/json`) | ||
request instead of `application/x-www-form-urlencoded` when client wants to subscribe on | ||
private channel. See [in docs](https://fzambia.gitbooks.io/centrifugal/content/mixed/private_channels.html) how to deal with JSON in this case. | ||
* send JSON instead of form when subscribing on private channel. | ||
* simple reconnect strategy | ||
0.9.0 | ||
@@ -2,0 +12,0 @@ ===== |
{ | ||
"name": "centrifuge", | ||
"version": "0.9.0", | ||
"version": "1.0.0", | ||
"description": "Centrifuge javascript client", | ||
@@ -5,0 +5,0 @@ "main": "centrifuge.js", |
@@ -14,3 +14,2 @@ /** | ||
tokenSelector: '#centrifuge-token', | ||
projectSelector: '#centrifuge-project', | ||
userSelector: '#centrifuge-user', | ||
@@ -217,8 +216,2 @@ timestampSelector: '#centrifuge-timestamp', | ||
var project = $(options.projectSelector).attr(options.valueAttrName); | ||
if (!project) { | ||
console.log("Centrifuge project not found"); | ||
return; | ||
} | ||
var user = $(options.userSelector).attr(options.valueAttrName); | ||
@@ -256,3 +249,2 @@ if (!user) { | ||
token: token, | ||
project: project, | ||
user: user, | ||
@@ -259,0 +251,0 @@ timestamp: timestamp, |
@@ -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.projectSelector).attr(h.valueAttrName);if(!n)return void console.log("Centrifuge project not found");var o=$(h.userSelector).attr(h.valueAttrName);if(!o)return void console.log("Centrifuge user not found");var i=$(h.timestampSelector).attr(h.valueAttrName);if(!i)return void console.log("Centrifuge timestamp not found");var u;if(null===h.url&&(u=$(h.urlSelector).attr(h.valueAttrName)),!u)return void console.log("Centrifuge connection url not found");var c=$(h.infoSelector).attr(h.valueAttrName);c||(t("Centrifuge info not used, token must be generated without info part."),c=null);var s=new Centrifuge({url:u,token:e,project:n,user:o,timestamp:i,info:c});return d(s),0===r(p)?void t("No valid handlers found on page, no need in connection to Centrifuge"):(f(s),a(s),void s.connect())}var b={url:null,selector:".centrifuge",urlSelector:"#centrifuge-address",tokenSelector:"#centrifuge-token",projectSelector:"#centrifuge-project",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){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); |
@@ -563,90 +563,2 @@ ;(function () { | ||
// http://krasimirtsonev.com/blog/article/Cross-browser-handling-of-Ajax-requests-in-absurdjs | ||
var AJAX = { | ||
request: function(url, method, ops) { | ||
ops.data = ops.data || {}; | ||
var getParams = function(data, request_url) { | ||
var arr = [], str; | ||
for(var name in data) { | ||
if (typeof data[name] === 'object') { | ||
for (var i in data[name]) { | ||
arr.push(name + '=' + encodeURIComponent(data[name][i])); | ||
} | ||
} else { | ||
arr.push(name + '=' + encodeURIComponent(data[name])); | ||
} | ||
} | ||
str = arr.join('&'); | ||
if(str != '') { | ||
return request_url ? (request_url.indexOf('?') < 0 ? '?' + str : '&' + str) : str; | ||
} | ||
return ''; | ||
}; | ||
var api = { | ||
host: {}, | ||
setHeaders: function(headers) { | ||
for(var name in headers) { | ||
this.xhr && this.xhr.setRequestHeader(name, headers[name]); | ||
} | ||
}, | ||
process: function(ops) { | ||
var self = this; | ||
this.xhr = null; | ||
if (window.ActiveXObject) { | ||
this.xhr = new ActiveXObject('Microsoft.XMLHTTP'); | ||
} | ||
else if (window.XMLHttpRequest) { | ||
this.xhr = new XMLHttpRequest(); | ||
} | ||
if(this.xhr) { | ||
this.xhr.onreadystatechange = function() { | ||
if(self.xhr.readyState == 4 && self.xhr.status == 200) { | ||
var result = self.xhr.responseText; | ||
if (typeof JSON != 'undefined') { | ||
result = JSON.parse(result); | ||
} else { | ||
throw "JSON undefined"; | ||
} | ||
self.doneCallback && self.doneCallback.apply(self.host, [result, self.xhr]); | ||
} else if(self.xhr.readyState == 4) { | ||
self.failCallback && self.failCallback.apply(self.host, [self.xhr]); | ||
} | ||
self.alwaysCallback && self.alwaysCallback.apply(self.host, [self.xhr]); | ||
} | ||
} | ||
if(method == 'get') { | ||
this.xhr.open("GET", url + getParams(ops.data, url), true); | ||
} else { | ||
this.xhr.open(method, url, true); | ||
this.setHeaders({ | ||
'X-Requested-With': 'XMLHttpRequest', | ||
'Content-type': 'application/x-www-form-urlencoded' | ||
}); | ||
} | ||
if(ops.headers && typeof ops.headers == 'object') { | ||
this.setHeaders(ops.headers); | ||
} | ||
setTimeout(function() { | ||
method == 'get' ? self.xhr.send() : self.xhr.send(getParams(ops.data)); | ||
}, 20); | ||
return this; | ||
}, | ||
done: function(callback) { | ||
this.doneCallback = callback; | ||
return this; | ||
}, | ||
fail: function(callback) { | ||
this.failCallback = callback; | ||
return this; | ||
}, | ||
always: function(callback) { | ||
this.alwaysCallback = callback; | ||
return this; | ||
} | ||
}; | ||
return api.process(ops); | ||
} | ||
}; | ||
function endsWith(value, suffix) { | ||
@@ -704,4 +616,6 @@ return value.indexOf(suffix, value.length - suffix.length) !== -1; | ||
this._refreshTimeout = null; | ||
this._retry = null; | ||
this._config = { | ||
retry: 3000, | ||
retry: 1000, | ||
maxRetry: 10000, | ||
info: "", | ||
@@ -711,2 +625,3 @@ debug: false, | ||
server: null, | ||
privateChannelPrefix: "$", | ||
protocols_whitelist: [ | ||
@@ -735,7 +650,10 @@ 'websocket', | ||
], | ||
privateChannelPrefix: "$", | ||
refreshEndpoint: "/centrifuge/refresh", | ||
refreshHeaders: {}, | ||
refreshParams: {}, | ||
refreshTransport: "ajax", | ||
authEndpoint: "/centrifuge/auth", | ||
authHeaders: {}, | ||
refreshHeaders: {} | ||
authParams: {}, | ||
authTransport: "ajax" | ||
}; | ||
@@ -749,4 +667,97 @@ if (options) { | ||
Centrifuge._authCallbacks = {}; | ||
Centrifuge._nextAuthCallbackID = 1; | ||
var centrifugeProto = Centrifuge.prototype; | ||
centrifugeProto._jsonp = function (url, params, headers, data, callback) { | ||
if (headers.length > 0) { | ||
this._log("Only AJAX request allows to send custom headers, it's not possible with JSONP."); | ||
} | ||
self._debug("sending JSONP request to", url); | ||
var callbackName = Centrifuge._nextAuthCallbackID.toString(); | ||
Centrifuge._nextAuthCallbackID++; | ||
var document = window.document; | ||
var script = document.createElement("script"); | ||
Centrifuge._authCallbacks[callbackName] = function (data) { | ||
callback(false, data); | ||
delete Centrifuge[callbackName]; | ||
}; | ||
var query = ""; | ||
for (var i in params) { | ||
if (query.length > 0) { | ||
query += "&"; | ||
} | ||
query += encodeURIComponent(i) + "=" + encodeURIComponent(params[i]); | ||
} | ||
var callback_name = "Centrifuge._authCallbacks['" + callbackName + "']"; | ||
script.src = this._config.authEndpoint + | ||
'?callback=' + encodeURIComponent(callback_name) + | ||
'&data=' + encodeURIComponent(JSON.stringify(data)) + | ||
'&' + query; | ||
var head = document.getElementsByTagName("head")[0] || document.documentElement; | ||
head.insertBefore(script, head.firstChild); | ||
}; | ||
centrifugeProto._ajax = function (url, params, headers, data, callback) { | ||
var self = this; | ||
self._debug("sending AJAX request to", url); | ||
var xhr = (window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")); | ||
var query = ""; | ||
for (var i in params) { | ||
if (query.length > 0) { | ||
query += "&"; | ||
} | ||
query += encodeURIComponent(i) + "=" + encodeURIComponent(params[i]); | ||
} | ||
if (query.length > 0) { | ||
query = "?" + query; | ||
} | ||
xhr.open("POST", url + query, true); | ||
// add request headers | ||
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); | ||
xhr.setRequestHeader("Content-Type", "application/json"); | ||
for (var headerName in headers) { | ||
xhr.setRequestHeader(headerName, headers[headerName]); | ||
} | ||
xhr.onreadystatechange = function () { | ||
if (xhr.readyState === 4) { | ||
if (xhr.status === 200) { | ||
var data, parsed = false; | ||
try { | ||
data = JSON.parse(xhr.responseText); | ||
parsed = true; | ||
} catch (e) { | ||
callback(true, 'JSON returned from webapp was invalid, yet status code was 200. Data was: ' + xhr.responseText); | ||
} | ||
if (parsed) { // prevents double execution. | ||
callback(false, data); | ||
} | ||
} else { | ||
self._log("Couldn't get auth info from your webapp", xhr.status); | ||
callback(true, xhr.status); | ||
} | ||
} | ||
}; | ||
setTimeout(function() { | ||
// method == 'get' ? self.xhr.send() : self.xhr.send(JSON.stringify(ops.data)); | ||
xhr.send(JSON.stringify(data)); | ||
}, 20); | ||
return xhr; | ||
}; | ||
centrifugeProto._log = function () { | ||
@@ -775,6 +786,2 @@ log("info", arguments); | ||
if (!this._config.project) { | ||
throw 'Missing required configuration parameter \'project\' specifying project key in server configuration'; | ||
} | ||
if (!this._config.user && this._config.user !== '') { | ||
@@ -861,2 +868,19 @@ if (!this._config.insecure) { | ||
centrifugeProto._resetRetry = function() { | ||
this._debug("reset retry timeout"); | ||
this._retry = null; | ||
}; | ||
centrifugeProto._getRetry = function() { | ||
if (this._retry === null) { | ||
this._retry = this._config.retry + Math.round(Math.random() * 1000); | ||
} else { | ||
this._retry = this._retry + Math.round(Math.random() * 1000); | ||
} | ||
if (this._retry > this._config.maxRetry) { | ||
this._retry = this._config.maxRetry; | ||
} | ||
return this._retry; | ||
}; | ||
centrifugeProto._send = function (messages) { | ||
@@ -921,2 +945,4 @@ // We must be sure that the messages have a clientId. | ||
self._resetRetry(); | ||
var centrifugeMessage = { | ||
@@ -926,3 +952,2 @@ 'method': 'connect', | ||
'user': self._config.user, | ||
'project': self._config.project, | ||
'info': self._config.info | ||
@@ -947,2 +972,4 @@ } | ||
if (self._reconnect === true) { | ||
var retry = self._getRetry(); | ||
self._debug("reconnect after " + retry + " milliseconds"); | ||
window.setTimeout(function () { | ||
@@ -952,3 +979,3 @@ if (self._reconnect === true) { | ||
} | ||
}, self._config.retry); | ||
}, retry); | ||
} | ||
@@ -1003,6 +1030,8 @@ }; | ||
} | ||
var isExpired = message.body.expired; | ||
if (isExpired) { | ||
this.refresh(); | ||
return; | ||
if (message.body.expires) { | ||
var isExpired = message.body.expired; | ||
if (isExpired) { | ||
this.refresh(); | ||
return; | ||
} | ||
} | ||
@@ -1015,3 +1044,3 @@ this._clientId = message.body.client; | ||
} | ||
if (message.body.ttl !== null) { | ||
if (message.body.expires) { | ||
var self = this; | ||
@@ -1153,4 +1182,12 @@ this._refreshTimeout = window.setTimeout(function() { | ||
} | ||
if (message.body.ttl !== null) { | ||
if (message.body.expires) { | ||
var self = this; | ||
var isExpired = message.body.expired; | ||
if (isExpired) { | ||
self._refreshTimeout = window.setTimeout(function(){ | ||
self.refresh.call(self); | ||
}, 3000 + Math.round(Math.random() * 1000)); | ||
return; | ||
} | ||
this._clientId = message.body.client; | ||
self._refreshTimeout = window.setTimeout(function () { | ||
@@ -1324,3 +1361,3 @@ self.refresh.call(self); | ||
"client": this.getClientId(), | ||
"channels[]": channels | ||
"channels": channels | ||
}; | ||
@@ -1330,6 +1367,19 @@ | ||
AJAX.request(this._config.authEndpoint, "post", { | ||
"headers": this._config.authHeaders, | ||
"data": data | ||
}).done(function(data) { | ||
var cb = function(error, data) { | ||
if (error === true) { | ||
self._debug("authorization request failed"); | ||
for (var i in channels) { | ||
var channel = channels[i]; | ||
self._subscribeResponse({ | ||
"error": "authorization request failed", | ||
"body": { | ||
"channel": channel | ||
} | ||
}); | ||
} | ||
if (callback) { | ||
callback(); | ||
} | ||
return; | ||
} | ||
for (var i in channels) { | ||
@@ -1368,20 +1418,15 @@ var channel = channels[i]; | ||
} | ||
}).fail(function() { | ||
self._debug("authorization request failed"); | ||
for (var i in channels) { | ||
var channel = channels[i]; | ||
self._subscribeResponse({ | ||
"error": "authorization request failed", | ||
"body": { | ||
"channel": channel | ||
} | ||
}); | ||
} | ||
return false; | ||
}).always(function(){ | ||
if (callback) { | ||
callback(); | ||
} | ||
}) | ||
}; | ||
var transport = this._config.authTransport.toLowerCase(); | ||
if (transport === "ajax") { | ||
this._ajax(this._config.authEndpoint, this._config.authParams, this._config.authHeaders, data, cb); | ||
} else if (transport === "jsonp") { | ||
this._jsonp(this._config.authEndpoint, this._config.authParams, this._config.authHeaders, data, cb); | ||
} else { | ||
throw 'Unknown auth transport ' + transport; | ||
} | ||
}; | ||
@@ -1461,18 +1506,29 @@ | ||
centrifugeProto.refresh = function () { | ||
// ask web app for connection parameters - project ID, user ID, | ||
// ask web app for connection parameters - user ID, | ||
// timestamp, info and token | ||
var self = this; | ||
this._debug('refresh'); | ||
AJAX.request(this._config.refreshEndpoint, "post", { | ||
"headers": this._config.refreshHeaders, | ||
"data": {} | ||
}).done(function(data) { | ||
this._debug('refresh credentials'); | ||
var cb = function(error, data) { | ||
if (error === true) { | ||
// 403 or 500 - does not matter - if connection check activated then Centrifugo | ||
// will disconnect client eventually | ||
self._debug("error getting connect parameters", data); | ||
if (self._refreshTimeout) { | ||
window.clearTimeout(self._refreshTimeout); | ||
} | ||
self._refreshTimeout = window.setTimeout(function(){ | ||
self.refresh.call(self); | ||
}, 3000); | ||
return; | ||
} | ||
self._config.user = data.user; | ||
self._config.project = data.project; | ||
self._config.timestamp = data.timestamp; | ||
self._config.info = data.info; | ||
self._config.token = data.token; | ||
if (self._reconnect && self.isDisconnected()) { | ||
self.connect(); | ||
if (self.isDisconnected()) { | ||
self._debug("credentials refreshed, connect from scratch"); | ||
self._connect(); | ||
} else { | ||
self._debug("send refreshed credentials"); | ||
var centrifugeMessage = { | ||
@@ -1482,3 +1538,2 @@ "method": "refresh", | ||
'user': self._config.user, | ||
'project': self._config.project, | ||
'timestamp': self._config.timestamp, | ||
@@ -1491,14 +1546,12 @@ 'info': self._config.info, | ||
} | ||
}).fail(function(xhr){ | ||
// 403 or 500 - does not matter - if connection check activated then Centrifuge | ||
// will disconnect client eventually | ||
self._debug(xhr); | ||
self._debug("error getting connect parameters"); | ||
if (self._refreshTimeout) { | ||
window.clearTimeout(self._refreshTimeout); | ||
} | ||
self._refreshTimeout = window.setTimeout(function(){ | ||
self.refresh.call(self); | ||
}, 3000); | ||
}); | ||
}; | ||
var transport = this._config.refreshTransport.toLowerCase(); | ||
if (transport === "ajax") { | ||
this._ajax(this._config.refreshEndpoint, this._config.refreshParams, this._config.refreshHeaders, {}, cb); | ||
} else if (transport === "jsonp") { | ||
this._jsonp(this._config.refreshEndpoint, this._config.refreshParams, this._config.refreshHeaders, {}, cb); | ||
} else { | ||
throw 'Unknown refresh transport ' + transport; | ||
} | ||
}; | ||
@@ -1505,0 +1558,0 @@ |
Sorry, the diff of this file is not supported yet
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
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
153935
0
3162