audiobookshelf/server/routers/HlsRouter.js

66 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-08-18 00:01:11 +02:00
const express = require('express')
const Path = require('path')
2022-07-06 02:53:01 +02:00
const fs = require('../libs/fsExtra')
const Logger = require('../Logger')
2021-08-18 00:01:11 +02:00
class HlsRouter {
constructor(db, auth, playbackSessionManager, emitter) {
2021-08-18 00:01:11 +02:00
this.db = db
this.auth = auth
this.playbackSessionManager = playbackSessionManager
2021-08-18 00:01:11 +02:00
this.emitter = emitter
this.router = express()
this.init()
}
init() {
this.router.get('/:stream/:file', this.streamFileRequest.bind(this))
}
parseSegmentFilename(filename) {
var basename = Path.basename(filename, Path.extname(filename))
2021-08-18 00:01:11 +02:00
var num_part = basename.split('-')[1]
return Number(num_part)
}
async streamFileRequest(req, res) {
var streamId = req.params.stream
var fullFilePath = Path.join(this.playbackSessionManager.StreamsPath, streamId, req.params.file)
2021-09-01 20:47:18 +02:00
2021-08-18 00:01:11 +02:00
var exists = await fs.pathExists(fullFilePath)
if (!exists) {
Logger.warn('File path does not exist', fullFilePath)
2021-08-18 00:01:11 +02:00
var fileExt = Path.extname(req.params.file)
if (fileExt === '.ts' || fileExt === '.m4s') {
2021-08-18 00:01:11 +02:00
var segNum = this.parseSegmentFilename(req.params.file)
var stream = this.playbackSessionManager.getStream(streamId)
2021-08-18 00:01:11 +02:00
if (!stream) {
Logger.error(`[HlsRouter] Stream ${streamId} does not exist`)
2021-08-18 00:01:11 +02:00
return res.sendStatus(500)
}
if (stream.isResetting) {
Logger.info(`[HlsRouter] Stream ${streamId} is currently resetting`)
2021-08-18 00:01:11 +02:00
return res.sendStatus(404)
} else {
var startTimeForReset = await stream.checkSegmentNumberRequest(segNum)
if (startTimeForReset) {
// HLS.js will restart the stream at the new time
Logger.info(`[HlsRouter] Resetting Stream - notify client @${startTimeForReset}s`)
2021-08-18 00:01:11 +02:00
this.emitter('stream_reset', {
startTime: startTimeForReset,
streamId: stream.id
})
return res.sendStatus(500)
}
}
}
}
2021-08-18 00:01:11 +02:00
// Logger.info('Sending file', fullFilePath)
res.sendFile(fullFilePath)
}
}
module.exports = HlsRouter