Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

polling-xhr.js 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /* global attachEvent */
  2. /**
  3. * Module requirements.
  4. */
  5. var XMLHttpRequest = require('xmlhttprequest-ssl');
  6. var Polling = require('./polling');
  7. var Emitter = require('component-emitter');
  8. var inherit = require('component-inherit');
  9. var debug = require('debug')('engine.io-client:polling-xhr');
  10. /**
  11. * Module exports.
  12. */
  13. module.exports = XHR;
  14. module.exports.Request = Request;
  15. /**
  16. * Empty function
  17. */
  18. function empty () {}
  19. /**
  20. * XHR Polling constructor.
  21. *
  22. * @param {Object} opts
  23. * @api public
  24. */
  25. function XHR (opts) {
  26. Polling.call(this, opts);
  27. this.requestTimeout = opts.requestTimeout;
  28. this.extraHeaders = opts.extraHeaders;
  29. if (typeof location !== 'undefined') {
  30. var isSSL = 'https:' === location.protocol;
  31. var port = location.port;
  32. // some user agents have empty `location.port`
  33. if (!port) {
  34. port = isSSL ? 443 : 80;
  35. }
  36. this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
  37. port !== opts.port;
  38. this.xs = opts.secure !== isSSL;
  39. }
  40. }
  41. /**
  42. * Inherits from Polling.
  43. */
  44. inherit(XHR, Polling);
  45. /**
  46. * XHR supports binary
  47. */
  48. XHR.prototype.supportsBinary = true;
  49. /**
  50. * Creates a request.
  51. *
  52. * @param {String} method
  53. * @api private
  54. */
  55. XHR.prototype.request = function (opts) {
  56. opts = opts || {};
  57. opts.uri = this.uri();
  58. opts.xd = this.xd;
  59. opts.xs = this.xs;
  60. opts.agent = this.agent || false;
  61. opts.supportsBinary = this.supportsBinary;
  62. opts.enablesXDR = this.enablesXDR;
  63. opts.withCredentials = this.withCredentials;
  64. // SSL options for Node.js client
  65. opts.pfx = this.pfx;
  66. opts.key = this.key;
  67. opts.passphrase = this.passphrase;
  68. opts.cert = this.cert;
  69. opts.ca = this.ca;
  70. opts.ciphers = this.ciphers;
  71. opts.rejectUnauthorized = this.rejectUnauthorized;
  72. opts.requestTimeout = this.requestTimeout;
  73. // other options for Node.js client
  74. opts.extraHeaders = this.extraHeaders;
  75. return new Request(opts);
  76. };
  77. /**
  78. * Sends data.
  79. *
  80. * @param {String} data to send.
  81. * @param {Function} called upon flush.
  82. * @api private
  83. */
  84. XHR.prototype.doWrite = function (data, fn) {
  85. var isBinary = typeof data !== 'string' && data !== undefined;
  86. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  87. var self = this;
  88. req.on('success', fn);
  89. req.on('error', function (err) {
  90. self.onError('xhr post error', err);
  91. });
  92. this.sendXhr = req;
  93. };
  94. /**
  95. * Starts a poll cycle.
  96. *
  97. * @api private
  98. */
  99. XHR.prototype.doPoll = function () {
  100. debug('xhr poll');
  101. var req = this.request();
  102. var self = this;
  103. req.on('data', function (data) {
  104. self.onData(data);
  105. });
  106. req.on('error', function (err) {
  107. self.onError('xhr poll error', err);
  108. });
  109. this.pollXhr = req;
  110. };
  111. /**
  112. * Request constructor
  113. *
  114. * @param {Object} options
  115. * @api public
  116. */
  117. function Request (opts) {
  118. this.method = opts.method || 'GET';
  119. this.uri = opts.uri;
  120. this.xd = !!opts.xd;
  121. this.xs = !!opts.xs;
  122. this.async = false !== opts.async;
  123. this.data = undefined !== opts.data ? opts.data : null;
  124. this.agent = opts.agent;
  125. this.isBinary = opts.isBinary;
  126. this.supportsBinary = opts.supportsBinary;
  127. this.enablesXDR = opts.enablesXDR;
  128. this.withCredentials = opts.withCredentials;
  129. this.requestTimeout = opts.requestTimeout;
  130. // SSL options for Node.js client
  131. this.pfx = opts.pfx;
  132. this.key = opts.key;
  133. this.passphrase = opts.passphrase;
  134. this.cert = opts.cert;
  135. this.ca = opts.ca;
  136. this.ciphers = opts.ciphers;
  137. this.rejectUnauthorized = opts.rejectUnauthorized;
  138. // other options for Node.js client
  139. this.extraHeaders = opts.extraHeaders;
  140. this.create();
  141. }
  142. /**
  143. * Mix in `Emitter`.
  144. */
  145. Emitter(Request.prototype);
  146. /**
  147. * Creates the XHR object and sends the request.
  148. *
  149. * @api private
  150. */
  151. Request.prototype.create = function () {
  152. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  153. // SSL options for Node.js client
  154. opts.pfx = this.pfx;
  155. opts.key = this.key;
  156. opts.passphrase = this.passphrase;
  157. opts.cert = this.cert;
  158. opts.ca = this.ca;
  159. opts.ciphers = this.ciphers;
  160. opts.rejectUnauthorized = this.rejectUnauthorized;
  161. var xhr = this.xhr = new XMLHttpRequest(opts);
  162. var self = this;
  163. try {
  164. debug('xhr open %s: %s', this.method, this.uri);
  165. xhr.open(this.method, this.uri, this.async);
  166. try {
  167. if (this.extraHeaders) {
  168. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  169. for (var i in this.extraHeaders) {
  170. if (this.extraHeaders.hasOwnProperty(i)) {
  171. xhr.setRequestHeader(i, this.extraHeaders[i]);
  172. }
  173. }
  174. }
  175. } catch (e) {}
  176. if ('POST' === this.method) {
  177. try {
  178. if (this.isBinary) {
  179. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  180. } else {
  181. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  182. }
  183. } catch (e) {}
  184. }
  185. try {
  186. xhr.setRequestHeader('Accept', '*/*');
  187. } catch (e) {}
  188. // ie6 check
  189. if ('withCredentials' in xhr) {
  190. xhr.withCredentials = this.withCredentials;
  191. }
  192. if (this.requestTimeout) {
  193. xhr.timeout = this.requestTimeout;
  194. }
  195. if (this.hasXDR()) {
  196. xhr.onload = function () {
  197. self.onLoad();
  198. };
  199. xhr.onerror = function () {
  200. self.onError(xhr.responseText);
  201. };
  202. } else {
  203. xhr.onreadystatechange = function () {
  204. if (xhr.readyState === 2) {
  205. try {
  206. var contentType = xhr.getResponseHeader('Content-Type');
  207. if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
  208. xhr.responseType = 'arraybuffer';
  209. }
  210. } catch (e) {}
  211. }
  212. if (4 !== xhr.readyState) return;
  213. if (200 === xhr.status || 1223 === xhr.status) {
  214. self.onLoad();
  215. } else {
  216. // make sure the `error` event handler that's user-set
  217. // does not throw in the same tick and gets caught here
  218. setTimeout(function () {
  219. self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
  220. }, 0);
  221. }
  222. };
  223. }
  224. debug('xhr data %s', this.data);
  225. xhr.send(this.data);
  226. } catch (e) {
  227. // Need to defer since .create() is called directly fhrom the constructor
  228. // and thus the 'error' event can only be only bound *after* this exception
  229. // occurs. Therefore, also, we cannot throw here at all.
  230. setTimeout(function () {
  231. self.onError(e);
  232. }, 0);
  233. return;
  234. }
  235. if (typeof document !== 'undefined') {
  236. this.index = Request.requestsCount++;
  237. Request.requests[this.index] = this;
  238. }
  239. };
  240. /**
  241. * Called upon successful response.
  242. *
  243. * @api private
  244. */
  245. Request.prototype.onSuccess = function () {
  246. this.emit('success');
  247. this.cleanup();
  248. };
  249. /**
  250. * Called if we have data.
  251. *
  252. * @api private
  253. */
  254. Request.prototype.onData = function (data) {
  255. this.emit('data', data);
  256. this.onSuccess();
  257. };
  258. /**
  259. * Called upon error.
  260. *
  261. * @api private
  262. */
  263. Request.prototype.onError = function (err) {
  264. this.emit('error', err);
  265. this.cleanup(true);
  266. };
  267. /**
  268. * Cleans up house.
  269. *
  270. * @api private
  271. */
  272. Request.prototype.cleanup = function (fromError) {
  273. if ('undefined' === typeof this.xhr || null === this.xhr) {
  274. return;
  275. }
  276. // xmlhttprequest
  277. if (this.hasXDR()) {
  278. this.xhr.onload = this.xhr.onerror = empty;
  279. } else {
  280. this.xhr.onreadystatechange = empty;
  281. }
  282. if (fromError) {
  283. try {
  284. this.xhr.abort();
  285. } catch (e) {}
  286. }
  287. if (typeof document !== 'undefined') {
  288. delete Request.requests[this.index];
  289. }
  290. this.xhr = null;
  291. };
  292. /**
  293. * Called upon load.
  294. *
  295. * @api private
  296. */
  297. Request.prototype.onLoad = function () {
  298. var data;
  299. try {
  300. var contentType;
  301. try {
  302. contentType = this.xhr.getResponseHeader('Content-Type');
  303. } catch (e) {}
  304. if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
  305. data = this.xhr.response || this.xhr.responseText;
  306. } else {
  307. data = this.xhr.responseText;
  308. }
  309. } catch (e) {
  310. this.onError(e);
  311. }
  312. if (null != data) {
  313. this.onData(data);
  314. }
  315. };
  316. /**
  317. * Check if it has XDomainRequest.
  318. *
  319. * @api private
  320. */
  321. Request.prototype.hasXDR = function () {
  322. return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
  323. };
  324. /**
  325. * Aborts the request.
  326. *
  327. * @api public
  328. */
  329. Request.prototype.abort = function () {
  330. this.cleanup();
  331. };
  332. /**
  333. * Aborts pending requests when unloading the window. This is needed to prevent
  334. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  335. * emitted.
  336. */
  337. Request.requestsCount = 0;
  338. Request.requests = {};
  339. if (typeof document !== 'undefined') {
  340. if (typeof attachEvent === 'function') {
  341. attachEvent('onunload', unloadHandler);
  342. } else if (typeof addEventListener === 'function') {
  343. var terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
  344. addEventListener(terminationEvent, unloadHandler, false);
  345. }
  346. }
  347. function unloadHandler () {
  348. for (var i in Request.requests) {
  349. if (Request.requests.hasOwnProperty(i)) {
  350. Request.requests[i].abort();
  351. }
  352. }
  353. }