123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492 |
- 'use strict';
- const uuid = require('uuid');
- const stream_buf = require('stream-buffers');
- const debug = require('debug')('joystream:util:ranges');
- function _parse_range(range)
- {
- var matches = range.match(/^(\d+-\d+|\d+-|-\d+|\*)$/u);
- if (!matches) {
- throw new Error(`Not a valid range: ${range}`);
- }
- var vals = matches[1].split('-').map((v) => {
- return v === '*' || v === '' ? undefined : parseInt(v, 10);
- });
- if (vals[1] <= vals[0]) {
- throw new Error(`Invalid range: start "${vals[0]}" must be before end "${vals[1]}".`);
- }
- return [vals[0], vals[1]];
- }
- function parse(range_str)
- {
- var res = {};
- debug('Parse range header value:', range_str);
- var matches = range_str.match(/^(([^\s]+)=)?((?:(?:\d+-\d+|-\d+|\d+-),?)+)$/u)
- if (!matches) {
- throw new Error(`Not a valid range header: ${range_str}`);
- }
- res.unit = matches[2] || 'bytes';
- res.range_str = matches[3];
- res.ranges = [];
-
- var ranges = []
- res.range_str.split(',').forEach((range) => {
- ranges.push(_parse_range(range));
- });
-
- ranges.forEach((new_range) => {
- debug('Found range:', new_range);
- var is_merged = false;
- for (var i in res.ranges) {
- var old_range = res.ranges[i];
-
- if (old_range[1] + 1 < new_range[0] || new_range[1] + 1 < old_range[0]) {
- debug('Range does not overlap with', old_range);
- continue;
- }
-
-
-
- var merged = [
- Math.min(old_range[0], new_range[0]),
- Math.max(old_range[1], new_range[1])
- ];
- res.ranges[i] = merged;
- is_merged = true;
- debug('Merged', new_range, 'into', old_range, 'as', merged);
- }
- if (!is_merged) {
- debug('Non-overlapping range!');
- res.ranges.push(new_range);
- }
- });
-
- res.ranges.sort((first, second) => {
- if (first[0] === second[0]) {
-
- return 0;
- }
- return (first[0] < second[0]) ? -1 : 1;
- });
- debug('Result of parse is', res);
- return res;
- }
- function parseAsync(range_str, cb)
- {
- try {
- return cb(parse(range_str));
- } catch (err) {
- return cb(null, err);
- }
- }
- class RangeSender
- {
- constructor(response, stream, opts, end_callback)
- {
-
- this.name = opts.name || 'content.bin';
- this.type = opts.type || 'application/octet-stream';
- this.size = opts.size;
- this.ranges = opts.ranges;
- this.download = opts.download || false;
-
- this.read_offset = 0;
- this.range_index = -1;
- this.range_boundary = undefined;
-
- this.handlers = {};
- this.opened = false;
- debug('RangeSender:', this);
- if (opts.ranges) {
- debug('Parsed ranges:', opts.ranges.ranges);
- }
-
- this.response = response;
- this.stream = stream;
- this.opts = opts;
- this.end_callback = end_callback;
- }
- on_error(err)
- {
-
- debug('Error:', err);
- if (!this.response.headersSent) {
- this.response.status(err.code || 404).send({
- message: err.message || `File not found: ${this.name}`
- });
- }
- if (this.end_callback) {
- this.end_callback(err);
- }
- }
- on_end()
- {
- debug('End of stream.');
- this.response.end();
- if (this.end_callback) {
- this.end_callback();
- }
- }
-
- on_open_no_range()
- {
-
- debug('Open succeeded:', this.name, this.type);
- this.opened = true;
- this.response.status(200);
- this.response.contentType(this.type);
- this.response.header('Accept-Ranges', 'bytes');
- this.response.header('Content-Transfer-Encoding', 'binary');
- if (this.download) {
- this.response.header('Content-Disposition', `attachment; filename="${this.name}"`);
- }
- else {
- this.response.header('Content-Disposition', 'inline');
- }
- if (this.size) {
- this.response.header('Content-Length', this.size);
- }
- }
- on_data_no_range(chunk)
- {
- if (!this.opened) {
- this.handlers['open']();
- }
-
- this.response.write(Buffer.from(chunk, 'binary'));
- }
-
- next_range_headers()
- {
-
- this.range_index += 1;
- if (this.range_index >= this.ranges.ranges.length) {
- debug('Cannot advance range index; we are done.');
- return undefined;
- }
-
- var range = this.ranges.ranges[this.range_index];
- var total_size;
- if (this.size) {
- total_size = this.size;
- }
- if (typeof range[0] === 'undefined') {
- range[0] = 0;
- }
- if (typeof range[1] === 'undefined') {
- if (this.size) {
- range[1] = total_size - 1;
- }
- }
- var send_size;
- if (typeof range[0] !== 'undefined' && typeof range[1] !== 'undefined') {
- send_size = range[1] - range[0] + 1;
- }
-
-
- var start = (typeof range[0] === 'undefined') ? '' : `${range[0]}`;
- var end = (typeof range[1] === 'undefined') ? '' : `${range[1]}`;
- var size_str;
- if (total_size) {
- size_str = `${total_size}`;
- }
- else {
- size_str = '*';
- }
- var ret = {
- 'Content-Range': `bytes ${start}-${end}/${size_str}`,
- 'Content-Type': `${this.type}`,
- };
- if (send_size) {
- ret['Content-Length'] = `${send_size}`;
- }
- return ret;
- }
- next_range()
- {
- if (this.ranges.ranges.length == 1) {
- debug('Cannot start new range; only one requested.');
- this.stream.off('data', this.handlers['data']);
- return false;
- }
- var headers = this.next_range_headers();
- if (headers) {
- var header_buf = new stream_buf.WritableStreamBuffer();
-
- header_buf.write(`\r\n--${this.range_boundary}\r\n`);
-
- for (var header in headers) {
- header_buf.write(`${header}: ${headers[header]}\r\n`);
- }
- header_buf.write('\r\n');
- this.response.write(header_buf.getContents());
- debug('New range started.');
- return true;
- }
-
- this.response.write(`\r\n--${this.range_boundary}--\r\n`);
- debug('End of ranges sent.');
- this.stream.off('data', this.handlers['data']);
- return false;
- }
- on_open_ranges()
- {
-
- debug('Open succeeded:', this.name, this.type);
- this.opened = true;
- this.response.header('Accept-Ranges', 'bytes');
- this.response.header('Content-Transfer-Encoding', 'binary');
- this.response.header('Content-Disposition', 'inline');
-
-
-
-
-
-
- if (this.ranges.ranges.length == 1) {
- this.response.writeHead(206, 'Partial Content', this.next_range_headers());
- }
- else {
- this.range_boundary = uuid.v4();
- var headers = {
- 'Content-Type': `multipart/byteranges; boundary=${this.range_boundary}`,
- };
- this.response.writeHead(206, 'Partial Content', headers);
- this.next_range();
- }
- }
- on_data_ranges(chunk)
- {
- if (!this.opened) {
- this.handlers['open']();
- }
-
-
-
-
-
-
-
-
-
-
- var chunk_range = [this.read_offset, this.read_offset + chunk.length - 1];
- debug('= Got chunk with byte range', chunk_range);
- while (true) {
- var req_range = this.ranges.ranges[this.range_index];
- if (!req_range) {
- break;
- }
- debug('Current requested range is', req_range);
- if (!req_range[1]) {
- req_range = [req_range[0], Number.MAX_SAFE_INTEGER];
- debug('Treating as', req_range);
- }
-
- if (chunk_range[1] < req_range[0] || chunk_range[0] > req_range[1]) {
- debug('Ignoring chunk; it is out of range.');
- break;
- }
-
-
- var segment = [
- Math.max(chunk_range[0], req_range[0]),
- Math.min(chunk_range[1], req_range[1]),
- ];
- debug('Segment to send within chunk is', segment);
-
- var start = segment[0] - this.read_offset;
- var end = segment[1] - this.read_offset;
- var len = end - start + 1;
- debug('Offsets into buffer are', [start, end], 'with length', len);
-
-
-
-
- var buf = Buffer.from(chunk, 'binary');
- this.response.write(Buffer.from(buf.buffer, buf.byteOffset + start, len));
-
- if (req_range[1] > chunk_range[1]) {
- debug('Chunk is finished, but the requested range is missing bytes.');
- break;
- }
- if (req_range[1] <= chunk_range[1]) {
- debug('Range is finished.');
- if (!this.next_range(segment)) {
- break;
- }
- }
- }
-
- this.read_offset += chunk.length;
- }
- start()
- {
-
-
-
- var nuke = false;
- if (this.ranges) {
- for (var i in this.ranges.ranges) {
- if (typeof this.ranges.ranges[i][0] === 'undefined') {
- nuke = true;
- break;
- }
- }
- }
- if (nuke) {
- this.ranges = undefined;
- }
-
-
- this.handlers['error'] = this.on_error.bind(this);
- this.handlers['end'] = this.on_end.bind(this);
- if (this.ranges) {
- debug('Preparing to handle ranges.');
- this.handlers['open'] = this.on_open_ranges.bind(this);
- this.handlers['data'] = this.on_data_ranges.bind(this);
- }
- else {
- debug('No ranges, just send the whole file.');
- this.handlers['open'] = this.on_open_no_range.bind(this);
- this.handlers['data'] = this.on_data_no_range.bind(this);
- }
- for (var handler in this.handlers) {
- this.stream.on(handler, this.handlers[handler]);
- }
- }
- }
- function send(response, stream, opts, end_callback)
- {
- var sender = new RangeSender(response, stream, opts, end_callback);
- sender.start();
- }
- module.exports =
- {
- parse: parse,
- parseAsync: parseAsync,
- RangeSender: RangeSender,
- send: send,
- };
|