2
0

network.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. 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. const readers = this._rangeRequestReaders.slice(0);
  204. readers.forEach(function (reader) {
  205. reader.cancel(reason);
  206. });
  207. }
  208. }
  209. exports.PDFNetworkStream = PDFNetworkStream;
  210. class PDFNetworkStreamFullRequestReader {
  211. constructor(manager, source) {
  212. this._manager = manager;
  213. const args = {
  214. onHeadersReceived: this._onHeadersReceived.bind(this),
  215. onDone: this._onDone.bind(this),
  216. onError: this._onError.bind(this),
  217. onProgress: this._onProgress.bind(this)
  218. };
  219. this._url = source.url;
  220. this._fullRequestId = manager.requestFull(args);
  221. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  222. this._disableRange = source.disableRange || false;
  223. this._contentLength = source.length;
  224. this._rangeChunkSize = source.rangeChunkSize;
  225. if (!this._rangeChunkSize && !this._disableRange) {
  226. this._disableRange = true;
  227. }
  228. this._isStreamingSupported = false;
  229. this._isRangeSupported = false;
  230. this._cachedChunks = [];
  231. this._requests = [];
  232. this._done = false;
  233. this._storedError = undefined;
  234. this._filename = null;
  235. this.onProgress = null;
  236. }
  237. _onHeadersReceived() {
  238. const fullRequestXhrId = this._fullRequestId;
  239. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  240. const getResponseHeader = name => {
  241. return fullRequestXhr.getResponseHeader(name);
  242. };
  243. const {
  244. allowRangeRequests,
  245. suggestedLength
  246. } = (0, _network_utils.validateRangeRequestCapabilities)({
  247. getResponseHeader,
  248. isHttp: this._manager.isHttp,
  249. rangeChunkSize: this._rangeChunkSize,
  250. disableRange: this._disableRange
  251. });
  252. if (allowRangeRequests) {
  253. this._isRangeSupported = true;
  254. }
  255. this._contentLength = suggestedLength || this._contentLength;
  256. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  257. if (this._isRangeSupported) {
  258. this._manager.abortRequest(fullRequestXhrId);
  259. }
  260. this._headersReceivedCapability.resolve();
  261. }
  262. _onDone(args) {
  263. if (args) {
  264. if (this._requests.length > 0) {
  265. const requestCapability = this._requests.shift();
  266. requestCapability.resolve({
  267. value: args.chunk,
  268. done: false
  269. });
  270. } else {
  271. this._cachedChunks.push(args.chunk);
  272. }
  273. }
  274. this._done = true;
  275. if (this._cachedChunks.length > 0) {
  276. return;
  277. }
  278. this._requests.forEach(function (requestCapability) {
  279. requestCapability.resolve({
  280. value: undefined,
  281. done: true
  282. });
  283. });
  284. this._requests = [];
  285. }
  286. _onError(status) {
  287. const url = this._url;
  288. const exception = (0, _network_utils.createResponseStatusError)(status, url);
  289. this._storedError = exception;
  290. this._headersReceivedCapability.reject(exception);
  291. this._requests.forEach(function (requestCapability) {
  292. requestCapability.reject(exception);
  293. });
  294. this._requests = [];
  295. this._cachedChunks = [];
  296. }
  297. _onProgress(data) {
  298. if (this.onProgress) {
  299. this.onProgress({
  300. loaded: data.loaded,
  301. total: data.lengthComputable ? data.total : this._contentLength
  302. });
  303. }
  304. }
  305. get filename() {
  306. return this._filename;
  307. }
  308. get isRangeSupported() {
  309. return this._isRangeSupported;
  310. }
  311. get isStreamingSupported() {
  312. return this._isStreamingSupported;
  313. }
  314. get contentLength() {
  315. return this._contentLength;
  316. }
  317. get headersReady() {
  318. return this._headersReceivedCapability.promise;
  319. }
  320. async read() {
  321. if (this._storedError) {
  322. throw this._storedError;
  323. }
  324. if (this._cachedChunks.length > 0) {
  325. const chunk = this._cachedChunks.shift();
  326. return {
  327. value: chunk,
  328. done: false
  329. };
  330. }
  331. if (this._done) {
  332. return {
  333. value: undefined,
  334. done: true
  335. };
  336. }
  337. const requestCapability = (0, _util.createPromiseCapability)();
  338. this._requests.push(requestCapability);
  339. return requestCapability.promise;
  340. }
  341. cancel(reason) {
  342. this._done = true;
  343. this._headersReceivedCapability.reject(reason);
  344. this._requests.forEach(function (requestCapability) {
  345. requestCapability.resolve({
  346. value: undefined,
  347. done: true
  348. });
  349. });
  350. this._requests = [];
  351. if (this._manager.isPendingRequest(this._fullRequestId)) {
  352. this._manager.abortRequest(this._fullRequestId);
  353. }
  354. this._fullRequestReader = null;
  355. }
  356. }
  357. class PDFNetworkStreamRangeRequestReader {
  358. constructor(manager, begin, end) {
  359. this._manager = manager;
  360. const args = {
  361. onDone: this._onDone.bind(this),
  362. onProgress: this._onProgress.bind(this)
  363. };
  364. this._requestId = manager.requestRange(begin, end, args);
  365. this._requests = [];
  366. this._queuedChunk = null;
  367. this._done = false;
  368. this.onProgress = null;
  369. this.onClosed = null;
  370. }
  371. _close() {
  372. if (this.onClosed) {
  373. this.onClosed(this);
  374. }
  375. }
  376. _onDone(data) {
  377. const chunk = data.chunk;
  378. if (this._requests.length > 0) {
  379. const requestCapability = this._requests.shift();
  380. requestCapability.resolve({
  381. value: chunk,
  382. done: false
  383. });
  384. } else {
  385. this._queuedChunk = chunk;
  386. }
  387. this._done = true;
  388. this._requests.forEach(function (requestCapability) {
  389. requestCapability.resolve({
  390. value: undefined,
  391. done: true
  392. });
  393. });
  394. this._requests = [];
  395. this._close();
  396. }
  397. _onProgress(evt) {
  398. if (!this.isStreamingSupported && this.onProgress) {
  399. this.onProgress({
  400. loaded: evt.loaded
  401. });
  402. }
  403. }
  404. get isStreamingSupported() {
  405. return false;
  406. }
  407. async read() {
  408. if (this._queuedChunk !== null) {
  409. const chunk = this._queuedChunk;
  410. this._queuedChunk = null;
  411. return {
  412. value: chunk,
  413. done: false
  414. };
  415. }
  416. if (this._done) {
  417. return {
  418. value: undefined,
  419. done: true
  420. };
  421. }
  422. const requestCapability = (0, _util.createPromiseCapability)();
  423. this._requests.push(requestCapability);
  424. return requestCapability.promise;
  425. }
  426. cancel(reason) {
  427. this._done = true;
  428. this._requests.forEach(function (requestCapability) {
  429. requestCapability.resolve({
  430. value: undefined,
  431. done: true
  432. });
  433. });
  434. this._requests = [];
  435. if (this._manager.isPendingRequest(this._requestId)) {
  436. this._manager.abortRequest(this._requestId);
  437. }
  438. this._close();
  439. }
  440. }