123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429 |
- 'use strict'
- const uuid = require('uuid')
- const streamBuf = require('stream-buffers')
- const PARSE_RANGE_REGEX = /^(\d+-\d+|\d+-|-\d+|\*)$/u
- const PARSE_RANGE_HEADERS_REGEX = /^(([^\s]+)=)?((?:(?:\d+-\d+|-\d+|\d+-),?)+)$/u
- function parseRange(range) {
- const matches = range.match(PARSE_RANGE_REGEX)
- if (!matches) {
- throw new Error(`Not a valid range: ${range}`)
- }
- const 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(rangeStr) {
- const res = {}
- const matches = rangeStr.match(PARSE_RANGE_HEADERS_REGEX)
- if (!matches) {
- throw new Error(`Not a valid range header: ${rangeStr}`)
- }
- res.unit = matches[2] || 'bytes'
- res.rangeStr = matches[3]
- res.ranges = []
-
- const ranges = []
- res.rangeStr.split(',').forEach((range) => {
- ranges.push(parseRange(range))
- })
-
- ranges.forEach((newRange) => {
- let isMerged = false
- for (const i in res.ranges) {
- const oldRange = res.ranges[i]
-
- if (oldRange[1] + 1 < newRange[0] || newRange[1] + 1 < oldRange[0]) {
- continue
- }
-
-
-
- const merged = [Math.min(oldRange[0], newRange[0]), Math.max(oldRange[1], newRange[1])]
- res.ranges[i] = merged
- isMerged = true
- }
- if (!isMerged) {
- res.ranges.push(newRange)
- }
- })
-
- res.ranges.sort((first, second) => {
- if (first[0] === second[0]) {
-
- return 0
- }
- return first[0] < second[0] ? -1 : 1
- })
- return res
- }
- function parseAsync(rangeStr, cb) {
- try {
- return cb(parse(rangeStr))
- } catch (err) {
- return cb(null, err)
- }
- }
- class RangeSender {
- constructor(response, stream, opts, endCallback) {
-
- 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.readOffset = 0
- this.rangeIndex = -1
- this.rangeBoundary = undefined
-
- this.handlers = {}
- this.opened = false
-
- this.response = response
- this.stream = stream
- this.opts = opts
- this.endCallback = endCallback
- }
- onError(err) {
-
- if (!this.response.headersSent) {
- this.response.status(err.code || 404).send({
- message: err.message || `File not found: ${this.name}`,
- })
- }
- if (this.endCallback) {
- this.endCallback(err)
- }
- }
- onEnd() {
- this.response.end()
- if (this.endCallback) {
- this.endCallback()
- }
- }
-
- onOpenNoRange() {
-
- 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)
- }
- }
- onDataNoRange(chunk) {
- if (!this.opened) {
- this.handlers.open()
- }
-
- this.response.write(Buffer.from(chunk, 'binary'))
- }
-
- nextRangeHeaders() {
-
- this.rangeIndex += 1
- if (this.rangeIndex >= this.ranges.ranges.length) {
- return undefined
- }
-
- const range = this.ranges.ranges[this.rangeIndex]
- let totalSize
- if (this.size) {
- totalSize = this.size
- }
- if (typeof range[0] === 'undefined') {
- range[0] = 0
- }
- if (typeof range[1] === 'undefined') {
- if (this.size) {
- range[1] = totalSize - 1
- }
- }
- let sendSize
- if (typeof range[0] !== 'undefined' && typeof range[1] !== 'undefined') {
- sendSize = range[1] - range[0] + 1
- }
-
-
- const start = typeof range[0] === 'undefined' ? '' : `${range[0]}`
- const end = typeof range[1] === 'undefined' ? '' : `${range[1]}`
- let sizeStr
- if (totalSize) {
- sizeStr = `${totalSize}`
- } else {
- sizeStr = '*'
- }
- const ret = {
- 'Content-Range': `bytes ${start}-${end}/${sizeStr}`,
- 'Content-Type': `${this.type}`,
- }
- if (sendSize) {
- ret['Content-Length'] = `${sendSize}`
- }
- return ret
- }
- nextRange() {
- if (this.ranges.ranges.length === 1) {
- this.stream.off('data', this.handlers.data)
- return false
- }
- const headers = this.nextRangeHeaders()
- if (headers) {
- const onDataRanges = new streamBuf.WritableStreamBuffer()
-
- onDataRanges.write(`\r\n--${this.rangeBoundary}\r\n`)
-
- for (const header in headers) {
- onDataRanges.write(`${header}: ${headers[header]}\r\n`)
- }
- onDataRanges.write('\r\n')
- this.response.write(onDataRanges.getContents())
- return true
- }
-
- this.response.write(`\r\n--${this.rangeBoundary}--\r\n`)
- this.stream.off('data', this.handlers.data)
- return false
- }
- onOpenRanges() {
-
- 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.nextRangeHeaders())
- } else {
- this.rangeBoundary = uuid.v4()
- const headers = {
- 'Content-Type': `multipart/byteranges; boundary=${this.rangeBoundary}`,
- }
- this.response.writeHead(206, 'Partial Content', headers)
- this.nextRange()
- }
- }
- onDataRanges(chunk) {
- if (!this.opened) {
- this.handlers.open()
- }
-
-
-
-
-
-
-
-
-
-
- const chunkRange = [this.readOffset, this.readOffset + chunk.length - 1]
- while (true) {
- let reqRange = this.ranges.ranges[this.rangeIndex]
- if (!reqRange) {
- break
- }
- if (!reqRange[1]) {
- reqRange = [reqRange[0], Number.MAX_SAFE_INTEGER]
- }
-
- if (chunkRange[1] < reqRange[0] || chunkRange[0] > reqRange[1]) {
- break
- }
-
-
- const segment = [Math.max(chunkRange[0], reqRange[0]), Math.min(chunkRange[1], reqRange[1])]
-
- const start = segment[0] - this.readOffset
- const end = segment[1] - this.readOffset
- const len = end - start + 1
-
-
-
-
- const buf = Buffer.from(chunk, 'binary')
- this.response.write(Buffer.from(buf.buffer, buf.byteOffset + start, len))
-
- if (reqRange[1] > chunkRange[1]) {
- break
- }
- if (reqRange[1] <= chunkRange[1]) {
- if (!this.nextRange(segment)) {
- break
- }
- }
- }
-
- this.readOffset += chunk.length
- }
- start() {
-
-
-
- let nuke = false
- if (this.ranges) {
- for (const 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.onError.bind(this)
- this.handlers.end = this.onEnd.bind(this)
- if (this.ranges) {
- this.handlers.open = this.onOpenRanges.bind(this)
- this.handlers.data = this.onDataRanges.bind(this)
- } else {
- this.handlers.open = this.onOpenNoRange.bind(this)
- this.handlers.data = this.onDataNoRange.bind(this)
- }
- for (const handler in this.handlers) {
- this.stream.on(handler, this.handlers[handler])
- }
- }
- }
- function send(response, stream, opts, endCallback) {
- const sender = new RangeSender(response, stream, opts, endCallback)
- sender.start()
- }
- module.exports = {
- parse,
- parseAsync,
- RangeSender,
- send,
- }
|