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, requestType);
  70. resolve(response);
  71. } catch (error) {
  72. goog.asserts.assert(error instanceof shaka.util.Error,
  73. 'Wrong error type!');
  74. reject(error);
  75. }
  76. };
  77. xhr.onerror = (event) => {
  78. reject(new shaka.util.Error(
  79. shaka.util.Error.Severity.RECOVERABLE,
  80. shaka.util.Error.Category.NETWORK,
  81. shaka.util.Error.Code.HTTP_ERROR,
  82. uri, event, requestType));
  83. };
  84. xhr.ontimeout = (event) => {
  85. reject(new shaka.util.Error(
  86. shaka.util.Error.Severity.RECOVERABLE,
  87. shaka.util.Error.Category.NETWORK,
  88. shaka.util.Error.Code.TIMEOUT,
  89. uri, requestType));
  90. };
  91. xhr.onprogress = (event) => {
  92. const currentTime = Date.now();
  93. // If the time between last time and this time we got progress event
  94. // is long enough, or if a whole segment is downloaded, call
  95. // progressUpdated().
  96. const minBytes = config.minBytesForProgressEvents || 0;
  97. const chunkSize = event.loaded - lastLoaded;
  98. if ((currentTime - lastTime > 100 && chunkSize >= minBytes) ||
  99. (event.lengthComputable && event.loaded == event.total)) {
  100. const numBytesRemaining =
  101. xhr.readyState == 4 ? 0 : event.total - event.loaded;
  102. progressUpdated(currentTime - lastTime, chunkSize,
  103. numBytesRemaining);
  104. lastLoaded = event.loaded;
  105. lastTime = currentTime;
  106. }
  107. };
  108. for (const key in request.headers) {
  109. // The Fetch API automatically normalizes outgoing header keys to
  110. // lowercase. For consistency's sake, do it here too.
  111. const lowercasedKey = key.toLowerCase();
  112. xhr.setRequestHeader(lowercasedKey, request.headers[key]);
  113. }
  114. xhr.send(request.body);
  115. }));
  116. return new shaka.util.AbortableOperation(
  117. promise,
  118. () => {
  119. xhr.abort();
  120. return Promise.resolve();
  121. });
  122. }
  123. /**
  124. * @param {!XMLHttpRequest} xhr
  125. * @return {!Object.<string, string>}
  126. * @private
  127. */
  128. static headersToGenericObject_(xhr) {
  129. // Since Edge incorrectly return the header with a leading new
  130. // line character ('\n'), we trim the header here.
  131. const headerLines = xhr.getAllResponseHeaders().trim().split('\r\n');
  132. const headers = {};
  133. for (const header of headerLines) {
  134. /** @type {!Array.<string>} */
  135. const parts = header.split(': ');
  136. headers[parts[0].toLowerCase()] = parts.slice(1).join(': ');
  137. }
  138. return headers;
  139. }
  140. };
  141. /**
  142. * Overridden in unit tests, but compiled out in production.
  143. *
  144. * @const {function(new: XMLHttpRequest)}
  145. * @private
  146. */
  147. shaka.net.HttpXHRPlugin.Xhr_ = window.XMLHttpRequest;
  148. shaka.net.NetworkingEngine.registerScheme(
  149. 'http', shaka.net.HttpXHRPlugin.parse,
  150. shaka.net.NetworkingEngine.PluginPriority.FALLBACK,
  151. /* progressSupport= */ true);
  152. shaka.net.NetworkingEngine.registerScheme(
  153. 'https', shaka.net.HttpXHRPlugin.parse,
  154. shaka.net.NetworkingEngine.PluginPriority.FALLBACK,
  155. /* progressSupport= */ true);
  156. shaka.net.NetworkingEngine.registerScheme(
  157. 'blob', shaka.net.HttpXHRPlugin.parse,
  158. shaka.net.NetworkingEngine.PluginPriority.FALLBACK,
  159. /* progressSupport= */ true);