File streaming

This commit is contained in:
MrFry 2019-11-06 13:18:39 +01:00
parent 273b4c321b
commit b8316bb989
3 changed files with 50 additions and 43 deletions

View file

@ -49,50 +49,57 @@ app.use(bodyParser.json({
// --------------------------------------------------------------
app.get('/*.mp4', function (req, res) {
let p = req.url.replace(/%20/g, ' ')
let fp = p.split('?')
fp.pop()
const fpath = './public/files' + fp.join('/')
if (req.query.stream) {
const stat = fs.statSync(fpath)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, '').split('-')
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize - 1
const chunksize = (end - start) + 1
const file = fs.createReadStream(fpath, { start, end })
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4'
// app, '/*.mp4', 'video/mp4', 'stuff/video'
function appGetFileType (app, wildcard, contentType, pageToRender) {
app.get(wildcard, function (req, res) {
let p = req.url.replace(/%20/g, ' ')
let fp = p.split('?')
fp.pop()
const fpath = './public/files' + fp.join('/')
if (req.query.stream) {
const stat = fs.statSync(fpath)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, '').split('-')
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize - 1
const chunksize = (end - start) + 1
const file = fs.createReadStream(fpath, { start, end })
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': contentType
}
res.writeHead(200, head)
fs.createReadStream(fpath).pipe(res)
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4'
}
res.writeHead(200, head)
fs.createReadStream(fpath).pipe(res)
logger.LogReq(req)
let fname = p.split('/')
fname = fname.pop()
res.render(pageToRender, {
path: p,
fname,
url,
contentType
})
}
} else {
logger.LogReq(req)
let fname = p.split('/')
fname = fname.pop()
res.render('stuff/video', {
path: p,
fname,
url
})
}
})
})
}
appGetFileType(app, '/*.mp4', 'video/mp4', 'stuff/video')
appGetFileType(app, '/*.mp3', 'audio/mpeg', 'stuff/audio')
app.get('/*', function (req, res) {
let parsedUrl = req.url.replace(/%20/g, ' ')

@ -1 +1 @@
Subproject commit cbfaffa70ceb29b4beac4b13f6cbb4b85baac8a8
Subproject commit fe74436ab119a31fdb35f7a3bbae50a572b0fb21

View file

@ -21,7 +21,7 @@
<%= fname %>
</h2>
</center>
<video id="videoPlayer" controls muted="muted" autoplay>
<video id="videoPlayer" controls>
<source src="<%= url %><%= path %>?stream=true" type="video/mp4">
</video>
</body>