uristream.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. var util = require('util'),
  2. url = require('url'),
  3. zlib = require('zlib'),
  4. assert = require('assert');
  5. var request = require('request'),
  6. extend = require('xtend'),
  7. oncemore = require('./oncemore'),
  8. debug = require('debug')('hls:uristream');
  9. try {
  10. var Readable = require('stream').Readable;
  11. assert(Readable);
  12. } catch (e) {
  13. var Readable = require('readable-stream');
  14. }
  15. function noop() {};
  16. var pkg = require('../package');
  17. var DEFAULT_AGENT = util.format('%s/v%s (http://github.com/kanongil/node-hls-tools) node.js/%s', pkg.name, pkg.version, process.version);
  18. module.exports = uristream;
  19. uristream.UriFetchStream = UriFetchStream;
  20. uristream.PartialError = PartialError;
  21. function inheritErrors(stream) {
  22. stream.on('pipe', function(source) {
  23. source.on('error', stream.emit.bind(stream, 'error'));
  24. });
  25. stream.on('unpipe', function(source) {
  26. source.removeListener('error', stream.emit.bind(stream, 'error'));
  27. });
  28. return stream;
  29. }
  30. function setupHttp(uri, options, dst) {
  31. var defaults = {
  32. 'user-agent': DEFAULT_AGENT,
  33. 'accept-encoding': ['gzip','deflate']
  34. };
  35. // TODO: handle case in header names
  36. var headers = extend(defaults, options.headers);
  37. var timeout = options.timeout || 60*1000;
  38. var probe = !!options.probe;
  39. var offset = ~~options.start;
  40. var tries = 10;
  41. var fetch = probe ? request.head : request.get;
  42. function fetchHttp(start) {
  43. if (start > 0)
  44. headers['range'] = 'bytes=' + start + '-';
  45. else
  46. delete headers['range'];
  47. var accum = 0, size = -1;
  48. var req = fetch({uri:uri, pool:false, headers:headers, timeout:timeout});
  49. req.on('error', onreqerror);
  50. req.on('error', noop);
  51. req.on('response', onresponse);
  52. function failOrRetry(err, temporary) {
  53. req.abort();
  54. // remap error to partial error if we have received any data
  55. if (start + accum !== 0)
  56. err = new PartialError(err, start - offset + accum, (size !== -1) ? start - offset + size : size);
  57. return dst.emit('error', err);
  58. }
  59. function reqcleanup() {
  60. req.removeListener('error', onreqerror);
  61. req.removeListener('response', onresponse);
  62. }
  63. function onreqerror(err) {
  64. reqcleanup();
  65. failOrRetry(err);
  66. }
  67. function onresponse(res) {
  68. reqcleanup();
  69. if (res.statusCode !== 200 && res.statusCode !== 206)
  70. return failOrRetry(new Error('Bad server response code: '+res.statusCode), res.statusCode >= 500 && res.statusCode !== 501);
  71. if (res.headers['content-length']) size = parseInt(res.headers['content-length'], 10);
  72. var filesize = (size >= 0) ? start + size - offset : -1;
  73. // transparently handle gzip responses
  74. var stream = res;
  75. if (res.headers['content-encoding'] === 'gzip' || res.headers['content-encoding'] === 'deflate') {
  76. unzip = zlib.createUnzip();
  77. stream = stream.pipe(inheritErrors(unzip));
  78. filesize = -1;
  79. }
  80. // pipe it to self
  81. stream.on('data', function(chunk) {
  82. if (!dst.push(chunk))
  83. stream.pause();
  84. });
  85. oncemore(stream).once('end', 'error', function(err) {
  86. dst._read = noop;
  87. if (err) return failOrRetry(err);
  88. dst.push(null);
  89. });
  90. dst._read = function(n) {
  91. stream.resume();
  92. };
  93. // allow aborting the request
  94. dst.abort = req.abort.bind(req);
  95. // forward all future errors to response stream
  96. req.on('error', function(err) {
  97. if (dst.listeners('error').length !== 0)
  98. dst.emit('error', err);
  99. });
  100. // turn bad content-length into actual errors
  101. if (size >= 0 && !probe) {
  102. res.on('data', function(chunk) {
  103. accum += chunk.length;
  104. if (accum > size)
  105. req.abort();
  106. });
  107. oncemore(res).once('end', 'error', function(err) {
  108. if (!err && accum !== size)
  109. failOrRetry(new Error('Stream length did not match header'), accum && accum < size);
  110. });
  111. }
  112. // attach empty 'error' listener to keep it from ever throwing
  113. dst.on('error', noop);
  114. if (!dst.meta) {
  115. // extract meta information from header
  116. var typeparts = /^(.+?\/.+?)(?:;\w*.*)?$/.exec(res.headers['content-type']) || [null, 'application/octet-stream'],
  117. mimetype = typeparts[1].toLowerCase(),
  118. modified = res.headers['last-modified'] ? new Date(res.headers['last-modified']) : null;
  119. dst.meta = {url:url.format(req.uri), mime:mimetype, size:filesize, modified:modified};
  120. dst.emit('meta', dst.meta);
  121. }
  122. }
  123. }
  124. fetchHttp(offset);
  125. }
  126. function UriFetchStream(uri, options) {
  127. var self = this;
  128. Readable.call(this, options);
  129. options = options || {};
  130. this.url = url.parse(uri);
  131. this.meta = null;
  132. if (this.url.protocol === 'http:' || this.url.protocol === 'https:') {
  133. setupHttp(uri, options, this);
  134. } else {
  135. throw new Error('Unsupported protocol: '+this.url.protocol);
  136. }
  137. }
  138. util.inherits(UriFetchStream, Readable);
  139. UriFetchStream.prototype._read = noop;
  140. function uristream(uri, options) {
  141. return new UriFetchStream(uri, options);
  142. }
  143. function PartialError(err, processed, expected) {
  144. Error.call(this);
  145. if (err.stack) {
  146. Object.defineProperty(this, 'stack', {
  147. enumerable: false,
  148. configurable: false,
  149. get: function() { return err.stack; }
  150. });
  151. }
  152. else Error.captureStackTrace(this, arguments.callee);
  153. this.message = err.message || err.toString();
  154. this.processed = processed || -1;
  155. this.expected = expected;
  156. }
  157. util.inherits(PartialError, Error);
  158. PartialError.prototype.name = 'Partial Error';