network.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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.PDFNetworkStream = 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. ;
  37. var OK_RESPONSE = 200;
  38. var PARTIAL_CONTENT_RESPONSE = 206;
  39. function getArrayBuffer(xhr) {
  40. var data = xhr.response;
  41. if (typeof data !== 'string') {
  42. return data;
  43. }
  44. var array = (0, _util.stringToBytes)(data);
  45. return array.buffer;
  46. }
  47. var NetworkManager =
  48. /*#__PURE__*/
  49. function () {
  50. function NetworkManager(url, args) {
  51. _classCallCheck(this, NetworkManager);
  52. this.url = url;
  53. args = args || {};
  54. this.isHttp = /^https?:/i.test(url);
  55. this.httpHeaders = this.isHttp && args.httpHeaders || {};
  56. this.withCredentials = args.withCredentials || false;
  57. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  58. return new XMLHttpRequest();
  59. };
  60. this.currXhrId = 0;
  61. this.pendingRequests = Object.create(null);
  62. }
  63. _createClass(NetworkManager, [{
  64. key: "requestRange",
  65. value: function requestRange(begin, end, listeners) {
  66. var args = {
  67. begin: begin,
  68. end: end
  69. };
  70. for (var prop in listeners) {
  71. args[prop] = listeners[prop];
  72. }
  73. return this.request(args);
  74. }
  75. }, {
  76. key: "requestFull",
  77. value: function requestFull(listeners) {
  78. return this.request(listeners);
  79. }
  80. }, {
  81. key: "request",
  82. value: function request(args) {
  83. var xhr = this.getXhr();
  84. var xhrId = this.currXhrId++;
  85. var pendingRequest = this.pendingRequests[xhrId] = {
  86. xhr: xhr
  87. };
  88. xhr.open('GET', this.url);
  89. xhr.withCredentials = this.withCredentials;
  90. for (var property in this.httpHeaders) {
  91. var value = this.httpHeaders[property];
  92. if (typeof value === 'undefined') {
  93. continue;
  94. }
  95. xhr.setRequestHeader(property, value);
  96. }
  97. if (this.isHttp && 'begin' in args && 'end' in args) {
  98. xhr.setRequestHeader('Range', "bytes=".concat(args.begin, "-").concat(args.end - 1));
  99. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  100. } else {
  101. pendingRequest.expectedStatus = OK_RESPONSE;
  102. }
  103. xhr.responseType = 'arraybuffer';
  104. if (args.onError) {
  105. xhr.onerror = function (evt) {
  106. args.onError(xhr.status);
  107. };
  108. }
  109. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  110. xhr.onprogress = this.onProgress.bind(this, xhrId);
  111. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  112. pendingRequest.onDone = args.onDone;
  113. pendingRequest.onError = args.onError;
  114. pendingRequest.onProgress = args.onProgress;
  115. xhr.send(null);
  116. return xhrId;
  117. }
  118. }, {
  119. key: "onProgress",
  120. value: function onProgress(xhrId, evt) {
  121. var pendingRequest = this.pendingRequests[xhrId];
  122. if (!pendingRequest) {
  123. return;
  124. }
  125. if (pendingRequest.onProgress) {
  126. pendingRequest.onProgress(evt);
  127. }
  128. }
  129. }, {
  130. key: "onStateChange",
  131. value: function onStateChange(xhrId, evt) {
  132. var pendingRequest = this.pendingRequests[xhrId];
  133. if (!pendingRequest) {
  134. return;
  135. }
  136. var xhr = pendingRequest.xhr;
  137. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  138. pendingRequest.onHeadersReceived();
  139. delete pendingRequest.onHeadersReceived;
  140. }
  141. if (xhr.readyState !== 4) {
  142. return;
  143. }
  144. if (!(xhrId in this.pendingRequests)) {
  145. return;
  146. }
  147. delete this.pendingRequests[xhrId];
  148. if (xhr.status === 0 && this.isHttp) {
  149. if (pendingRequest.onError) {
  150. pendingRequest.onError(xhr.status);
  151. }
  152. return;
  153. }
  154. var xhrStatus = xhr.status || OK_RESPONSE;
  155. var ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  156. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  157. if (pendingRequest.onError) {
  158. pendingRequest.onError(xhr.status);
  159. }
  160. return;
  161. }
  162. var chunk = getArrayBuffer(xhr);
  163. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  164. var rangeHeader = xhr.getResponseHeader('Content-Range');
  165. var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  166. pendingRequest.onDone({
  167. begin: parseInt(matches[1], 10),
  168. chunk: chunk
  169. });
  170. } else if (chunk) {
  171. pendingRequest.onDone({
  172. begin: 0,
  173. chunk: chunk
  174. });
  175. } else if (pendingRequest.onError) {
  176. pendingRequest.onError(xhr.status);
  177. }
  178. }
  179. }, {
  180. key: "hasPendingRequests",
  181. value: function hasPendingRequests() {
  182. for (var xhrId in this.pendingRequests) {
  183. return true;
  184. }
  185. return false;
  186. }
  187. }, {
  188. key: "getRequestXhr",
  189. value: function getRequestXhr(xhrId) {
  190. return this.pendingRequests[xhrId].xhr;
  191. }
  192. }, {
  193. key: "isPendingRequest",
  194. value: function isPendingRequest(xhrId) {
  195. return xhrId in this.pendingRequests;
  196. }
  197. }, {
  198. key: "abortAllRequests",
  199. value: function abortAllRequests() {
  200. for (var xhrId in this.pendingRequests) {
  201. this.abortRequest(xhrId | 0);
  202. }
  203. }
  204. }, {
  205. key: "abortRequest",
  206. value: function abortRequest(xhrId) {
  207. var xhr = this.pendingRequests[xhrId].xhr;
  208. delete this.pendingRequests[xhrId];
  209. xhr.abort();
  210. }
  211. }]);
  212. return NetworkManager;
  213. }();
  214. var PDFNetworkStream =
  215. /*#__PURE__*/
  216. function () {
  217. function PDFNetworkStream(source) {
  218. _classCallCheck(this, PDFNetworkStream);
  219. this._source = source;
  220. this._manager = new NetworkManager(source.url, {
  221. httpHeaders: source.httpHeaders,
  222. withCredentials: source.withCredentials
  223. });
  224. this._rangeChunkSize = source.rangeChunkSize;
  225. this._fullRequestReader = null;
  226. this._rangeRequestReaders = [];
  227. }
  228. _createClass(PDFNetworkStream, [{
  229. key: "_onRangeRequestReaderClosed",
  230. value: function _onRangeRequestReaderClosed(reader) {
  231. var i = this._rangeRequestReaders.indexOf(reader);
  232. if (i >= 0) {
  233. this._rangeRequestReaders.splice(i, 1);
  234. }
  235. }
  236. }, {
  237. key: "getFullReader",
  238. value: function getFullReader() {
  239. (0, _util.assert)(!this._fullRequestReader);
  240. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  241. return this._fullRequestReader;
  242. }
  243. }, {
  244. key: "getRangeReader",
  245. value: function getRangeReader(begin, end) {
  246. var reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  247. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  248. this._rangeRequestReaders.push(reader);
  249. return reader;
  250. }
  251. }, {
  252. key: "cancelAllRequests",
  253. value: function cancelAllRequests(reason) {
  254. if (this._fullRequestReader) {
  255. this._fullRequestReader.cancel(reason);
  256. }
  257. var readers = this._rangeRequestReaders.slice(0);
  258. readers.forEach(function (reader) {
  259. reader.cancel(reason);
  260. });
  261. }
  262. }]);
  263. return PDFNetworkStream;
  264. }();
  265. exports.PDFNetworkStream = PDFNetworkStream;
  266. var PDFNetworkStreamFullRequestReader =
  267. /*#__PURE__*/
  268. function () {
  269. function PDFNetworkStreamFullRequestReader(manager, source) {
  270. _classCallCheck(this, PDFNetworkStreamFullRequestReader);
  271. this._manager = manager;
  272. var args = {
  273. onHeadersReceived: this._onHeadersReceived.bind(this),
  274. onDone: this._onDone.bind(this),
  275. onError: this._onError.bind(this),
  276. onProgress: this._onProgress.bind(this)
  277. };
  278. this._url = source.url;
  279. this._fullRequestId = manager.requestFull(args);
  280. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  281. this._disableRange = source.disableRange || false;
  282. this._contentLength = source.length;
  283. this._rangeChunkSize = source.rangeChunkSize;
  284. if (!this._rangeChunkSize && !this._disableRange) {
  285. this._disableRange = true;
  286. }
  287. this._isStreamingSupported = false;
  288. this._isRangeSupported = false;
  289. this._cachedChunks = [];
  290. this._requests = [];
  291. this._done = false;
  292. this._storedError = undefined;
  293. this._filename = null;
  294. this.onProgress = null;
  295. }
  296. _createClass(PDFNetworkStreamFullRequestReader, [{
  297. key: "_onHeadersReceived",
  298. value: function _onHeadersReceived() {
  299. var fullRequestXhrId = this._fullRequestId;
  300. var fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  301. var getResponseHeader = function getResponseHeader(name) {
  302. return fullRequestXhr.getResponseHeader(name);
  303. };
  304. var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
  305. getResponseHeader: getResponseHeader,
  306. isHttp: this._manager.isHttp,
  307. rangeChunkSize: this._rangeChunkSize,
  308. disableRange: this._disableRange
  309. }),
  310. allowRangeRequests = _validateRangeRequest.allowRangeRequests,
  311. suggestedLength = _validateRangeRequest.suggestedLength;
  312. if (allowRangeRequests) {
  313. this._isRangeSupported = true;
  314. }
  315. this._contentLength = suggestedLength || this._contentLength;
  316. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  317. if (this._isRangeSupported) {
  318. this._manager.abortRequest(fullRequestXhrId);
  319. }
  320. this._headersReceivedCapability.resolve();
  321. }
  322. }, {
  323. key: "_onDone",
  324. value: function _onDone(args) {
  325. if (args) {
  326. if (this._requests.length > 0) {
  327. var requestCapability = this._requests.shift();
  328. requestCapability.resolve({
  329. value: args.chunk,
  330. done: false
  331. });
  332. } else {
  333. this._cachedChunks.push(args.chunk);
  334. }
  335. }
  336. this._done = true;
  337. if (this._cachedChunks.length > 0) {
  338. return;
  339. }
  340. this._requests.forEach(function (requestCapability) {
  341. requestCapability.resolve({
  342. value: undefined,
  343. done: true
  344. });
  345. });
  346. this._requests = [];
  347. }
  348. }, {
  349. key: "_onError",
  350. value: function _onError(status) {
  351. var url = this._url;
  352. var exception = (0, _network_utils.createResponseStatusError)(status, url);
  353. this._storedError = exception;
  354. this._headersReceivedCapability.reject(exception);
  355. this._requests.forEach(function (requestCapability) {
  356. requestCapability.reject(exception);
  357. });
  358. this._requests = [];
  359. this._cachedChunks = [];
  360. }
  361. }, {
  362. key: "_onProgress",
  363. value: function _onProgress(data) {
  364. if (this.onProgress) {
  365. this.onProgress({
  366. loaded: data.loaded,
  367. total: data.lengthComputable ? data.total : this._contentLength
  368. });
  369. }
  370. }
  371. }, {
  372. key: "read",
  373. value: function () {
  374. var _read = _asyncToGenerator(
  375. /*#__PURE__*/
  376. _regenerator["default"].mark(function _callee() {
  377. var chunk, requestCapability;
  378. return _regenerator["default"].wrap(function _callee$(_context) {
  379. while (1) {
  380. switch (_context.prev = _context.next) {
  381. case 0:
  382. if (!this._storedError) {
  383. _context.next = 2;
  384. break;
  385. }
  386. throw this._storedError;
  387. case 2:
  388. if (!(this._cachedChunks.length > 0)) {
  389. _context.next = 5;
  390. break;
  391. }
  392. chunk = this._cachedChunks.shift();
  393. return _context.abrupt("return", {
  394. value: chunk,
  395. done: false
  396. });
  397. case 5:
  398. if (!this._done) {
  399. _context.next = 7;
  400. break;
  401. }
  402. return _context.abrupt("return", {
  403. value: undefined,
  404. done: true
  405. });
  406. case 7:
  407. requestCapability = (0, _util.createPromiseCapability)();
  408. this._requests.push(requestCapability);
  409. return _context.abrupt("return", requestCapability.promise);
  410. case 10:
  411. case "end":
  412. return _context.stop();
  413. }
  414. }
  415. }, _callee, this);
  416. }));
  417. function read() {
  418. return _read.apply(this, arguments);
  419. }
  420. return read;
  421. }()
  422. }, {
  423. key: "cancel",
  424. value: function cancel(reason) {
  425. this._done = true;
  426. this._headersReceivedCapability.reject(reason);
  427. this._requests.forEach(function (requestCapability) {
  428. requestCapability.resolve({
  429. value: undefined,
  430. done: true
  431. });
  432. });
  433. this._requests = [];
  434. if (this._manager.isPendingRequest(this._fullRequestId)) {
  435. this._manager.abortRequest(this._fullRequestId);
  436. }
  437. this._fullRequestReader = null;
  438. }
  439. }, {
  440. key: "filename",
  441. get: function get() {
  442. return this._filename;
  443. }
  444. }, {
  445. key: "isRangeSupported",
  446. get: function get() {
  447. return this._isRangeSupported;
  448. }
  449. }, {
  450. key: "isStreamingSupported",
  451. get: function get() {
  452. return this._isStreamingSupported;
  453. }
  454. }, {
  455. key: "contentLength",
  456. get: function get() {
  457. return this._contentLength;
  458. }
  459. }, {
  460. key: "headersReady",
  461. get: function get() {
  462. return this._headersReceivedCapability.promise;
  463. }
  464. }]);
  465. return PDFNetworkStreamFullRequestReader;
  466. }();
  467. var PDFNetworkStreamRangeRequestReader =
  468. /*#__PURE__*/
  469. function () {
  470. function PDFNetworkStreamRangeRequestReader(manager, begin, end) {
  471. _classCallCheck(this, PDFNetworkStreamRangeRequestReader);
  472. this._manager = manager;
  473. var args = {
  474. onDone: this._onDone.bind(this),
  475. onProgress: this._onProgress.bind(this)
  476. };
  477. this._requestId = manager.requestRange(begin, end, args);
  478. this._requests = [];
  479. this._queuedChunk = null;
  480. this._done = false;
  481. this.onProgress = null;
  482. this.onClosed = null;
  483. }
  484. _createClass(PDFNetworkStreamRangeRequestReader, [{
  485. key: "_close",
  486. value: function _close() {
  487. if (this.onClosed) {
  488. this.onClosed(this);
  489. }
  490. }
  491. }, {
  492. key: "_onDone",
  493. value: function _onDone(data) {
  494. var chunk = data.chunk;
  495. if (this._requests.length > 0) {
  496. var requestCapability = this._requests.shift();
  497. requestCapability.resolve({
  498. value: chunk,
  499. done: false
  500. });
  501. } else {
  502. this._queuedChunk = chunk;
  503. }
  504. this._done = true;
  505. this._requests.forEach(function (requestCapability) {
  506. requestCapability.resolve({
  507. value: undefined,
  508. done: true
  509. });
  510. });
  511. this._requests = [];
  512. this._close();
  513. }
  514. }, {
  515. key: "_onProgress",
  516. value: function _onProgress(evt) {
  517. if (!this.isStreamingSupported && this.onProgress) {
  518. this.onProgress({
  519. loaded: evt.loaded
  520. });
  521. }
  522. }
  523. }, {
  524. key: "read",
  525. value: function () {
  526. var _read2 = _asyncToGenerator(
  527. /*#__PURE__*/
  528. _regenerator["default"].mark(function _callee2() {
  529. var chunk, requestCapability;
  530. return _regenerator["default"].wrap(function _callee2$(_context2) {
  531. while (1) {
  532. switch (_context2.prev = _context2.next) {
  533. case 0:
  534. if (!(this._queuedChunk !== null)) {
  535. _context2.next = 4;
  536. break;
  537. }
  538. chunk = this._queuedChunk;
  539. this._queuedChunk = null;
  540. return _context2.abrupt("return", {
  541. value: chunk,
  542. done: false
  543. });
  544. case 4:
  545. if (!this._done) {
  546. _context2.next = 6;
  547. break;
  548. }
  549. return _context2.abrupt("return", {
  550. value: undefined,
  551. done: true
  552. });
  553. case 6:
  554. requestCapability = (0, _util.createPromiseCapability)();
  555. this._requests.push(requestCapability);
  556. return _context2.abrupt("return", requestCapability.promise);
  557. case 9:
  558. case "end":
  559. return _context2.stop();
  560. }
  561. }
  562. }, _callee2, this);
  563. }));
  564. function read() {
  565. return _read2.apply(this, arguments);
  566. }
  567. return read;
  568. }()
  569. }, {
  570. key: "cancel",
  571. value: function cancel(reason) {
  572. this._done = true;
  573. this._requests.forEach(function (requestCapability) {
  574. requestCapability.resolve({
  575. value: undefined,
  576. done: true
  577. });
  578. });
  579. this._requests = [];
  580. if (this._manager.isPendingRequest(this._requestId)) {
  581. this._manager.abortRequest(this._requestId);
  582. }
  583. this._close();
  584. }
  585. }, {
  586. key: "isStreamingSupported",
  587. get: function get() {
  588. return false;
  589. }
  590. }]);
  591. return PDFNetworkStreamRangeRequestReader;
  592. }();