eventsource.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /*
  2. * EventSource polyfill version 0.9.6
  3. * Supported by sc AmvTek srl
  4. * :email: devel@amvtek.com
  5. */
  6. ;(function (global) {
  7. if (global.EventSource && !global._eventSourceImportPrefix){
  8. return;
  9. }
  10. var evsImportName = (global._eventSourceImportPrefix||'')+"EventSource";
  11. var EventSource = function (url, options) {
  12. if (!url || typeof url != 'string') {
  13. throw new SyntaxError('Not enough arguments');
  14. }
  15. this.URL = url;
  16. this.setOptions(options);
  17. var evs = this;
  18. setTimeout(function(){evs.poll()}, 0);
  19. };
  20. EventSource.prototype = {
  21. CONNECTING: 0,
  22. OPEN: 1,
  23. CLOSED: 2,
  24. defaultOptions: {
  25. loggingEnabled: false,
  26. loggingPrefix: "eventsource",
  27. interval: 500, // milliseconds
  28. bufferSizeLimit: 256*1024, // bytes
  29. silentTimeout: 300000, // milliseconds
  30. getArgs:{
  31. 'evs_buffer_size_limit': 256*1024
  32. },
  33. xhrHeaders:{
  34. 'Accept': 'text/event-stream',
  35. 'Cache-Control': 'no-cache',
  36. 'X-Requested-With': 'XMLHttpRequest'
  37. }
  38. },
  39. setOptions: function(options){
  40. var defaults = this.defaultOptions;
  41. var option;
  42. // set all default options...
  43. for (option in defaults){
  44. if ( defaults.hasOwnProperty(option) ){
  45. this[option] = defaults[option];
  46. }
  47. }
  48. // override with what is in options
  49. for (option in options){
  50. if (option in defaults && options.hasOwnProperty(option)){
  51. this[option] = options[option];
  52. }
  53. }
  54. // if getArgs option is enabled
  55. // ensure evs_buffer_size_limit corresponds to bufferSizeLimit
  56. if (this.getArgs && this.bufferSizeLimit) {
  57. this.getArgs['evs_buffer_size_limit'] = this.bufferSizeLimit;
  58. }
  59. // if console is not available, force loggingEnabled to false
  60. if (typeof console === "undefined" || typeof console.log === "undefined") {
  61. this.loggingEnabled = false;
  62. }
  63. },
  64. log: function(message) {
  65. if (this.loggingEnabled) {
  66. console.log("[" + this.loggingPrefix +"]:" + message)
  67. }
  68. },
  69. poll: function() {
  70. try {
  71. if (this.readyState == this.CLOSED) {
  72. return;
  73. }
  74. this.cleanup();
  75. this.readyState = this.CONNECTING;
  76. this.cursor = 0;
  77. this.cache = '';
  78. this._xhr = new this.XHR(this);
  79. this.resetNoActivityTimer();
  80. }
  81. catch (e) {
  82. // in an attempt to silence the errors
  83. this.log('There were errors inside the pool try-catch');
  84. this.dispatchEvent('error', { type: 'error', data: e.message });
  85. }
  86. },
  87. pollAgain: function (interval) {
  88. // schedule poll to be called after interval milliseconds
  89. var evs = this;
  90. evs.readyState = evs.CONNECTING;
  91. evs.dispatchEvent('error', {
  92. type: 'error',
  93. data: "Reconnecting "
  94. });
  95. this._pollTimer = setTimeout(function(){evs.poll()}, interval||0);
  96. },
  97. cleanup: function() {
  98. this.log('evs cleaning up')
  99. if (this._pollTimer){
  100. clearInterval(this._pollTimer);
  101. this._pollTimer = null;
  102. }
  103. if (this._noActivityTimer){
  104. clearInterval(this._noActivityTimer);
  105. this._noActivityTimer = null;
  106. }
  107. if (this._xhr){
  108. this._xhr.abort();
  109. this._xhr = null;
  110. }
  111. },
  112. resetNoActivityTimer: function(){
  113. if (this.silentTimeout){
  114. if (this._noActivityTimer){
  115. clearInterval(this._noActivityTimer);
  116. }
  117. var evs = this;
  118. this._noActivityTimer = setTimeout(
  119. function(){ evs.log('Timeout! silentTImeout:'+evs.silentTimeout); evs.pollAgain(); },
  120. this.silentTimeout
  121. );
  122. }
  123. },
  124. close: function () {
  125. this.readyState = this.CLOSED;
  126. this.log('Closing connection. readyState: '+this.readyState);
  127. this.cleanup();
  128. },
  129. ondata: function() {
  130. var request = this._xhr;
  131. if (request.isReady() && !request.hasError() ) {
  132. // reset the timer, as we have activity
  133. this.resetNoActivityTimer();
  134. // move this EventSource to OPEN state...
  135. if (this.readyState == this.CONNECTING) {
  136. this.readyState = this.OPEN;
  137. this.dispatchEvent('open', { type: 'open' });
  138. }
  139. var buffer = request.getBuffer();
  140. if (buffer.length > this.bufferSizeLimit) {
  141. this.log('buffer.length > this.bufferSizeLimit');
  142. this.pollAgain();
  143. }
  144. if (this.cursor == 0 && buffer.length > 0){
  145. // skip byte order mark \uFEFF character if it starts the stream
  146. if (buffer.substring(0,1) == '\uFEFF'){
  147. this.cursor = 1;
  148. }
  149. }
  150. var lastMessageIndex = this.lastMessageIndex(buffer);
  151. if (lastMessageIndex[0] >= this.cursor){
  152. var newcursor = lastMessageIndex[1];
  153. var toparse = buffer.substring(this.cursor, newcursor);
  154. this.parseStream(toparse);
  155. this.cursor = newcursor;
  156. }
  157. // if request is finished, reopen the connection
  158. if (request.isDone()) {
  159. this.log('request.isDone(). reopening the connection');
  160. this.pollAgain(this.interval);
  161. }
  162. }
  163. else if (this.readyState !== this.CLOSED) {
  164. this.log('this.readyState !== this.CLOSED');
  165. this.pollAgain(this.interval);
  166. //MV: Unsure why an error was previously dispatched
  167. }
  168. },
  169. parseStream: function(chunk) {
  170. // normalize line separators (\r\n,\r,\n) to \n
  171. // remove white spaces that may precede \n
  172. chunk = this.cache + this.normalizeToLF(chunk);
  173. var events = chunk.split('\n\n');
  174. var i, j, eventType, datas, line, retry;
  175. for (i=0; i < (events.length - 1); i++) {
  176. eventType = 'message';
  177. datas = [];
  178. parts = events[i].split('\n');
  179. for (j=0; j < parts.length; j++) {
  180. line = this.trimWhiteSpace(parts[j]);
  181. if (line.indexOf('event') == 0) {
  182. eventType = line.replace(/event:?\s*/, '');
  183. }
  184. else if (line.indexOf('retry') == 0) {
  185. retry = parseInt(line.replace(/retry:?\s*/, ''));
  186. if(!isNaN(retry)) {
  187. this.interval = retry;
  188. }
  189. }
  190. else if (line.indexOf('data') == 0) {
  191. datas.push(line.replace(/data:?\s*/, ''));
  192. }
  193. else if (line.indexOf('id:') == 0) {
  194. this.lastEventId = line.replace(/id:?\s*/, '');
  195. }
  196. else if (line.indexOf('id') == 0) { // this resets the id
  197. this.lastEventId = null;
  198. }
  199. }
  200. if (datas.length) {
  201. // dispatch a new event
  202. var event = new MessageEvent(eventType, datas.join('\n'), window.location.origin, this.lastEventId);
  203. this.dispatchEvent(eventType, event);
  204. }
  205. }
  206. this.cache = events[events.length - 1];
  207. },
  208. dispatchEvent: function (type, event) {
  209. var handlers = this['_' + type + 'Handlers'];
  210. if (handlers) {
  211. for (var i = 0; i < handlers.length; i++) {
  212. handlers[i].call(this, event);
  213. }
  214. }
  215. if (this['on' + type]) {
  216. this['on' + type].call(this, event);
  217. }
  218. },
  219. addEventListener: function (type, handler) {
  220. if (!this['_' + type + 'Handlers']) {
  221. this['_' + type + 'Handlers'] = [];
  222. }
  223. this['_' + type + 'Handlers'].push(handler);
  224. },
  225. removeEventListener: function (type, handler) {
  226. var handlers = this['_' + type + 'Handlers'];
  227. if (!handlers) {
  228. return;
  229. }
  230. for (var i = handlers.length - 1; i >= 0; --i) {
  231. if (handlers[i] === handler) {
  232. handlers.splice(i, 1);
  233. break;
  234. }
  235. }
  236. },
  237. _pollTimer: null,
  238. _noactivityTimer: null,
  239. _xhr: null,
  240. lastEventId: null,
  241. cache: '',
  242. cursor: 0,
  243. onerror: null,
  244. onmessage: null,
  245. onopen: null,
  246. readyState: 0,
  247. // ===================================================================
  248. // helpers functions
  249. // those are attached to prototype to ease reuse and testing...
  250. urlWithParams: function (baseURL, params) {
  251. var encodedArgs = [];
  252. if (params){
  253. var key, urlarg;
  254. var urlize = encodeURIComponent;
  255. for (key in params){
  256. if (params.hasOwnProperty(key)) {
  257. urlarg = urlize(key)+'='+urlize(params[key]);
  258. encodedArgs.push(urlarg);
  259. }
  260. }
  261. }
  262. if (encodedArgs.length > 0){
  263. if (baseURL.indexOf('?') == -1)
  264. return baseURL + '?' + encodedArgs.join('&');
  265. return baseURL + '&' + encodedArgs.join('&');
  266. }
  267. return baseURL;
  268. },
  269. lastMessageIndex: function(text) {
  270. var ln2 =text.lastIndexOf('\n\n');
  271. var lr2 = text.lastIndexOf('\r\r');
  272. var lrln2 = text.lastIndexOf('\r\n\r\n');
  273. if (lrln2 > Math.max(ln2, lr2)) {
  274. return [lrln2, lrln2+4];
  275. }
  276. return [Math.max(ln2, lr2), Math.max(ln2, lr2) + 2]
  277. },
  278. trimWhiteSpace: function(str) {
  279. // to remove whitespaces left and right of string
  280. var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
  281. return str.replace(reTrim, '');
  282. },
  283. normalizeToLF: function(str) {
  284. // replace \r and \r\n with \n
  285. return str.replace(/\r\n|\r/g, '\n');
  286. }
  287. };
  288. if (!isOldIE()){
  289. EventSource.isPolyfill = "XHR";
  290. // EventSource will send request using XMLHttpRequest
  291. EventSource.prototype.XHR = function(evs) {
  292. request = new XMLHttpRequest();
  293. this._request = request;
  294. evs._xhr = this;
  295. // set handlers
  296. request.onreadystatechange = function(){
  297. if (request.readyState > 1 && evs.readyState != evs.CLOSED) {
  298. if (request.status == 200 || (request.status>=300 && request.status<400)){
  299. evs.ondata();
  300. }
  301. else {
  302. request._failed = true;
  303. evs.readyState = evs.CLOSED;
  304. evs.dispatchEvent('error', {
  305. type: 'error',
  306. data: "The server responded with "+request.status
  307. });
  308. evs.close();
  309. }
  310. }
  311. };
  312. request.onprogress = function () {
  313. };
  314. request.open('GET', evs.urlWithParams(evs.URL, evs.getArgs), true);
  315. var headers = evs.xhrHeaders; // maybe null
  316. for (var header in headers) {
  317. if (headers.hasOwnProperty(header)){
  318. request.setRequestHeader(header, headers[header]);
  319. }
  320. }
  321. if (evs.lastEventId) {
  322. request.setRequestHeader('Last-Event-Id', evs.lastEventId);
  323. }
  324. request.send();
  325. };
  326. EventSource.prototype.XHR.prototype = {
  327. useXDomainRequest: false,
  328. _request: null,
  329. _failed: false, // true if we have had errors...
  330. isReady: function() {
  331. return this._request.readyState >= 2;
  332. },
  333. isDone: function() {
  334. return (this._request.readyState == 4);
  335. },
  336. hasError: function() {
  337. return (this._failed || (this._request.status >= 400));
  338. },
  339. getBuffer: function() {
  340. var rv = '';
  341. try {
  342. rv = this._request.responseText || '';
  343. }
  344. catch (e){}
  345. return rv;
  346. },
  347. abort: function() {
  348. if ( this._request ) {
  349. this._request.abort();
  350. }
  351. }
  352. };
  353. }
  354. else {
  355. EventSource.isPolyfill = "IE_8-9";
  356. // patch EventSource defaultOptions
  357. var defaults = EventSource.prototype.defaultOptions;
  358. defaults.xhrHeaders = null; // no headers will be sent
  359. defaults.getArgs['evs_preamble'] = 2048 + 8;
  360. // EventSource will send request using Internet Explorer XDomainRequest
  361. EventSource.prototype.XHR = function(evs) {
  362. request = new XDomainRequest();
  363. this._request = request;
  364. // set handlers
  365. request.onprogress = function(){
  366. request._ready = true;
  367. evs.ondata();
  368. };
  369. request.onload = function(){
  370. this._loaded = true;
  371. evs.ondata();
  372. };
  373. request.onerror = function(){
  374. this._failed = true;
  375. evs.readyState = evs.CLOSED;
  376. evs.dispatchEvent('error', {
  377. type: 'error',
  378. data: "XDomainRequest error"
  379. });
  380. };
  381. request.ontimeout = function(){
  382. this._failed = true;
  383. evs.readyState = evs.CLOSED;
  384. evs.dispatchEvent('error', {
  385. type: 'error',
  386. data: "XDomainRequest timed out"
  387. });
  388. };
  389. // XDomainRequest does not allow setting custom headers
  390. // If EventSource has enabled the use of GET arguments
  391. // we add parameters to URL so that server can adapt the stream...
  392. var reqGetArgs = {};
  393. if (evs.getArgs) {
  394. // copy evs.getArgs in reqGetArgs
  395. var defaultArgs = evs.getArgs;
  396. for (var key in defaultArgs) {
  397. if (defaultArgs.hasOwnProperty(key)){
  398. reqGetArgs[key] = defaultArgs[key];
  399. }
  400. }
  401. if (evs.lastEventId){
  402. reqGetArgs['evs_last_event_id'] = evs.lastEventId;
  403. }
  404. }
  405. // send the request
  406. request.open('GET', evs.urlWithParams(evs.URL,reqGetArgs));
  407. request.send();
  408. };
  409. EventSource.prototype.XHR.prototype = {
  410. useXDomainRequest: true,
  411. _request: null,
  412. _ready: false, // true when progress events are dispatched
  413. _loaded: false, // true when request has been loaded
  414. _failed: false, // true if when request is in error
  415. isReady: function() {
  416. return this._request._ready;
  417. },
  418. isDone: function() {
  419. return this._request._loaded;
  420. },
  421. hasError: function() {
  422. return this._request._failed;
  423. },
  424. getBuffer: function() {
  425. var rv = '';
  426. try {
  427. rv = this._request.responseText || '';
  428. }
  429. catch (e){}
  430. return rv;
  431. },
  432. abort: function() {
  433. if ( this._request){
  434. this._request.abort();
  435. }
  436. }
  437. };
  438. }
  439. function MessageEvent(type, data, origin, lastEventId) {
  440. this.bubbles = false;
  441. this.cancelBubble = false;
  442. this.cancelable = false;
  443. this.data = data || null;
  444. this.origin = origin || '';
  445. this.lastEventId = lastEventId || '';
  446. this.type = type || 'message';
  447. }
  448. function isOldIE () {
  449. //return true if we are in IE8 or IE9
  450. return (window.XDomainRequest && (window.XMLHttpRequest && new XMLHttpRequest().responseType === undefined)) ? true : false;
  451. }
  452. global[evsImportName] = EventSource;
  453. })(this);