Advertisement
Guest User

Untitled

a guest
Feb 21st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.32 KB | None | 0 0
  1.  
  2. var XMLHttpRequestInternal = XMLHttpRequest;
  3. var XMLHttpRequestInternalPrototype = XMLHttpRequest.prototype;
  4.  
  5. var _Event = function Event(type, bubbles, cancelable, target) {
  6. this.type = type;
  7. this.bubbles = bubbles;
  8. this.cancelable = cancelable;
  9. this.target = target;
  10. this.currentTarget = target;
  11. };
  12.  
  13. _Event.prototype = {
  14. stopPropagation: function () {},
  15. preventDefault: function () {
  16. this.defaultPrevented = true;
  17. }
  18. };
  19.  
  20. /*
  21. Used to set the statusText property of an xhr object
  22. */
  23. var httpStatusCodes = {
  24. 100: "Continue",
  25. 101: "Switching Protocols",
  26. 200: "OK",
  27. 201: "Created",
  28. 202: "Accepted",
  29. 203: "Non-Authoritative Information",
  30. 204: "No Content",
  31. 205: "Reset Content",
  32. 206: "Partial Content",
  33. 300: "Multiple Choice",
  34. 301: "Moved Permanently",
  35. 302: "Found",
  36. 303: "See Other",
  37. 304: "Not Modified",
  38. 305: "Use Proxy",
  39. 307: "Temporary Redirect",
  40. 400: "Bad Request",
  41. 401: "Unauthorized",
  42. 402: "Payment Required",
  43. 403: "Forbidden",
  44. 404: "Not Found",
  45. 405: "Method Not Allowed",
  46. 406: "Not Acceptable",
  47. 407: "Proxy Authentication Required",
  48. 408: "Request Timeout",
  49. 409: "Conflict",
  50. 410: "Gone",
  51. 411: "Length Required",
  52. 412: "Precondition Failed",
  53. 413: "Request Entity Too Large",
  54. 414: "Request-URI Too Long",
  55. 415: "Unsupported Media Type",
  56. 416: "Requested Range Not Satisfiable",
  57. 417: "Expectation Failed",
  58. 422: "Unprocessable Entity",
  59. 500: "Internal Server Error",
  60. 501: "Not Implemented",
  61. 502: "Bad Gateway",
  62. 503: "Service Unavailable",
  63. 504: "Gateway Timeout",
  64. 505: "HTTP Version Not Supported"
  65. };
  66.  
  67.  
  68. /*
  69. Cross-browser XML parsing. Used to turn
  70. XML responses into Document objects
  71. Borrowed from JSpec
  72. */
  73. function parseXML(text) {
  74. var xmlDoc;
  75.  
  76. if (typeof DOMParser != "undefined") {
  77. var parser = new DOMParser();
  78. xmlDoc = parser.parseFromString(text, "text/xml");
  79. } else {
  80. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  81. xmlDoc.async = "false";
  82. xmlDoc.loadXML(text);
  83. }
  84.  
  85. return xmlDoc;
  86. }
  87.  
  88. /*
  89. Without mocking, the native XMLHttpRequest object will throw
  90. an error when attempting to set these headers. We match this behavior.
  91. */
  92. var unsafeHeaders = {
  93. "Accept-Charset": true,
  94. "Accept-Encoding": true,
  95. "Connection": true,
  96. "Content-Length": true,
  97. "Cookie": true,
  98. "Cookie2": true,
  99. "Content-Transfer-Encoding": true,
  100. "Date": true,
  101. "Expect": true,
  102. "Host": true,
  103. "Keep-Alive": true,
  104. "Referer": true,
  105. "TE": true,
  106. "Trailer": true,
  107. "Transfer-Encoding": true,
  108. "Upgrade": true,
  109. "User-Agent": true,
  110. "Via": true
  111. };
  112.  
  113. /*
  114. Adds an "event" onto the xhr object
  115. that just calls the same-named method. This is
  116. in case a library adds callbacks for these events.
  117. */
  118. function _addEventListener(eventName, xhr){
  119. xhr.addEventListener(eventName, function (event) {
  120. var listener = xhr["on" + eventName];
  121.  
  122. if (listener && typeof listener == "function") {
  123. listener.call(event.target, event);
  124. }
  125. });
  126. }
  127.  
  128. function EventedObject() {
  129. this._eventListeners = {};
  130. var events = ["loadstart", "progress", "load", "abort", "loadend"];
  131. for (var i = events.length - 1; i >= 0; i--) {
  132. _addEventListener(events[i], this);
  133. }
  134. };
  135.  
  136. EventedObject.prototype = {
  137. /*
  138. Duplicates the behavior of native XMLHttpRequest's addEventListener function
  139. */
  140. addEventListener: function addEventListener(event, listener) {
  141. this._eventListeners[event] = this._eventListeners[event] || [];
  142. this._eventListeners[event].push(listener);
  143. },
  144.  
  145. /*
  146. Duplicates the behavior of native XMLHttpRequest's removeEventListener function
  147. */
  148. removeEventListener: function removeEventListener(event, listener) {
  149. var listeners = this._eventListeners[event] || [];
  150.  
  151. for (var i = 0, l = listeners.length; i < l; ++i) {
  152. if (listeners[i] == listener) {
  153. return listeners.splice(i, 1);
  154. }
  155. }
  156. },
  157.  
  158. /*
  159. Duplicates the behavior of native XMLHttpRequest's dispatchEvent function
  160. */
  161. dispatchEvent: function dispatchEvent(event) {
  162. var type = event.type;
  163. var listeners = this._eventListeners[type] || [];
  164.  
  165. for (var i = 0; i < listeners.length; i++) {
  166. if (typeof listeners[i] == "function") {
  167. listeners[i].call(this, event);
  168. } else {
  169. listeners[i].handleEvent(event);
  170. }
  171. }
  172.  
  173. return !!event.defaultPrevented;
  174. },
  175.  
  176. /*
  177. Triggers an `onprogress` event with the given parameters.
  178. */
  179. _progress: function _progress(lengthComputable, loaded, total) {
  180. var event = new _Event('progress');
  181. event.target = this;
  182. event.lengthComputable = lengthComputable;
  183. event.loaded = loaded;
  184. event.total = total;
  185. this.dispatchEvent(event);
  186. }
  187. }
  188.  
  189. /*
  190. Constructor for a window.XMLHttpRequest
  191. */
  192. XMLHttpRequest = function() {
  193. EventedObject.call(this);
  194. this.readyState = XMLHttpRequest.UNSENT;
  195. this.requestHeaders = {};
  196. this.requestBody = null;
  197. this.status = 0;
  198. this.statusText = "";
  199. this.upload = new EventedObject();
  200. }
  201.  
  202. XMLHttpRequest.prototype = new EventedObject();
  203.  
  204. // These status codes are available on the native XMLHttpRequest
  205. // object, so we match that here in case a library is relying on them.
  206. XMLHttpRequest.UNSENT = 0;
  207. XMLHttpRequest.OPENED = 1;
  208. XMLHttpRequest.HEADERS_RECEIVED = 2;
  209. XMLHttpRequest.LOADING = 3;
  210. XMLHttpRequest.DONE = 4;
  211.  
  212. var XMLHttpRequestProto = {
  213. UNSENT: 0,
  214. OPENED: 1,
  215. HEADERS_RECEIVED: 2,
  216. LOADING: 3,
  217. DONE: 4,
  218. async: true,
  219. withCredentials: false,
  220. timeout: 0,
  221.  
  222. /*
  223. Duplicates the behavior of native XMLHttpRequest's open function
  224. */
  225. open: function open(method, url, async, username, password) {
  226. this.method = method;
  227. this.url = url;
  228. this.async = typeof async == "boolean" ? async : true;
  229. this.username = username;
  230. this.password = password;
  231. this.responseText = null;
  232. this.responseXML = null;
  233. this.requestHeaders = {};
  234. this.sendFlag = false;
  235. this._readyStateChange(XMLHttpRequest.OPENED);
  236. },
  237.  
  238. /*
  239. Duplicates the behavior of native XMLHttpRequest's setRequestHeader function
  240. */
  241. setRequestHeader: function setRequestHeader(header, value) {
  242. verifyState(this);
  243.  
  244. if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
  245. throw new Error("Refused to set unsafe header \"" + header + "\"");
  246. }
  247.  
  248. if (this.requestHeaders[header]) {
  249. this.requestHeaders[header] += "," + value;
  250. } else {
  251. this.requestHeaders[header] = value;
  252. }
  253. },
  254.  
  255. /*
  256. Duplicates the behavior of native XMLHttpRequest's send function
  257. */
  258. send: function send(data) {
  259. verifyState(this);
  260.  
  261. if (!/^(get|head)$/i.test(this.method)) {
  262. var hasContentTypeHeader = false
  263.  
  264. Object.keys(this.requestHeaders).forEach(function (key) {
  265. if (key.toLowerCase() === 'content-type') {
  266. hasContentTypeHeader = true;
  267. }
  268. });
  269.  
  270. if (!hasContentTypeHeader && !(data || '').toString().match('FormData')) {
  271. this.requestHeaders["Content-Type"] = "text/plain;charset=UTF-8";
  272. }
  273.  
  274. this.requestBody = data;
  275. }
  276.  
  277. this.errorFlag = false;
  278. this.sendFlag = this.async;
  279. this._readyStateChange(XMLHttpRequest.OPENED);
  280.  
  281. if (typeof this.onSend == "function") {
  282. this.onSend(this);
  283. }
  284.  
  285. this.dispatchEvent(new _Event("loadstart", false, false, this));
  286. },
  287.  
  288. onSend: function onSend() {
  289. let this_ref = this;
  290.  
  291. var link = document.createElement("a");
  292. link.href = this.url;
  293.  
  294. let url = link.protocol+"//"+link.host+link.pathname+link.search+link.hash;
  295.  
  296. if((url.includes("vod.dori") == false && url.includes("video.dori") == false) || this.async == false) {
  297. let xhr = new XMLHttpRequestInternal();
  298.  
  299. if(this.responseType) {
  300. xhr.responseType = this.responseType;
  301. }
  302.  
  303. if(this.forceMimeType) {
  304. xhr.overrideMimeType(this.forceMimeType);
  305. }
  306.  
  307. if(this.async) {
  308. xhr.onload = function(event) {
  309. if(xhr.readyState == 4) {
  310. this_ref.respond(xhr.status, xhr.getAllResponseHeaders(), xhr.response);
  311. }
  312. }
  313. }
  314.  
  315. xhr.onerror = function(exception) {
  316. this_ref.dispatchEvent(exception);
  317. }
  318.  
  319. xhr.onprogress = function(event) {
  320. this_ref.dispatchEvent(event);
  321. }
  322.  
  323. xhr.ontimeout = function(event) {
  324. this_ref.dispatchEvent(event);
  325. }
  326.  
  327. xhr.onabort = function(event) {
  328. this_ref.dispatchEvent(event);
  329. }
  330.  
  331. xhr.open(this_ref.method, this_ref.url, this_ref.async, this_ref.user, this_ref.password);
  332.  
  333. Object.keys(this.requestHeaders).forEach(function (key) {
  334. xhr.setRequestHeader(key, this.requestHeaders[key]);
  335. });
  336.  
  337. if(this_ref.async) {
  338. xhr.timeout = this_ref.timeout;
  339. }
  340.  
  341. xhr.send(this.requestBody);
  342.  
  343. if(!this_ref.async) {
  344. this_ref.respond(xhr.status, xhr.getAllResponseHeaders(), xhr.response);
  345. }
  346.  
  347. } else {
  348.  
  349. if(!this_ref.async) {
  350. console.log("XHR attempting to do a synchronous request but webrtc doesn't support it");
  351. debugger;
  352. }
  353.  
  354. url = url + "&good=1";
  355.  
  356. let has_content_type = false;
  357.  
  358. let headers = [];
  359.  
  360. Object.keys(this.requestHeaders).forEach(function (key) {
  361. headers.push(key + ": " + this_ref.requestHeaders[key]);
  362. if(this_ref.requestHeaders[key].toLowerCase() == "content-type") {
  363. has_content_type = false;
  364. }
  365. });
  366.  
  367. if(has_content_type == false) {
  368. if(typeof(this.requestBody) === "string") {
  369. headers.push("Content-Type: application/text");
  370. }
  371. }
  372. requester.request(this_ref.method, url, this.requestBody, headers).then(function(http) {
  373. this_ref.respond(http.status, http.getAllResponseHeaders(), http.responseText);
  374. }, function(exception) {
  375.  
  376. this_ref.dispatchEvent(new _Event("error", false, false, this));
  377. this_ref.dispatchEvent(new _Event("loadend", false, false, this));
  378. });
  379. }
  380. },
  381.  
  382. /*
  383. Duplicates the behavior of native XMLHttpRequest's abort function
  384. */
  385. abort: function abort() {
  386. this.aborted = true;
  387. this.responseText = null;
  388. this.errorFlag = true;
  389. this.requestHeaders = {};
  390.  
  391. if (this.readyState > XMLHttpRequest.UNSENT && this.sendFlag) {
  392. this._readyStateChange(XMLHttpRequest.DONE);
  393. this.sendFlag = false;
  394. }
  395.  
  396. this.readyState = XMLHttpRequest.UNSENT;
  397.  
  398. this.dispatchEvent(new _Event("abort", false, false, this));
  399. if (typeof this.onerror === "function") {
  400. this.onerror();
  401. }
  402. },
  403.  
  404. /*
  405. Duplicates the behavior of native XMLHttpRequest's getResponseHeader function
  406. */
  407. getResponseHeader: function getResponseHeader(header) {
  408. if (this.readyState < XMLHttpRequest.HEADERS_RECEIVED) {
  409. return null;
  410. }
  411.  
  412. if (/^Set-Cookie2?$/i.test(header)) {
  413. return null;
  414. }
  415.  
  416. header = header.toLowerCase();
  417.  
  418. for (var h in this.responseHeaders) {
  419. if (h.toLowerCase() == header) {
  420. return this.responseHeaders[h];
  421. }
  422. }
  423.  
  424. return null;
  425. },
  426.  
  427. /*
  428. Duplicates the behavior of native XMLHttpRequest's getAllResponseHeaders function
  429. */
  430. getAllResponseHeaders: function getAllResponseHeaders() {
  431. if (this.readyState < XMLHttpRequest.HEADERS_RECEIVED) {
  432. return "";
  433. }
  434.  
  435. var headers = "";
  436.  
  437. for (var header in this.responseHeaders) {
  438. if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) {
  439. headers += header + ": " + this.responseHeaders[header] + "\r\n";
  440. }
  441. }
  442.  
  443. return headers;
  444. },
  445.  
  446. /*
  447. Duplicates the behavior of native XMLHttpRequest's overrideMimeType function
  448. */
  449. overrideMimeType: function overrideMimeType(mimeType) {
  450. if (typeof mimeType === "string") {
  451. this.forceMimeType = mimeType.toLowerCase();
  452. }
  453. },
  454.  
  455.  
  456. /*
  457. Places a XMLHttpRequest object into the passed
  458. state.
  459. */
  460. _readyStateChange: function _readyStateChange(state) {
  461. this.readyState = state;
  462.  
  463. if (typeof this.onreadystatechange == "function") {
  464. this.onreadystatechange(new _Event("readystatechange"));
  465. }
  466.  
  467. this.dispatchEvent(new _Event("readystatechange"));
  468.  
  469. if (this.readyState == XMLHttpRequest.DONE) {
  470. this.dispatchEvent(new _Event("load", false, false, this));
  471. this.dispatchEvent(new _Event("loadend", false, false, this));
  472. }
  473. },
  474.  
  475.  
  476. /*
  477. Sets theXMLHttpRequest object's response headers and
  478. places the object into readyState 2
  479. */
  480. _setResponseHeaders: function _setResponseHeaders(headers) {
  481. this.responseHeaders = {};
  482.  
  483. for (var header in headers) {
  484. if (headers.hasOwnProperty(header)) {
  485. this.responseHeaders[header] = headers[header];
  486. }
  487. }
  488.  
  489. if (this.forceMimeType) {
  490. this.responseHeaders['Content-Type'] = this.forceMimeType;
  491. }
  492.  
  493. if (this.async) {
  494. this._readyStateChange(XMLHttpRequest.HEADERS_RECEIVED);
  495. } else {
  496. this.readyState = XMLHttpRequest.HEADERS_RECEIVED;
  497. }
  498. },
  499.  
  500. /*
  501. Sets the XMLHttpRequest object's response body and
  502. if body text is XML, sets responseXML to parsed document
  503. object
  504. */
  505. _setResponseBody: function _setResponseBody(body) {
  506. verifyRequestSent(this);
  507. verifyHeadersReceived(this);
  508. verifyResponseBodyType(body);
  509.  
  510. var chunkSize = this.chunkSize || 10;
  511. var index = 0;
  512. this.responseText = "";
  513.  
  514. do {
  515. if (this.async) {
  516. this._readyStateChange(XMLHttpRequest.LOADING);
  517. }
  518.  
  519. this.responseText += body.substring(index, index + chunkSize);
  520. index += chunkSize;
  521. } while (index < body.length);
  522.  
  523. var type = this.getResponseHeader("Content-Type");
  524.  
  525. if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
  526. try {
  527. this.responseXML = parseXML(this.responseText);
  528. } catch (e) {
  529. // Unable to parse XML - no biggie
  530. }
  531. }
  532.  
  533. if (this.async) {
  534. this._readyStateChange(XMLHttpRequest.DONE);
  535. } else {
  536. this.readyState = XMLHttpRequest.DONE;
  537. }
  538. },
  539.  
  540. /*
  541. Forces a response on to the XMLHttpRequest object.
  542.  
  543. This is the public API for faking responses. This function
  544. takes a number status, headers object, and string body:
  545.  
  546. ```
  547. xhr.respond(404, {Content-Type: 'text/plain'}, "Sorry. This object was not found.")
  548.  
  549. ```
  550. */
  551. respond: function respond(status, headers, body) {
  552. this._setResponseHeaders(headers || {});
  553. this.status = typeof status == "number" ? status : 200;
  554. this.statusText = httpStatusCodes[this.status];
  555. this._setResponseBody(body || "");
  556. }
  557. };
  558.  
  559. for (var property in XMLHttpRequestProto) {
  560. XMLHttpRequest.prototype[property] = XMLHttpRequestProto[property];
  561. }
  562.  
  563. function verifyState(xhr) {
  564. if (xhr.readyState !== XMLHttpRequest.OPENED) {
  565. throw new Error("INVALID_STATE_ERR");
  566. }
  567.  
  568. if (xhr.sendFlag) {
  569. throw new Error("INVALID_STATE_ERR");
  570. }
  571. }
  572.  
  573.  
  574. function verifyRequestSent(xhr) {
  575. if (xhr.readyState == XMLHttpRequest.DONE) {
  576. throw new Error("Request done");
  577. }
  578. }
  579.  
  580. function verifyHeadersReceived(xhr) {
  581. if (xhr.async && xhr.readyState != XMLHttpRequest.HEADERS_RECEIVED) {
  582. throw new Error("No headers received");
  583. }
  584. }
  585.  
  586. function verifyResponseBodyType(body) {
  587. if (typeof body != "string") {
  588. var error = new Error("Attempted to respond to XMLHttpRequest with " +
  589. body + ", which is not a string.");
  590. error.name = "InvalidBodyException";
  591. throw error;
  592. }
  593. }
  594.  
  595. for(let index = 0; index < 1000; index += 1) {
  596. let xmlhttp = new XMLHttpRequest(),
  597. method = 'GET',
  598. url = 'http://localhost:8000/index.html';
  599.  
  600. xmlhttp.open(method, url, true);
  601. xmlhttp.onload = function () {
  602. console.log(xmlhttp.responseText);
  603. };
  604. xmlhttp.onerror = function () {
  605. console.log(this._url);
  606. };
  607. xmlhttp.send("test" + index);
  608. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement