uristream.js 6.1 KB

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