Source: lib/net/http_xhr_plugin.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.net.HttpXHRPlugin');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.net.HttpPluginUtils');
  9. goog.require('shaka.net.NetworkingEngine');
  10. goog.require('shaka.util.AbortableOperation');
  11. goog.require('shaka.util.Error');
  12. /**
  13. * @summary A networking plugin to handle http and https URIs via XHR.
  14. * @export
  15. */
  16. shaka.net.HttpXHRPlugin = class {
  17. /**
  18. * @param {string} uri
  19. * @param {shaka.extern.Request} request
  20. * @param {shaka.net.NetworkingEngine.RequestType} requestType
  21. * @param {shaka.extern.ProgressUpdated} progressUpdated Called when a
  22. * progress event happened.
  23. * @param {shaka.extern.HeadersReceived} headersReceived Called when the
  24. * headers for the download are received, but before the body is.
  25. * @param {shaka.extern.SchemePluginConfig} config
  26. * @return {!shaka.extern.IAbortableOperation.<shaka.extern.Response>}
  27. * @export
  28. */
  29. static parse(uri, request, requestType, progressUpdated, headersReceived,
  30. config) {
  31. const xhr = new shaka.net.HttpXHRPlugin.Xhr_();
  32. // Last time stamp when we got a progress event.
  33. let lastTime = Date.now();
  34. // Last number of bytes loaded, from progress event.
  35. let lastLoaded = 0;
  36. const promise = new Promise(((resolve, reject) => {
  37. xhr.open(request.method, uri, true);
  38. xhr.responseType = 'arraybuffer';
  39. xhr.timeout = request.retryParameters.timeout;
  40. xhr.withCredentials = request.allowCrossSiteCredentials;
  41. xhr.onabort = () => {
  42. reject(new shaka.util.Error(
  43. shaka.util.Error.Severity.RECOVERABLE,
  44. shaka.util.Error.Category.NETWORK,
  45. shaka.util.Error.Code.OPERATION_ABORTED,
  46. uri, requestType));
  47. };
  48. let calledHeadersReceived = false;
  49. xhr.onreadystatechange = (event) => {
  50. // See if the readyState is 2 ("HEADERS_RECEIVED").
  51. if (xhr.readyState == 2 && !calledHeadersReceived) {
  52. const headers = shaka.net.HttpXHRPlugin.headersToGenericObject_(xhr);
  53. headersReceived(headers);
  54. // Don't send out this event twice.
  55. calledHeadersReceived = true;
  56. }
  57. };
  58. xhr.onload = (event) => {
  59. const headers = shaka.net.HttpXHRPlugin.headersToGenericObject_(xhr);
  60. // eslint-disable-next-line shaka-rules/buffersource-no-instanceof
  61. goog.asserts.assert(xhr.response instanceof ArrayBuffer,
  62. 'XHR should have a response by now!');
  63. const xhrResponse = xhr.response;
  64. try {
  65. const currentTime = Date.now();
  66. progressUpdated(currentTime - lastTime, event.loaded - lastLoaded,
  67. /* numBytesRemaining= */ 0);
  68. const response = shaka.net.HttpPluginUtils.makeResponse(headers,
  69. xhrResponse, xhr.status, uri, xhr.responseURL, request,
  70. requestType);
  71. resolve(response);
  72. } catch (error) {
  73. goog.asserts.assert(error instanceof shaka.util.Error,
  74. 'Wrong error type!');
  75. reject(error);
  76. }
  77. };
  78. xhr.onerror = (event) => {
  79. reject(new shaka.util.Error(
  80. shaka.util.Error.Severity.RECOVERABLE,
  81. shaka.util.Error.Category.NETWORK,
  82. shaka.util.Error.Code.HTTP_ERROR,
  83. uri, event, requestType));
  84. };
  85. xhr.ontimeout = (event) => {
  86. reject(new shaka.util.Error(
  87. shaka.util.Error.Severity.RECOVERABLE,
  88. shaka.util.Error.Category.NETWORK,
  89. shaka.util.Error.Code.TIMEOUT,
  90. uri, requestType));
  91. };
  92. xhr.onprogress = (event) => {
  93. const currentTime = Date.now();
  94. // If the time between last time and this time we got progress event
  95. // is long enough, or if a whole segment is downloaded, call
  96. // progressUpdated().
  97. const minBytes = config.minBytesForProgressEvents || 0;
  98. const chunkSize = event.loaded - lastLoaded;
  99. if ((currentTime - lastTime > 100 && chunkSize >= minBytes) ||
  100. (event.lengthComputable && event.loaded == event.total)) {
  101. const numBytesRemaining =
  102. xhr.readyState == 4 ? 0 : event.total - event.loaded;
  103. progressUpdated(currentTime - lastTime, chunkSize,
  104. numBytesRemaining);
  105. lastLoaded = event.loaded;
  106. lastTime = currentTime;
  107. }
  108. };
  109. for (const key in request.headers) {
  110. // The Fetch API automatically normalizes outgoing header keys to
  111. // lowercase. For consistency's sake, do it here too.
  112. const lowercasedKey = key.toLowerCase();
  113. xhr.setRequestHeader(lowercasedKey, request.headers[key]);
  114. }
  115. xhr.send(request.body);
  116. }));
  117. return new shaka.util.AbortableOperation(
  118. promise,
  119. () => {
  120. xhr.abort();
  121. return Promise.resolve();
  122. });
  123. }
  124. /**
  125. * @param {!XMLHttpRequest} xhr
  126. * @return {!Object<string, string>}
  127. * @private
  128. */
  129. static headersToGenericObject_(xhr) {
  130. // Since Edge incorrectly return the header with a leading new
  131. // line character ('\n'), we trim the header here.
  132. const headerLines = xhr.getAllResponseHeaders().trim().split('\r\n');
  133. const headers = {};
  134. for (const header of headerLines) {
  135. /** @type {!Array<string>} */
  136. const parts = header.split(': ');
  137. headers[parts[0].toLowerCase()] = parts.slice(1).join(': ');
  138. }
  139. return headers;
  140. }
  141. };
  142. /**
  143. * Overridden in unit tests, but compiled out in production.
  144. *
  145. * @const {function(new: XMLHttpRequest)}
  146. * @private
  147. */
  148. shaka.net.HttpXHRPlugin.Xhr_ = window.XMLHttpRequest;
  149. shaka.net.NetworkingEngine.registerScheme(
  150. 'http', shaka.net.HttpXHRPlugin.parse,
  151. shaka.net.NetworkingEngine.PluginPriority.FALLBACK,
  152. /* progressSupport= */ true);
  153. shaka.net.NetworkingEngine.registerScheme(
  154. 'https', shaka.net.HttpXHRPlugin.parse,
  155. shaka.net.NetworkingEngine.PluginPriority.FALLBACK,
  156. /* progressSupport= */ true);
  157. shaka.net.NetworkingEngine.registerScheme(
  158. 'blob', shaka.net.HttpXHRPlugin.parse,
  159. shaka.net.NetworkingEngine.PluginPriority.FALLBACK,
  160. /* progressSupport= */ true);