uristream.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. // attach empty 'error' listener to keep dst from ever throwing
  43. dst.on('error', noop);
  44. function fetchHttp(start) {
  45. if (start > 0)
  46. headers['range'] = 'bytes=' + start + '-';
  47. else
  48. delete headers['range'];
  49. var accum = 0, size = -1;
  50. var req = fetch({uri:uri, pool:false, headers:headers, timeout:timeout});
  51. req.on('error', onreqerror);
  52. req.on('error', noop);
  53. req.on('response', onresponse);
  54. var failed = false;
  55. function failOrRetry(err, temporary) {
  56. if (failed) return;
  57. failed = true;
  58. req.abort();
  59. if (--tries <= 0) {
  60. // remap error to partial error if we have received any data
  61. if (start + accum !== 0)
  62. err = new PartialError(err, start - offset + accum, (size !== -1) ? start - offset + size : size);
  63. return dst.emit('error', err);
  64. }
  65. debug('retrying at ' + (start + accum));
  66. // TODO: delay retry?
  67. fetchHttp(start + accum);
  68. }
  69. function reqcleanup() {
  70. req.removeListener('error', onreqerror);
  71. req.removeListener('response', onresponse);
  72. }
  73. function onreqerror(err) {
  74. reqcleanup();
  75. failOrRetry(err);
  76. }
  77. function onresponse(res) {
  78. reqcleanup();
  79. if (res.statusCode !== 200 && res.statusCode !== 206)
  80. return failOrRetry(new Error('Bad server response code: '+res.statusCode), res.statusCode >= 500 && res.statusCode !== 501);
  81. if (res.headers['content-length']) size = parseInt(res.headers['content-length'], 10);
  82. var filesize = (size >= 0) ? start + size : -1;
  83. // transparently handle gzip responses
  84. var stream = res;
  85. if (res.headers['content-encoding'] === 'gzip' || res.headers['content-encoding'] === 'deflate') {
  86. unzip = zlib.createUnzip();
  87. stream = stream.pipe(inheritErrors(unzip));
  88. filesize = -1;
  89. }
  90. // pipe it to self
  91. stream.on('data', function(chunk) {
  92. if (!dst.push(chunk))
  93. stream.pause();
  94. });
  95. oncemore(stream).once('end', 'error', function(err) {
  96. dst._read = noop;
  97. if (err) return failOrRetry(err);
  98. if (!failed)
  99. dst.push(null);
  100. });
  101. dst._read = function(n) {
  102. stream.resume();
  103. };
  104. // allow aborting the request
  105. dst.abort = function() {
  106. tries = 0;
  107. req.abort();
  108. }
  109. // forward all future errors to response stream
  110. req.on('error', function(err) {
  111. if (dst.listeners('error').length !== 0)
  112. dst.emit('error', err);
  113. });
  114. // turn bad content-length into actual errors
  115. if (size >= 0 && !probe) {
  116. res.on('data', function(chunk) {
  117. accum += chunk.length;
  118. if (accum > size)
  119. req.abort();
  120. });
  121. oncemore(res).once('end', 'error', function(err) {
  122. if (!err && accum !== size)
  123. failOrRetry(new Error('Stream length did not match header'), accum && accum < size);
  124. });
  125. }
  126. if (!dst.meta) {
  127. // extract meta information from header
  128. var typeparts = /^(.+?\/.+?)(?:;\w*.*)?$/.exec(res.headers['content-type']) || [null, 'application/octet-stream'],
  129. mimetype = typeparts[1].toLowerCase(),
  130. modified = res.headers['last-modified'] ? new Date(res.headers['last-modified']) : null;
  131. dst.meta = {url:url.format(req.uri), mime:mimetype, size:filesize, modified:modified};
  132. dst.emit('meta', dst.meta);
  133. }
  134. }
  135. }
  136. fetchHttp(offset);
  137. }
  138. function UriFetchStream(uri, options) {
  139. var self = this;
  140. Readable.call(this, options);
  141. options = options || {};
  142. this.url = url.parse(uri);
  143. this.meta = null;
  144. if (this.url.protocol === 'http:' || this.url.protocol === 'https:') {
  145. setupHttp(uri, options, this);
  146. } else {
  147. throw new Error('Unsupported protocol: '+this.url.protocol);
  148. }
  149. }
  150. util.inherits(UriFetchStream, Readable);
  151. UriFetchStream.prototype._read = noop;
  152. function uristream(uri, options) {
  153. return new UriFetchStream(uri, options);
  154. }
  155. function PartialError(err, processed, expected) {
  156. Error.call(this);
  157. if (err.stack) {
  158. Object.defineProperty(this, 'stack', {
  159. enumerable: false,
  160. configurable: false,
  161. get: function() { return err.stack; }
  162. });
  163. }
  164. else Error.captureStackTrace(this, arguments.callee);
  165. this.message = err.message || err.toString();
  166. this.processed = processed || -1;
  167. this.expected = expected;
  168. }
  169. util.inherits(PartialError, Error);
  170. PartialError.prototype.name = 'Partial Error';