network.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 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 _util = require("../shared/util.js");
  28. var _network_utils = require("./network_utils.js");
  29. ;
  30. const OK_RESPONSE = 200;
  31. const PARTIAL_CONTENT_RESPONSE = 206;
  32. function getArrayBuffer(xhr) {
  33. const data = xhr.response;
  34. if (typeof data !== "string") {
  35. return data;
  36. }
  37. const array = (0, _util.stringToBytes)(data);
  38. return array.buffer;
  39. }
  40. class NetworkManager {
  41. constructor(url, args) {
  42. this.url = url;
  43. args = args || {};
  44. this.isHttp = /^https?:/i.test(url);
  45. this.httpHeaders = this.isHttp && args.httpHeaders || {};
  46. this.withCredentials = args.withCredentials || false;
  47. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  48. return new XMLHttpRequest();
  49. };
  50. this.currXhrId = 0;
  51. this.pendingRequests = Object.create(null);
  52. }
  53. requestRange(begin, end, listeners) {
  54. const args = {
  55. begin,
  56. end
  57. };
  58. for (const prop in listeners) {
  59. args[prop] = listeners[prop];
  60. }
  61. return this.request(args);
  62. }
  63. requestFull(listeners) {
  64. return this.request(listeners);
  65. }
  66. request(args) {
  67. const xhr = this.getXhr();
  68. const xhrId = this.currXhrId++;
  69. const pendingRequest = this.pendingRequests[xhrId] = {
  70. xhr
  71. };
  72. xhr.open("GET", this.url);
  73. xhr.withCredentials = this.withCredentials;
  74. for (const property in this.httpHeaders) {
  75. const value = this.httpHeaders[property];
  76. if (typeof value === "undefined") {
  77. continue;
  78. }
  79. xhr.setRequestHeader(property, value);
  80. }
  81. if (this.isHttp && "begin" in args && "end" in args) {
  82. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  83. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  84. } else {
  85. pendingRequest.expectedStatus = OK_RESPONSE;
  86. }
  87. xhr.responseType = "arraybuffer";
  88. if (args.onError) {
  89. xhr.onerror = function (evt) {
  90. args.onError(xhr.status);
  91. };
  92. }
  93. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  94. xhr.onprogress = this.onProgress.bind(this, xhrId);
  95. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  96. pendingRequest.onDone = args.onDone;
  97. pendingRequest.onError = args.onError;
  98. pendingRequest.onProgress = args.onProgress;
  99. xhr.send(null);
  100. return xhrId;
  101. }
  102. onProgress(xhrId, evt) {
  103. const pendingRequest = this.pendingRequests[xhrId];
  104. if (!pendingRequest) {
  105. return;
  106. }
  107. if (pendingRequest.onProgress) {
  108. pendingRequest.onProgress(evt);
  109. }
  110. }
  111. onStateChange(xhrId, evt) {
  112. const pendingRequest = this.pendingRequests[xhrId];
  113. if (!pendingRequest) {
  114. return;
  115. }
  116. const xhr = pendingRequest.xhr;
  117. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  118. pendingRequest.onHeadersReceived();
  119. delete pendingRequest.onHeadersReceived;
  120. }
  121. if (xhr.readyState !== 4) {
  122. return;
  123. }
  124. if (!(xhrId in this.pendingRequests)) {
  125. return;
  126. }
  127. delete this.pendingRequests[xhrId];
  128. if (xhr.status === 0 && this.isHttp) {
  129. if (pendingRequest.onError) {
  130. pendingRequest.onError(xhr.status);
  131. }
  132. return;
  133. }
  134. const xhrStatus = xhr.status || OK_RESPONSE;
  135. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  136. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  137. if (pendingRequest.onError) {
  138. pendingRequest.onError(xhr.status);
  139. }
  140. return;
  141. }
  142. const chunk = getArrayBuffer(xhr);
  143. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  144. const rangeHeader = xhr.getResponseHeader("Content-Range");
  145. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  146. pendingRequest.onDone({
  147. begin: parseInt(matches[1], 10),
  148. chunk
  149. });
  150. } else if (chunk) {
  151. pendingRequest.onDone({
  152. begin: 0,
  153. chunk
  154. });
  155. } else if (pendingRequest.onError) {
  156. pendingRequest.onError(xhr.status);
  157. }
  158. }
  159. hasPendingRequests() {
  160. for (const xhrId in this.pendingRequests) {
  161. return true;
  162. }
  163. return false;
  164. }
  165. getRequestXhr(xhrId) {
  166. return this.pendingRequests[xhrId].xhr;
  167. }
  168. isPendingRequest(xhrId) {
  169. return xhrId in this.pendingRequests;
  170. }
  171. abortAllRequests() {
  172. for (const xhrId in this.pendingRequests) {
  173. this.abortRequest(xhrId | 0);
  174. }
  175. }
  176. abortRequest(xhrId) {
  177. const xhr = this.pendingRequests[xhrId].xhr;
  178. delete this.pendingRequests[xhrId];
  179. xhr.abort();
  180. }
  181. }
  182. class PDFNetworkStream {
  183. constructor(source) {
  184. this._source = source;
  185. this._manager = new NetworkManager(source.url, {
  186. httpHeaders: source.httpHeaders,
  187. withCredentials: source.withCredentials
  188. });
  189. this._rangeChunkSize = source.rangeChunkSize;
  190. this._fullRequestReader = null;
  191. this._rangeRequestReaders = [];
  192. }
  193. _onRangeRequestReaderClosed(reader) {
  194. const i = this._rangeRequestReaders.indexOf(reader);
  195. if (i >= 0) {
  196. this._rangeRequestReaders.splice(i, 1);
  197. }
  198. }
  199. getFullReader() {
  200. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  201. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  202. return this._fullRequestReader;
  203. }
  204. getRangeReader(begin, end) {
  205. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  206. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  207. this._rangeRequestReaders.push(reader);
  208. return reader;
  209. }
  210. cancelAllRequests(reason) {
  211. if (this._fullRequestReader) {
  212. this._fullRequestReader.cancel(reason);
  213. }
  214. const readers = this._rangeRequestReaders.slice(0);
  215. readers.forEach(function (reader) {
  216. reader.cancel(reason);
  217. });
  218. }
  219. }
  220. exports.PDFNetworkStream = PDFNetworkStream;
  221. class PDFNetworkStreamFullRequestReader {
  222. constructor(manager, source) {
  223. this._manager = manager;
  224. const args = {
  225. onHeadersReceived: this._onHeadersReceived.bind(this),
  226. onDone: this._onDone.bind(this),
  227. onError: this._onError.bind(this),
  228. onProgress: this._onProgress.bind(this)
  229. };
  230. this._url = source.url;
  231. this._fullRequestId = manager.requestFull(args);
  232. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  233. this._disableRange = source.disableRange || false;
  234. this._contentLength = source.length;
  235. this._rangeChunkSize = source.rangeChunkSize;
  236. if (!this._rangeChunkSize && !this._disableRange) {
  237. this._disableRange = true;
  238. }
  239. this._isStreamingSupported = false;
  240. this._isRangeSupported = false;
  241. this._cachedChunks = [];
  242. this._requests = [];
  243. this._done = false;
  244. this._storedError = undefined;
  245. this._filename = null;
  246. this.onProgress = null;
  247. }
  248. _onHeadersReceived() {
  249. const fullRequestXhrId = this._fullRequestId;
  250. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  251. const getResponseHeader = name => {
  252. return fullRequestXhr.getResponseHeader(name);
  253. };
  254. const {
  255. allowRangeRequests,
  256. suggestedLength
  257. } = (0, _network_utils.validateRangeRequestCapabilities)({
  258. getResponseHeader,
  259. isHttp: this._manager.isHttp,
  260. rangeChunkSize: this._rangeChunkSize,
  261. disableRange: this._disableRange
  262. });
  263. if (allowRangeRequests) {
  264. this._isRangeSupported = true;
  265. }
  266. this._contentLength = suggestedLength || this._contentLength;
  267. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  268. if (this._isRangeSupported) {
  269. this._manager.abortRequest(fullRequestXhrId);
  270. }
  271. this._headersReceivedCapability.resolve();
  272. }
  273. _onDone(args) {
  274. if (args) {
  275. if (this._requests.length > 0) {
  276. const requestCapability = this._requests.shift();
  277. requestCapability.resolve({
  278. value: args.chunk,
  279. done: false
  280. });
  281. } else {
  282. this._cachedChunks.push(args.chunk);
  283. }
  284. }
  285. this._done = true;
  286. if (this._cachedChunks.length > 0) {
  287. return;
  288. }
  289. this._requests.forEach(function (requestCapability) {
  290. requestCapability.resolve({
  291. value: undefined,
  292. done: true
  293. });
  294. });
  295. this._requests = [];
  296. }
  297. _onError(status) {
  298. const url = this._url;
  299. const exception = (0, _network_utils.createResponseStatusError)(status, url);
  300. this._storedError = exception;
  301. this._headersReceivedCapability.reject(exception);
  302. this._requests.forEach(function (requestCapability) {
  303. requestCapability.reject(exception);
  304. });
  305. this._requests = [];
  306. this._cachedChunks = [];
  307. }
  308. _onProgress(data) {
  309. if (this.onProgress) {
  310. this.onProgress({
  311. loaded: data.loaded,
  312. total: data.lengthComputable ? data.total : this._contentLength
  313. });
  314. }
  315. }
  316. get filename() {
  317. return this._filename;
  318. }
  319. get isRangeSupported() {
  320. return this._isRangeSupported;
  321. }
  322. get isStreamingSupported() {
  323. return this._isStreamingSupported;
  324. }
  325. get contentLength() {
  326. return this._contentLength;
  327. }
  328. get headersReady() {
  329. return this._headersReceivedCapability.promise;
  330. }
  331. async read() {
  332. if (this._storedError) {
  333. throw this._storedError;
  334. }
  335. if (this._cachedChunks.length > 0) {
  336. const chunk = this._cachedChunks.shift();
  337. return {
  338. value: chunk,
  339. done: false
  340. };
  341. }
  342. if (this._done) {
  343. return {
  344. value: undefined,
  345. done: true
  346. };
  347. }
  348. const requestCapability = (0, _util.createPromiseCapability)();
  349. this._requests.push(requestCapability);
  350. return requestCapability.promise;
  351. }
  352. cancel(reason) {
  353. this._done = true;
  354. this._headersReceivedCapability.reject(reason);
  355. this._requests.forEach(function (requestCapability) {
  356. requestCapability.resolve({
  357. value: undefined,
  358. done: true
  359. });
  360. });
  361. this._requests = [];
  362. if (this._manager.isPendingRequest(this._fullRequestId)) {
  363. this._manager.abortRequest(this._fullRequestId);
  364. }
  365. this._fullRequestReader = null;
  366. }
  367. }
  368. class PDFNetworkStreamRangeRequestReader {
  369. constructor(manager, begin, end) {
  370. this._manager = manager;
  371. const args = {
  372. onDone: this._onDone.bind(this),
  373. onProgress: this._onProgress.bind(this)
  374. };
  375. this._requestId = manager.requestRange(begin, end, args);
  376. this._requests = [];
  377. this._queuedChunk = null;
  378. this._done = false;
  379. this.onProgress = null;
  380. this.onClosed = null;
  381. }
  382. _close() {
  383. if (this.onClosed) {
  384. this.onClosed(this);
  385. }
  386. }
  387. _onDone(data) {
  388. const chunk = data.chunk;
  389. if (this._requests.length > 0) {
  390. const requestCapability = this._requests.shift();
  391. requestCapability.resolve({
  392. value: chunk,
  393. done: false
  394. });
  395. } else {
  396. this._queuedChunk = chunk;
  397. }
  398. this._done = true;
  399. this._requests.forEach(function (requestCapability) {
  400. requestCapability.resolve({
  401. value: undefined,
  402. done: true
  403. });
  404. });
  405. this._requests = [];
  406. this._close();
  407. }
  408. _onProgress(evt) {
  409. if (!this.isStreamingSupported && this.onProgress) {
  410. this.onProgress({
  411. loaded: evt.loaded
  412. });
  413. }
  414. }
  415. get isStreamingSupported() {
  416. return false;
  417. }
  418. async read() {
  419. if (this._queuedChunk !== null) {
  420. const chunk = this._queuedChunk;
  421. this._queuedChunk = null;
  422. return {
  423. value: chunk,
  424. done: false
  425. };
  426. }
  427. if (this._done) {
  428. return {
  429. value: undefined,
  430. done: true
  431. };
  432. }
  433. const requestCapability = (0, _util.createPromiseCapability)();
  434. this._requests.push(requestCapability);
  435. return requestCapability.promise;
  436. }
  437. cancel(reason) {
  438. this._done = true;
  439. this._requests.forEach(function (requestCapability) {
  440. requestCapability.resolve({
  441. value: undefined,
  442. done: true
  443. });
  444. });
  445. this._requests = [];
  446. if (this._manager.isPendingRequest(this._requestId)) {
  447. this._manager.abortRequest(this._requestId);
  448. }
  449. this._close();
  450. }
  451. }