fetch_stream.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2019 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PDFFetchStream = void 0;
  27. var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  28. var _util = require("../shared/util");
  29. var _network_utils = require("./network_utils");
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  32. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  33. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36. function createFetchOptions(headers, withCredentials, abortController) {
  37. return {
  38. method: 'GET',
  39. headers: headers,
  40. signal: abortController && abortController.signal,
  41. mode: 'cors',
  42. credentials: withCredentials ? 'include' : 'same-origin',
  43. redirect: 'follow'
  44. };
  45. }
  46. var PDFFetchStream =
  47. /*#__PURE__*/
  48. function () {
  49. function PDFFetchStream(source) {
  50. _classCallCheck(this, PDFFetchStream);
  51. this.source = source;
  52. this.isHttp = /^https?:/i.test(source.url);
  53. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  54. this._fullRequestReader = null;
  55. this._rangeRequestReaders = [];
  56. }
  57. _createClass(PDFFetchStream, [{
  58. key: "getFullReader",
  59. value: function getFullReader() {
  60. (0, _util.assert)(!this._fullRequestReader);
  61. this._fullRequestReader = new PDFFetchStreamReader(this);
  62. return this._fullRequestReader;
  63. }
  64. }, {
  65. key: "getRangeReader",
  66. value: function getRangeReader(begin, end) {
  67. if (end <= this._progressiveDataLength) {
  68. return null;
  69. }
  70. var reader = new PDFFetchStreamRangeReader(this, begin, end);
  71. this._rangeRequestReaders.push(reader);
  72. return reader;
  73. }
  74. }, {
  75. key: "cancelAllRequests",
  76. value: function cancelAllRequests(reason) {
  77. if (this._fullRequestReader) {
  78. this._fullRequestReader.cancel(reason);
  79. }
  80. var readers = this._rangeRequestReaders.slice(0);
  81. readers.forEach(function (reader) {
  82. reader.cancel(reason);
  83. });
  84. }
  85. }, {
  86. key: "_progressiveDataLength",
  87. get: function get() {
  88. return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
  89. }
  90. }]);
  91. return PDFFetchStream;
  92. }();
  93. exports.PDFFetchStream = PDFFetchStream;
  94. var PDFFetchStreamReader =
  95. /*#__PURE__*/
  96. function () {
  97. function PDFFetchStreamReader(stream) {
  98. var _this = this;
  99. _classCallCheck(this, PDFFetchStreamReader);
  100. this._stream = stream;
  101. this._reader = null;
  102. this._loaded = 0;
  103. this._filename = null;
  104. var source = stream.source;
  105. this._withCredentials = source.withCredentials || false;
  106. this._contentLength = source.length;
  107. this._headersCapability = (0, _util.createPromiseCapability)();
  108. this._disableRange = source.disableRange || false;
  109. this._rangeChunkSize = source.rangeChunkSize;
  110. if (!this._rangeChunkSize && !this._disableRange) {
  111. this._disableRange = true;
  112. }
  113. if (typeof AbortController !== 'undefined') {
  114. this._abortController = new AbortController();
  115. }
  116. this._isStreamingSupported = !source.disableStream;
  117. this._isRangeSupported = !source.disableRange;
  118. this._headers = new Headers();
  119. for (var property in this._stream.httpHeaders) {
  120. var value = this._stream.httpHeaders[property];
  121. if (typeof value === 'undefined') {
  122. continue;
  123. }
  124. this._headers.append(property, value);
  125. }
  126. var url = source.url;
  127. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(function (response) {
  128. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  129. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  130. }
  131. _this._reader = response.body.getReader();
  132. _this._headersCapability.resolve();
  133. var getResponseHeader = function getResponseHeader(name) {
  134. return response.headers.get(name);
  135. };
  136. var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
  137. getResponseHeader: getResponseHeader,
  138. isHttp: _this._stream.isHttp,
  139. rangeChunkSize: _this._rangeChunkSize,
  140. disableRange: _this._disableRange
  141. }),
  142. allowRangeRequests = _validateRangeRequest.allowRangeRequests,
  143. suggestedLength = _validateRangeRequest.suggestedLength;
  144. _this._isRangeSupported = allowRangeRequests;
  145. _this._contentLength = suggestedLength || _this._contentLength;
  146. _this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  147. if (!_this._isStreamingSupported && _this._isRangeSupported) {
  148. _this.cancel(new _util.AbortException('Streaming is disabled.'));
  149. }
  150. })["catch"](this._headersCapability.reject);
  151. this.onProgress = null;
  152. }
  153. _createClass(PDFFetchStreamReader, [{
  154. key: "read",
  155. value: function () {
  156. var _read = _asyncToGenerator(
  157. /*#__PURE__*/
  158. _regenerator["default"].mark(function _callee() {
  159. var _ref, value, done, buffer;
  160. return _regenerator["default"].wrap(function _callee$(_context) {
  161. while (1) {
  162. switch (_context.prev = _context.next) {
  163. case 0:
  164. _context.next = 2;
  165. return this._headersCapability.promise;
  166. case 2:
  167. _context.next = 4;
  168. return this._reader.read();
  169. case 4:
  170. _ref = _context.sent;
  171. value = _ref.value;
  172. done = _ref.done;
  173. if (!done) {
  174. _context.next = 9;
  175. break;
  176. }
  177. return _context.abrupt("return", {
  178. value: value,
  179. done: done
  180. });
  181. case 9:
  182. this._loaded += value.byteLength;
  183. if (this.onProgress) {
  184. this.onProgress({
  185. loaded: this._loaded,
  186. total: this._contentLength
  187. });
  188. }
  189. buffer = new Uint8Array(value).buffer;
  190. return _context.abrupt("return", {
  191. value: buffer,
  192. done: false
  193. });
  194. case 13:
  195. case "end":
  196. return _context.stop();
  197. }
  198. }
  199. }, _callee, this);
  200. }));
  201. function read() {
  202. return _read.apply(this, arguments);
  203. }
  204. return read;
  205. }()
  206. }, {
  207. key: "cancel",
  208. value: function cancel(reason) {
  209. if (this._reader) {
  210. this._reader.cancel(reason);
  211. }
  212. if (this._abortController) {
  213. this._abortController.abort();
  214. }
  215. }
  216. }, {
  217. key: "headersReady",
  218. get: function get() {
  219. return this._headersCapability.promise;
  220. }
  221. }, {
  222. key: "filename",
  223. get: function get() {
  224. return this._filename;
  225. }
  226. }, {
  227. key: "contentLength",
  228. get: function get() {
  229. return this._contentLength;
  230. }
  231. }, {
  232. key: "isRangeSupported",
  233. get: function get() {
  234. return this._isRangeSupported;
  235. }
  236. }, {
  237. key: "isStreamingSupported",
  238. get: function get() {
  239. return this._isStreamingSupported;
  240. }
  241. }]);
  242. return PDFFetchStreamReader;
  243. }();
  244. var PDFFetchStreamRangeReader =
  245. /*#__PURE__*/
  246. function () {
  247. function PDFFetchStreamRangeReader(stream, begin, end) {
  248. var _this2 = this;
  249. _classCallCheck(this, PDFFetchStreamRangeReader);
  250. this._stream = stream;
  251. this._reader = null;
  252. this._loaded = 0;
  253. var source = stream.source;
  254. this._withCredentials = source.withCredentials || false;
  255. this._readCapability = (0, _util.createPromiseCapability)();
  256. this._isStreamingSupported = !source.disableStream;
  257. if (typeof AbortController !== 'undefined') {
  258. this._abortController = new AbortController();
  259. }
  260. this._headers = new Headers();
  261. for (var property in this._stream.httpHeaders) {
  262. var value = this._stream.httpHeaders[property];
  263. if (typeof value === 'undefined') {
  264. continue;
  265. }
  266. this._headers.append(property, value);
  267. }
  268. this._headers.append('Range', "bytes=".concat(begin, "-").concat(end - 1));
  269. var url = source.url;
  270. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(function (response) {
  271. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  272. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  273. }
  274. _this2._readCapability.resolve();
  275. _this2._reader = response.body.getReader();
  276. });
  277. this.onProgress = null;
  278. }
  279. _createClass(PDFFetchStreamRangeReader, [{
  280. key: "read",
  281. value: function () {
  282. var _read2 = _asyncToGenerator(
  283. /*#__PURE__*/
  284. _regenerator["default"].mark(function _callee2() {
  285. var _ref2, value, done, buffer;
  286. return _regenerator["default"].wrap(function _callee2$(_context2) {
  287. while (1) {
  288. switch (_context2.prev = _context2.next) {
  289. case 0:
  290. _context2.next = 2;
  291. return this._readCapability.promise;
  292. case 2:
  293. _context2.next = 4;
  294. return this._reader.read();
  295. case 4:
  296. _ref2 = _context2.sent;
  297. value = _ref2.value;
  298. done = _ref2.done;
  299. if (!done) {
  300. _context2.next = 9;
  301. break;
  302. }
  303. return _context2.abrupt("return", {
  304. value: value,
  305. done: done
  306. });
  307. case 9:
  308. this._loaded += value.byteLength;
  309. if (this.onProgress) {
  310. this.onProgress({
  311. loaded: this._loaded
  312. });
  313. }
  314. buffer = new Uint8Array(value).buffer;
  315. return _context2.abrupt("return", {
  316. value: buffer,
  317. done: false
  318. });
  319. case 13:
  320. case "end":
  321. return _context2.stop();
  322. }
  323. }
  324. }, _callee2, this);
  325. }));
  326. function read() {
  327. return _read2.apply(this, arguments);
  328. }
  329. return read;
  330. }()
  331. }, {
  332. key: "cancel",
  333. value: function cancel(reason) {
  334. if (this._reader) {
  335. this._reader.cancel(reason);
  336. }
  337. if (this._abortController) {
  338. this._abortController.abort();
  339. }
  340. }
  341. }, {
  342. key: "isStreamingSupported",
  343. get: function get() {
  344. return this._isStreamingSupported;
  345. }
  346. }]);
  347. return PDFFetchStreamRangeReader;
  348. }();