node_stream.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 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.PDFNodeStream = undefined;
  27. var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28. var _util = require('../shared/util');
  29. var _network_utils = require('./network_utils');
  30. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  31. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  32. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33. var fs = require('fs');
  34. var http = require('http');
  35. var https = require('https');
  36. var url = require('url');
  37. var fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  38. function parseUrl(sourceUrl) {
  39. var parsedUrl = url.parse(sourceUrl);
  40. if (parsedUrl.protocol === 'file:' || parsedUrl.host) {
  41. return parsedUrl;
  42. }
  43. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  44. return url.parse('file:///' + sourceUrl);
  45. }
  46. if (!parsedUrl.host) {
  47. parsedUrl.protocol = 'file:';
  48. }
  49. return parsedUrl;
  50. }
  51. var PDFNodeStream = function () {
  52. function PDFNodeStream(source) {
  53. _classCallCheck(this, PDFNodeStream);
  54. this.source = source;
  55. this.url = parseUrl(source.url);
  56. this.isHttp = this.url.protocol === 'http:' || this.url.protocol === 'https:';
  57. this.isFsUrl = this.url.protocol === 'file:';
  58. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  59. this._fullRequest = null;
  60. this._rangeRequestReaders = [];
  61. }
  62. _createClass(PDFNodeStream, [{
  63. key: 'getFullReader',
  64. value: function getFullReader() {
  65. (0, _util.assert)(!this._fullRequest);
  66. this._fullRequest = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  67. return this._fullRequest;
  68. }
  69. }, {
  70. key: 'getRangeReader',
  71. value: function getRangeReader(start, end) {
  72. var rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  73. this._rangeRequestReaders.push(rangeReader);
  74. return rangeReader;
  75. }
  76. }, {
  77. key: 'cancelAllRequests',
  78. value: function cancelAllRequests(reason) {
  79. if (this._fullRequest) {
  80. this._fullRequest.cancel(reason);
  81. }
  82. var readers = this._rangeRequestReaders.slice(0);
  83. readers.forEach(function (reader) {
  84. reader.cancel(reason);
  85. });
  86. }
  87. }]);
  88. return PDFNodeStream;
  89. }();
  90. var BaseFullReader = function () {
  91. function BaseFullReader(stream) {
  92. _classCallCheck(this, BaseFullReader);
  93. this._url = stream.url;
  94. this._done = false;
  95. this._errored = false;
  96. this._reason = null;
  97. this.onProgress = null;
  98. var source = stream.source;
  99. this._contentLength = source.length;
  100. this._loaded = 0;
  101. this._filename = null;
  102. this._disableRange = source.disableRange || false;
  103. this._rangeChunkSize = source.rangeChunkSize;
  104. if (!this._rangeChunkSize && !this._disableRange) {
  105. this._disableRange = true;
  106. }
  107. this._isStreamingSupported = !source.disableStream;
  108. this._isRangeSupported = !source.disableRange;
  109. this._readableStream = null;
  110. this._readCapability = (0, _util.createPromiseCapability)();
  111. this._headersCapability = (0, _util.createPromiseCapability)();
  112. }
  113. _createClass(BaseFullReader, [{
  114. key: 'read',
  115. value: function read() {
  116. var _this = this;
  117. return this._readCapability.promise.then(function () {
  118. if (_this._done) {
  119. return Promise.resolve({
  120. value: undefined,
  121. done: true
  122. });
  123. }
  124. if (_this._errored) {
  125. return Promise.reject(_this._reason);
  126. }
  127. var chunk = _this._readableStream.read();
  128. if (chunk === null) {
  129. _this._readCapability = (0, _util.createPromiseCapability)();
  130. return _this.read();
  131. }
  132. _this._loaded += chunk.length;
  133. if (_this.onProgress) {
  134. _this.onProgress({
  135. loaded: _this._loaded,
  136. total: _this._contentLength
  137. });
  138. }
  139. var buffer = new Uint8Array(chunk).buffer;
  140. return Promise.resolve({
  141. value: buffer,
  142. done: false
  143. });
  144. });
  145. }
  146. }, {
  147. key: 'cancel',
  148. value: function cancel(reason) {
  149. if (!this._readableStream) {
  150. this._error(reason);
  151. return;
  152. }
  153. this._readableStream.destroy(reason);
  154. }
  155. }, {
  156. key: '_error',
  157. value: function _error(reason) {
  158. this._errored = true;
  159. this._reason = reason;
  160. this._readCapability.resolve();
  161. }
  162. }, {
  163. key: '_setReadableStream',
  164. value: function _setReadableStream(readableStream) {
  165. var _this2 = this;
  166. this._readableStream = readableStream;
  167. readableStream.on('readable', function () {
  168. _this2._readCapability.resolve();
  169. });
  170. readableStream.on('end', function () {
  171. readableStream.destroy();
  172. _this2._done = true;
  173. _this2._readCapability.resolve();
  174. });
  175. readableStream.on('error', function (reason) {
  176. _this2._error(reason);
  177. });
  178. if (!this._isStreamingSupported && this._isRangeSupported) {
  179. this._error(new _util.AbortException('streaming is disabled'));
  180. }
  181. if (this._errored) {
  182. this._readableStream.destroy(this._reason);
  183. }
  184. }
  185. }, {
  186. key: 'headersReady',
  187. get: function get() {
  188. return this._headersCapability.promise;
  189. }
  190. }, {
  191. key: 'filename',
  192. get: function get() {
  193. return this._filename;
  194. }
  195. }, {
  196. key: 'contentLength',
  197. get: function get() {
  198. return this._contentLength;
  199. }
  200. }, {
  201. key: 'isRangeSupported',
  202. get: function get() {
  203. return this._isRangeSupported;
  204. }
  205. }, {
  206. key: 'isStreamingSupported',
  207. get: function get() {
  208. return this._isStreamingSupported;
  209. }
  210. }]);
  211. return BaseFullReader;
  212. }();
  213. var BaseRangeReader = function () {
  214. function BaseRangeReader(stream) {
  215. _classCallCheck(this, BaseRangeReader);
  216. this._url = stream.url;
  217. this._done = false;
  218. this._errored = false;
  219. this._reason = null;
  220. this.onProgress = null;
  221. this._loaded = 0;
  222. this._readableStream = null;
  223. this._readCapability = (0, _util.createPromiseCapability)();
  224. var source = stream.source;
  225. this._isStreamingSupported = !source.disableStream;
  226. }
  227. _createClass(BaseRangeReader, [{
  228. key: 'read',
  229. value: function read() {
  230. var _this3 = this;
  231. return this._readCapability.promise.then(function () {
  232. if (_this3._done) {
  233. return Promise.resolve({
  234. value: undefined,
  235. done: true
  236. });
  237. }
  238. if (_this3._errored) {
  239. return Promise.reject(_this3._reason);
  240. }
  241. var chunk = _this3._readableStream.read();
  242. if (chunk === null) {
  243. _this3._readCapability = (0, _util.createPromiseCapability)();
  244. return _this3.read();
  245. }
  246. _this3._loaded += chunk.length;
  247. if (_this3.onProgress) {
  248. _this3.onProgress({ loaded: _this3._loaded });
  249. }
  250. var buffer = new Uint8Array(chunk).buffer;
  251. return Promise.resolve({
  252. value: buffer,
  253. done: false
  254. });
  255. });
  256. }
  257. }, {
  258. key: 'cancel',
  259. value: function cancel(reason) {
  260. if (!this._readableStream) {
  261. this._error(reason);
  262. return;
  263. }
  264. this._readableStream.destroy(reason);
  265. }
  266. }, {
  267. key: '_error',
  268. value: function _error(reason) {
  269. this._errored = true;
  270. this._reason = reason;
  271. this._readCapability.resolve();
  272. }
  273. }, {
  274. key: '_setReadableStream',
  275. value: function _setReadableStream(readableStream) {
  276. var _this4 = this;
  277. this._readableStream = readableStream;
  278. readableStream.on('readable', function () {
  279. _this4._readCapability.resolve();
  280. });
  281. readableStream.on('end', function () {
  282. readableStream.destroy();
  283. _this4._done = true;
  284. _this4._readCapability.resolve();
  285. });
  286. readableStream.on('error', function (reason) {
  287. _this4._error(reason);
  288. });
  289. if (this._errored) {
  290. this._readableStream.destroy(this._reason);
  291. }
  292. }
  293. }, {
  294. key: 'isStreamingSupported',
  295. get: function get() {
  296. return this._isStreamingSupported;
  297. }
  298. }]);
  299. return BaseRangeReader;
  300. }();
  301. function createRequestOptions(url, headers) {
  302. return {
  303. protocol: url.protocol,
  304. auth: url.auth,
  305. host: url.hostname,
  306. port: url.port,
  307. path: url.path,
  308. method: 'GET',
  309. headers: headers
  310. };
  311. }
  312. var PDFNodeStreamFullReader = function (_BaseFullReader) {
  313. _inherits(PDFNodeStreamFullReader, _BaseFullReader);
  314. function PDFNodeStreamFullReader(stream) {
  315. _classCallCheck(this, PDFNodeStreamFullReader);
  316. var _this5 = _possibleConstructorReturn(this, (PDFNodeStreamFullReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFullReader)).call(this, stream));
  317. var handleResponse = function handleResponse(response) {
  318. _this5._headersCapability.resolve();
  319. _this5._setReadableStream(response);
  320. var getResponseHeader = function getResponseHeader(name) {
  321. return _this5._readableStream.headers[name.toLowerCase()];
  322. };
  323. var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
  324. getResponseHeader: getResponseHeader,
  325. isHttp: stream.isHttp,
  326. rangeChunkSize: _this5._rangeChunkSize,
  327. disableRange: _this5._disableRange
  328. }),
  329. allowRangeRequests = _validateRangeRequest.allowRangeRequests,
  330. suggestedLength = _validateRangeRequest.suggestedLength;
  331. _this5._isRangeSupported = allowRangeRequests;
  332. _this5._contentLength = suggestedLength || _this5._contentLength;
  333. _this5._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  334. };
  335. _this5._request = null;
  336. if (_this5._url.protocol === 'http:') {
  337. _this5._request = http.request(createRequestOptions(_this5._url, stream.httpHeaders), handleResponse);
  338. } else {
  339. _this5._request = https.request(createRequestOptions(_this5._url, stream.httpHeaders), handleResponse);
  340. }
  341. _this5._request.on('error', function (reason) {
  342. _this5._errored = true;
  343. _this5._reason = reason;
  344. _this5._headersCapability.reject(reason);
  345. });
  346. _this5._request.end();
  347. return _this5;
  348. }
  349. return PDFNodeStreamFullReader;
  350. }(BaseFullReader);
  351. var PDFNodeStreamRangeReader = function (_BaseRangeReader) {
  352. _inherits(PDFNodeStreamRangeReader, _BaseRangeReader);
  353. function PDFNodeStreamRangeReader(stream, start, end) {
  354. _classCallCheck(this, PDFNodeStreamRangeReader);
  355. var _this6 = _possibleConstructorReturn(this, (PDFNodeStreamRangeReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamRangeReader)).call(this, stream));
  356. _this6._httpHeaders = {};
  357. for (var property in stream.httpHeaders) {
  358. var value = stream.httpHeaders[property];
  359. if (typeof value === 'undefined') {
  360. continue;
  361. }
  362. _this6._httpHeaders[property] = value;
  363. }
  364. _this6._httpHeaders['Range'] = 'bytes=' + start + '-' + (end - 1);
  365. _this6._request = null;
  366. if (_this6._url.protocol === 'http:') {
  367. _this6._request = http.request(createRequestOptions(_this6._url, _this6._httpHeaders), function (response) {
  368. _this6._setReadableStream(response);
  369. });
  370. } else {
  371. _this6._request = https.request(createRequestOptions(_this6._url, _this6._httpHeaders), function (response) {
  372. _this6._setReadableStream(response);
  373. });
  374. }
  375. _this6._request.on('error', function (reason) {
  376. _this6._errored = true;
  377. _this6._reason = reason;
  378. });
  379. _this6._request.end();
  380. return _this6;
  381. }
  382. return PDFNodeStreamRangeReader;
  383. }(BaseRangeReader);
  384. var PDFNodeStreamFsFullReader = function (_BaseFullReader2) {
  385. _inherits(PDFNodeStreamFsFullReader, _BaseFullReader2);
  386. function PDFNodeStreamFsFullReader(stream) {
  387. _classCallCheck(this, PDFNodeStreamFsFullReader);
  388. var _this7 = _possibleConstructorReturn(this, (PDFNodeStreamFsFullReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsFullReader)).call(this, stream));
  389. var path = decodeURIComponent(_this7._url.path);
  390. if (fileUriRegex.test(_this7._url.href)) {
  391. path = path.replace(/^\//, '');
  392. }
  393. fs.lstat(path, function (error, stat) {
  394. if (error) {
  395. _this7._errored = true;
  396. _this7._reason = error;
  397. _this7._headersCapability.reject(error);
  398. return;
  399. }
  400. _this7._contentLength = stat.size;
  401. _this7._setReadableStream(fs.createReadStream(path));
  402. _this7._headersCapability.resolve();
  403. });
  404. return _this7;
  405. }
  406. return PDFNodeStreamFsFullReader;
  407. }(BaseFullReader);
  408. var PDFNodeStreamFsRangeReader = function (_BaseRangeReader2) {
  409. _inherits(PDFNodeStreamFsRangeReader, _BaseRangeReader2);
  410. function PDFNodeStreamFsRangeReader(stream, start, end) {
  411. _classCallCheck(this, PDFNodeStreamFsRangeReader);
  412. var _this8 = _possibleConstructorReturn(this, (PDFNodeStreamFsRangeReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsRangeReader)).call(this, stream));
  413. var path = decodeURIComponent(_this8._url.path);
  414. if (fileUriRegex.test(_this8._url.href)) {
  415. path = path.replace(/^\//, '');
  416. }
  417. _this8._setReadableStream(fs.createReadStream(path, {
  418. start: start,
  419. end: end - 1
  420. }));
  421. return _this8;
  422. }
  423. return PDFNodeStreamFsRangeReader;
  424. }(BaseRangeReader);
  425. exports.PDFNodeStream = PDFNodeStream;