index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. var util = require('util');
  2. var slice = require('stream-slice').slice;
  3. var Stream = require('stream');
  4. module.exports = async function (ctx, next) {
  5. var range = ctx.header.range;
  6. ctx.set('Accept-Ranges', 'bytes');
  7. if (!range) {
  8. return next();
  9. }
  10. var ranges = rangeParse(range);
  11. if (!ranges || ranges.length == 0) {
  12. ctx.status = 416;
  13. return;
  14. }
  15. if (ctx.method == 'PUT') {
  16. ctx.status = 400;
  17. return;
  18. }
  19. await next();
  20. if (ctx.method != 'GET' ||
  21. ctx.body == null) {
  22. return;
  23. }
  24. var first = ranges[0];
  25. var rawBody = ctx.body;
  26. var len = rawBody.length;
  27. // avoid multi ranges
  28. var firstRange = ranges[0];
  29. var start = firstRange[0];
  30. var end = firstRange[1];
  31. if (!Buffer.isBuffer(rawBody)) {
  32. if (rawBody instanceof Stream.Readable) {
  33. len = ctx.length || '*';
  34. rawBody = rawBody.pipe(slice(start, end + 1));
  35. } else if (typeof rawBody !== 'string') {
  36. rawBody = new Buffer(JSON.stringify(rawBody));
  37. len = rawBody.length;
  38. } else {
  39. rawBody = new Buffer(rawBody);
  40. len = rawBody.length;
  41. }
  42. }
  43. //Adjust infinite end
  44. if (end === Infinity) {
  45. if (Number.isInteger(len)) {
  46. end = len - 1;
  47. } else {
  48. // FIXME(Calle Svensson): If we don't know how much we can return, we do a normal HTTP 200 repsonse
  49. ctx.status = 200;
  50. return;
  51. }
  52. }
  53. var args = [start, end+1].filter(function(item) {
  54. return typeof item == 'number';
  55. });
  56. ctx.set('Content-Range', rangeContentGenerator(start, end, len));
  57. ctx.status = 206;
  58. if (rawBody instanceof Stream) {
  59. ctx.body = rawBody;
  60. } else {
  61. ctx.body = rawBody.slice.apply(rawBody, args);
  62. }
  63. if (len !== '*') {
  64. ctx.length = end - start + 1;
  65. }
  66. };
  67. function rangeParse(str) {
  68. var token = str.split('=');
  69. if (!token || token.length != 2 || token[0] != 'bytes') {
  70. return null;
  71. }
  72. return token[1].split(',')
  73. .map(function(range) {
  74. return range.split('-').map(function(value) {
  75. if (value === '') {
  76. return Infinity;
  77. }
  78. return Number(value);
  79. });
  80. })
  81. .filter(function(range) {
  82. return !isNaN(range[0]) && !isNaN(range[1]) && range[0] <= range[1];
  83. });
  84. }
  85. function rangeContentGenerator(start, end, length) {
  86. return util.format('bytes %d-%d/%s', start, end, length);
  87. }