uristream.js 6.0 KB

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