2
0

network.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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. getRequestXhr(xhrId) {
  160. return this.pendingRequests[xhrId].xhr;
  161. }
  162. isPendingRequest(xhrId) {
  163. return xhrId in this.pendingRequests;
  164. }
  165. abortRequest(xhrId) {
  166. const xhr = this.pendingRequests[xhrId].xhr;
  167. delete this.pendingRequests[xhrId];
  168. xhr.abort();
  169. }
  170. }
  171. class PDFNetworkStream {
  172. constructor(source) {
  173. this._source = source;
  174. this._manager = new NetworkManager(source.url, {
  175. httpHeaders: source.httpHeaders,
  176. withCredentials: source.withCredentials
  177. });
  178. this._rangeChunkSize = source.rangeChunkSize;
  179. this._fullRequestReader = null;
  180. this._rangeRequestReaders = [];
  181. }
  182. _onRangeRequestReaderClosed(reader) {
  183. const i = this._rangeRequestReaders.indexOf(reader);
  184. if (i >= 0) {
  185. this._rangeRequestReaders.splice(i, 1);
  186. }
  187. }
  188. getFullReader() {
  189. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  190. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  191. return this._fullRequestReader;
  192. }
  193. getRangeReader(begin, end) {
  194. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  195. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  196. this._rangeRequestReaders.push(reader);
  197. return reader;
  198. }
  199. cancelAllRequests(reason) {
  200. if (this._fullRequestReader) {
  201. this._fullRequestReader.cancel(reason);
  202. }
  203. for (const reader of this._rangeRequestReaders.slice(0)) {
  204. reader.cancel(reason);
  205. }
  206. }
  207. }
  208. exports.PDFNetworkStream = PDFNetworkStream;
  209. class PDFNetworkStreamFullRequestReader {
  210. constructor(manager, source) {
  211. this._manager = manager;
  212. const args = {
  213. onHeadersReceived: this._onHeadersReceived.bind(this),
  214. onDone: this._onDone.bind(this),
  215. onError: this._onError.bind(this),
  216. onProgress: this._onProgress.bind(this)
  217. };
  218. this._url = source.url;
  219. this._fullRequestId = manager.requestFull(args);
  220. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  221. this._disableRange = source.disableRange || false;
  222. this._contentLength = source.length;
  223. this._rangeChunkSize = source.rangeChunkSize;
  224. if (!this._rangeChunkSize && !this._disableRange) {
  225. this._disableRange = true;
  226. }
  227. this._isStreamingSupported = false;
  228. this._isRangeSupported = false;
  229. this._cachedChunks = [];
  230. this._requests = [];
  231. this._done = false;
  232. this._storedError = undefined;
  233. this._filename = null;
  234. this.onProgress = null;
  235. }
  236. _onHeadersReceived() {
  237. const fullRequestXhrId = this._fullRequestId;
  238. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  239. const getResponseHeader = name => {
  240. return fullRequestXhr.getResponseHeader(name);
  241. };
  242. const {
  243. allowRangeRequests,
  244. suggestedLength
  245. } = (0, _network_utils.validateRangeRequestCapabilities)({
  246. getResponseHeader,
  247. isHttp: this._manager.isHttp,
  248. rangeChunkSize: this._rangeChunkSize,
  249. disableRange: this._disableRange
  250. });
  251. if (allowRangeRequests) {
  252. this._isRangeSupported = true;
  253. }
  254. this._contentLength = suggestedLength || this._contentLength;
  255. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  256. if (this._isRangeSupported) {
  257. this._manager.abortRequest(fullRequestXhrId);
  258. }
  259. this._headersReceivedCapability.resolve();
  260. }
  261. _onDone(args) {
  262. if (args) {
  263. if (this._requests.length > 0) {
  264. const requestCapability = this._requests.shift();
  265. requestCapability.resolve({
  266. value: args.chunk,
  267. done: false
  268. });
  269. } else {
  270. this._cachedChunks.push(args.chunk);
  271. }
  272. }
  273. this._done = true;
  274. if (this._cachedChunks.length > 0) {
  275. return;
  276. }
  277. for (const requestCapability of this._requests) {
  278. requestCapability.resolve({
  279. value: undefined,
  280. done: true
  281. });
  282. }
  283. this._requests.length = 0;
  284. }
  285. _onError(status) {
  286. const url = this._url;
  287. const exception = (0, _network_utils.createResponseStatusError)(status, url);
  288. this._storedError = exception;
  289. this._headersReceivedCapability.reject(exception);
  290. for (const requestCapability of this._requests) {
  291. requestCapability.reject(exception);
  292. }
  293. this._requests.length = 0;
  294. this._cachedChunks.length = 0;
  295. }
  296. _onProgress(data) {
  297. if (this.onProgress) {
  298. this.onProgress({
  299. loaded: data.loaded,
  300. total: data.lengthComputable ? data.total : this._contentLength
  301. });
  302. }
  303. }
  304. get filename() {
  305. return this._filename;
  306. }
  307. get isRangeSupported() {
  308. return this._isRangeSupported;
  309. }
  310. get isStreamingSupported() {
  311. return this._isStreamingSupported;
  312. }
  313. get contentLength() {
  314. return this._contentLength;
  315. }
  316. get headersReady() {
  317. return this._headersReceivedCapability.promise;
  318. }
  319. async read() {
  320. if (this._storedError) {
  321. throw this._storedError;
  322. }
  323. if (this._cachedChunks.length > 0) {
  324. const chunk = this._cachedChunks.shift();
  325. return {
  326. value: chunk,
  327. done: false
  328. };
  329. }
  330. if (this._done) {
  331. return {
  332. value: undefined,
  333. done: true
  334. };
  335. }
  336. const requestCapability = (0, _util.createPromiseCapability)();
  337. this._requests.push(requestCapability);
  338. return requestCapability.promise;
  339. }
  340. cancel(reason) {
  341. this._done = true;
  342. this._headersReceivedCapability.reject(reason);
  343. for (const requestCapability of this._requests) {
  344. requestCapability.resolve({
  345. value: undefined,
  346. done: true
  347. });
  348. }
  349. this._requests.length = 0;
  350. if (this._manager.isPendingRequest(this._fullRequestId)) {
  351. this._manager.abortRequest(this._fullRequestId);
  352. }
  353. this._fullRequestReader = null;
  354. }
  355. }
  356. class PDFNetworkStreamRangeRequestReader {
  357. constructor(manager, begin, end) {
  358. this._manager = manager;
  359. const args = {
  360. onDone: this._onDone.bind(this),
  361. onProgress: this._onProgress.bind(this)
  362. };
  363. this._requestId = manager.requestRange(begin, end, args);
  364. this._requests = [];
  365. this._queuedChunk = null;
  366. this._done = false;
  367. this.onProgress = null;
  368. this.onClosed = null;
  369. }
  370. _close() {
  371. if (this.onClosed) {
  372. this.onClosed(this);
  373. }
  374. }
  375. _onDone(data) {
  376. const chunk = data.chunk;
  377. if (this._requests.length > 0) {
  378. const requestCapability = this._requests.shift();
  379. requestCapability.resolve({
  380. value: chunk,
  381. done: false
  382. });
  383. } else {
  384. this._queuedChunk = chunk;
  385. }
  386. this._done = true;
  387. for (const requestCapability of this._requests) {
  388. requestCapability.resolve({
  389. value: undefined,
  390. done: true
  391. });
  392. }
  393. this._requests.length = 0;
  394. this._close();
  395. }
  396. _onProgress(evt) {
  397. if (!this.isStreamingSupported && this.onProgress) {
  398. this.onProgress({
  399. loaded: evt.loaded
  400. });
  401. }
  402. }
  403. get isStreamingSupported() {
  404. return false;
  405. }
  406. async read() {
  407. if (this._queuedChunk !== null) {
  408. const chunk = this._queuedChunk;
  409. this._queuedChunk = null;
  410. return {
  411. value: chunk,
  412. done: false
  413. };
  414. }
  415. if (this._done) {
  416. return {
  417. value: undefined,
  418. done: true
  419. };
  420. }
  421. const requestCapability = (0, _util.createPromiseCapability)();
  422. this._requests.push(requestCapability);
  423. return requestCapability.promise;
  424. }
  425. cancel(reason) {
  426. this._done = true;
  427. for (const requestCapability of this._requests) {
  428. requestCapability.resolve({
  429. value: undefined,
  430. done: true
  431. });
  432. }
  433. this._requests.length = 0;
  434. if (this._manager.isPendingRequest(this._requestId)) {
  435. this._manager.abortRequest(this._requestId);
  436. }
  437. this._close();
  438. }
  439. }