2021-08-18 00:01:11 +02:00
|
|
|
const Path = require('path')
|
|
|
|
const express = require('express')
|
|
|
|
const http = require('http')
|
|
|
|
const SocketIO = require('socket.io')
|
|
|
|
const fs = require('fs-extra')
|
2021-09-14 03:18:58 +02:00
|
|
|
const fileUpload = require('express-fileupload')
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
const Auth = require('./Auth')
|
|
|
|
const Watcher = require('./Watcher')
|
|
|
|
const Scanner = require('./Scanner')
|
|
|
|
const Db = require('./Db')
|
|
|
|
const ApiController = require('./ApiController')
|
|
|
|
const HlsController = require('./HlsController')
|
|
|
|
const StreamManager = require('./StreamManager')
|
2021-08-23 21:08:54 +02:00
|
|
|
const RssFeeds = require('./RssFeeds')
|
2021-09-04 21:17:26 +02:00
|
|
|
const DownloadManager = require('./DownloadManager')
|
2021-08-18 00:01:11 +02:00
|
|
|
const Logger = require('./Logger')
|
|
|
|
|
|
|
|
class Server {
|
|
|
|
constructor(PORT, CONFIG_PATH, METADATA_PATH, AUDIOBOOK_PATH) {
|
|
|
|
this.Port = PORT
|
|
|
|
this.Host = '0.0.0.0'
|
2021-08-26 00:36:54 +02:00
|
|
|
this.ConfigPath = Path.normalize(CONFIG_PATH)
|
|
|
|
this.AudiobookPath = Path.normalize(AUDIOBOOK_PATH)
|
|
|
|
this.MetadataPath = Path.normalize(METADATA_PATH)
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
fs.ensureDirSync(CONFIG_PATH)
|
|
|
|
fs.ensureDirSync(METADATA_PATH)
|
|
|
|
fs.ensureDirSync(AUDIOBOOK_PATH)
|
|
|
|
|
|
|
|
this.db = new Db(this.ConfigPath)
|
|
|
|
this.auth = new Auth(this.db)
|
|
|
|
this.watcher = new Watcher(this.AudiobookPath)
|
|
|
|
this.scanner = new Scanner(this.AudiobookPath, this.MetadataPath, this.db, this.emitter.bind(this))
|
|
|
|
this.streamManager = new StreamManager(this.db, this.MetadataPath)
|
2021-08-23 21:08:54 +02:00
|
|
|
this.rssFeeds = new RssFeeds(this.Port, this.db)
|
2021-09-15 03:45:00 +02:00
|
|
|
this.downloadManager = new DownloadManager(this.db, this.MetadataPath, this.AudiobookPath, this.emitter.bind(this))
|
2021-09-22 03:57:33 +02:00
|
|
|
this.apiController = new ApiController(this.MetadataPath, this.db, this.scanner, this.auth, this.streamManager, this.rssFeeds, this.downloadManager, this.emitter.bind(this), this.clientEmitter.bind(this))
|
|
|
|
this.hlsController = new HlsController(this.db, this.scanner, this.auth, this.streamManager, this.emitter.bind(this), this.streamManager.StreamsPath)
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
this.server = null
|
|
|
|
this.io = null
|
|
|
|
|
|
|
|
this.clients = {}
|
|
|
|
|
|
|
|
this.isScanning = false
|
2021-08-25 03:24:40 +02:00
|
|
|
this.isScanningCovers = false
|
2021-08-18 00:01:11 +02:00
|
|
|
this.isInitialized = false
|
|
|
|
}
|
|
|
|
|
|
|
|
get audiobooks() {
|
|
|
|
return this.db.audiobooks
|
|
|
|
}
|
2021-09-05 02:58:39 +02:00
|
|
|
get serverSettings() {
|
|
|
|
return this.db.serverSettings
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
|
|
|
|
2021-09-06 01:20:29 +02:00
|
|
|
getClientsForUser(userId) {
|
|
|
|
return Object.values(this.clients).filter(c => c.user && c.user.id === userId)
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
emitter(ev, data) {
|
2021-08-24 14:15:56 +02:00
|
|
|
// Logger.debug('EMITTER', ev)
|
2021-08-18 00:01:11 +02:00
|
|
|
this.io.emit(ev, data)
|
|
|
|
}
|
|
|
|
|
2021-09-06 01:20:29 +02:00
|
|
|
clientEmitter(userId, ev, data) {
|
|
|
|
var clients = this.getClientsForUser(userId)
|
|
|
|
if (!clients.length) {
|
|
|
|
return Logger.error(`[Server] clientEmitter - no clients found for user ${userId}`)
|
|
|
|
}
|
|
|
|
clients.forEach((client) => {
|
|
|
|
if (client.socket) {
|
|
|
|
client.socket.emit(ev, data)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-09-11 02:55:02 +02:00
|
|
|
async filesChanged(files) {
|
|
|
|
Logger.info('[Server]', files.length, 'Files Changed')
|
|
|
|
var result = await this.scanner.filesChanged(files)
|
|
|
|
Logger.info('[Server] Files changed result', result)
|
2021-09-07 03:14:04 +02:00
|
|
|
}
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
async scan() {
|
2021-08-24 14:15:56 +02:00
|
|
|
Logger.info('[Server] Starting Scan')
|
2021-08-18 00:01:11 +02:00
|
|
|
this.isScanning = true
|
|
|
|
this.isInitialized = true
|
2021-08-25 03:24:40 +02:00
|
|
|
this.emitter('scan_start', 'files')
|
2021-08-24 14:15:56 +02:00
|
|
|
var results = await this.scanner.scan()
|
2021-08-18 00:01:11 +02:00
|
|
|
this.isScanning = false
|
2021-08-25 03:24:40 +02:00
|
|
|
this.emitter('scan_complete', { scanType: 'files', results })
|
2021-08-24 14:15:56 +02:00
|
|
|
Logger.info('[Server] Scan complete')
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
|
|
|
|
2021-08-25 03:24:40 +02:00
|
|
|
async scanCovers() {
|
|
|
|
Logger.info('[Server] Start cover scan')
|
|
|
|
this.isScanningCovers = true
|
|
|
|
this.emitter('scan_start', 'covers')
|
|
|
|
var results = await this.scanner.scanCovers()
|
|
|
|
this.isScanningCovers = false
|
|
|
|
this.emitter('scan_complete', { scanType: 'covers', results })
|
|
|
|
Logger.info('[Server] Cover scan complete')
|
|
|
|
}
|
|
|
|
|
|
|
|
cancelScan() {
|
|
|
|
if (!this.isScanningCovers && !this.isScanning) return
|
|
|
|
this.scanner.cancelScan = true
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
async init() {
|
2021-08-24 14:15:56 +02:00
|
|
|
Logger.info('[Server] Init')
|
2021-09-22 03:57:33 +02:00
|
|
|
await this.streamManager.ensureStreamsDir()
|
2021-08-18 00:01:11 +02:00
|
|
|
await this.streamManager.removeOrphanStreams()
|
2021-09-04 21:17:26 +02:00
|
|
|
await this.downloadManager.removeOrphanDownloads()
|
2021-09-23 03:40:35 +02:00
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
await this.db.init()
|
|
|
|
this.auth.init()
|
|
|
|
|
|
|
|
this.watcher.initWatcher()
|
2021-09-11 02:55:02 +02:00
|
|
|
this.watcher.on('files', this.filesChanged.bind(this))
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
authMiddleware(req, res, next) {
|
|
|
|
this.auth.authMiddleware(req, res, next)
|
|
|
|
}
|
|
|
|
|
2021-09-18 19:45:34 +02:00
|
|
|
async handleUpload(req, res) {
|
|
|
|
if (!req.user.canUpload) {
|
|
|
|
Logger.warn('User attempted to upload without permission', req.user)
|
|
|
|
return res.sendStatus(403)
|
|
|
|
}
|
|
|
|
var files = Object.values(req.files)
|
|
|
|
var title = req.body.title
|
|
|
|
var author = req.body.author
|
|
|
|
var series = req.body.series
|
|
|
|
|
|
|
|
if (!files.length || !title || !author) {
|
|
|
|
return res.json({
|
|
|
|
error: 'Invalid post data received'
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
var outputDirectory = ''
|
|
|
|
if (series && series.length && series !== 'null') {
|
|
|
|
outputDirectory = Path.join(this.AudiobookPath, author, series, title)
|
|
|
|
} else {
|
|
|
|
outputDirectory = Path.join(this.AudiobookPath, author, title)
|
|
|
|
}
|
|
|
|
|
|
|
|
var exists = await fs.pathExists(outputDirectory)
|
|
|
|
if (exists) {
|
|
|
|
Logger.error(`[Server] Upload directory "${outputDirectory}" already exists`)
|
|
|
|
return res.json({
|
|
|
|
error: `Directory "${outputDirectory}" already exists`
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
await fs.ensureDir(outputDirectory)
|
|
|
|
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
|
|
|
|
|
|
|
for (let i = 0; i < files.length; i++) {
|
|
|
|
var file = files[i]
|
|
|
|
|
|
|
|
var path = Path.join(outputDirectory, file.name)
|
|
|
|
await file.mv(path).catch((error) => {
|
|
|
|
Logger.error('Failed to move file', path, error)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
res.sendStatus(200)
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
async start() {
|
|
|
|
Logger.info('=== Starting Server ===')
|
|
|
|
await this.init()
|
|
|
|
|
|
|
|
const app = express()
|
|
|
|
|
|
|
|
this.server = http.createServer(app)
|
|
|
|
|
|
|
|
app.use(this.auth.cors)
|
2021-09-14 03:18:58 +02:00
|
|
|
app.use(fileUpload())
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
// Static path to generated nuxt
|
2021-08-24 02:37:40 +02:00
|
|
|
const distPath = Path.join(global.appRoot, '/client/dist')
|
2021-08-18 00:01:11 +02:00
|
|
|
if (process.env.NODE_ENV === 'production') {
|
|
|
|
app.use(express.static(distPath))
|
2021-08-21 23:23:35 +02:00
|
|
|
app.use('/local', express.static(this.AudiobookPath))
|
|
|
|
} else {
|
|
|
|
app.use(express.static(this.AudiobookPath))
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
2021-08-21 23:23:35 +02:00
|
|
|
|
2021-09-22 03:57:33 +02:00
|
|
|
app.use('/metadata', this.authMiddleware.bind(this), express.static(this.MetadataPath))
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
app.use(express.static(this.MetadataPath))
|
2021-08-23 21:08:54 +02:00
|
|
|
app.use(express.static(Path.join(global.appRoot, 'static')))
|
2021-08-18 00:01:11 +02:00
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
app.use(express.json())
|
|
|
|
|
2021-08-24 02:37:40 +02:00
|
|
|
// Dynamic routes are not generated on client
|
|
|
|
app.get('/audiobook/:id', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-09-24 14:32:38 +02:00
|
|
|
app.get('/library/:id', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
|
|
|
app.get('/library', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-08-24 02:37:40 +02:00
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
app.use('/api', this.authMiddleware.bind(this), this.apiController.router)
|
|
|
|
app.use('/hls', this.authMiddleware.bind(this), this.hlsController.router)
|
2021-09-01 20:47:18 +02:00
|
|
|
// app.use('/hls', this.hlsController.router)
|
2021-08-23 21:08:54 +02:00
|
|
|
app.use('/feeds', this.rssFeeds.router)
|
2021-08-18 00:01:11 +02:00
|
|
|
|
2021-09-18 19:45:34 +02:00
|
|
|
app.post('/upload', this.authMiddleware.bind(this), this.handleUpload.bind(this))
|
2021-09-14 03:18:58 +02:00
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
app.post('/login', (req, res) => this.auth.login(req, res))
|
|
|
|
app.post('/logout', this.logout.bind(this))
|
|
|
|
app.get('/ping', (req, res) => {
|
|
|
|
Logger.info('Recieved ping')
|
|
|
|
res.json({ success: true })
|
|
|
|
})
|
|
|
|
|
2021-09-01 20:47:18 +02:00
|
|
|
// Used in development to set-up streams without authentication
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
app.use('/test-hls', this.hlsController.router)
|
|
|
|
app.get('/test-stream/:id', async (req, res) => {
|
|
|
|
var uri = await this.streamManager.openTestStream(this.MetadataPath, req.params.id)
|
|
|
|
res.send(uri)
|
|
|
|
})
|
|
|
|
app.get('/catalog.json', (req, res) => {
|
|
|
|
Logger.error('Catalog request made', req.headers)
|
|
|
|
res.json()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
this.server.listen(this.Port, this.Host, () => {
|
|
|
|
Logger.info(`Running on http://${this.Host}:${this.Port}`)
|
|
|
|
})
|
|
|
|
|
|
|
|
this.io = new SocketIO.Server(this.server, {
|
|
|
|
cors: {
|
|
|
|
origin: '*',
|
|
|
|
methods: ["GET", "POST"]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
this.io.on('connection', (socket) => {
|
|
|
|
this.clients[socket.id] = {
|
|
|
|
id: socket.id,
|
|
|
|
socket,
|
|
|
|
connected_at: Date.now()
|
|
|
|
}
|
|
|
|
socket.sheepClient = this.clients[socket.id]
|
|
|
|
|
|
|
|
Logger.info('[SOCKET] Socket Connected', socket.id)
|
|
|
|
|
|
|
|
socket.on('auth', (token) => this.authenticateSocket(socket, token))
|
2021-09-12 23:10:12 +02:00
|
|
|
|
|
|
|
// Scanning
|
2021-08-18 00:01:11 +02:00
|
|
|
socket.on('scan', this.scan.bind(this))
|
2021-08-25 03:24:40 +02:00
|
|
|
socket.on('scan_covers', this.scanCovers.bind(this))
|
|
|
|
socket.on('cancel_scan', this.cancelScan.bind(this))
|
2021-09-12 23:10:12 +02:00
|
|
|
|
|
|
|
// Streaming
|
2021-08-18 00:01:11 +02:00
|
|
|
socket.on('open_stream', (audiobookId) => this.streamManager.openStreamSocketRequest(socket, audiobookId))
|
|
|
|
socket.on('close_stream', () => this.streamManager.closeStreamRequest(socket))
|
|
|
|
socket.on('stream_update', (payload) => this.streamManager.streamUpdate(socket, payload))
|
2021-09-12 23:10:12 +02:00
|
|
|
|
2021-09-12 02:59:48 +02:00
|
|
|
socket.on('progress_update', (payload) => this.audiobookProgressUpdate(socket.sheepClient, payload))
|
2021-09-12 23:10:12 +02:00
|
|
|
|
|
|
|
// Downloading
|
2021-09-04 21:17:26 +02:00
|
|
|
socket.on('download', (payload) => this.downloadManager.downloadSocketRequest(socket, payload))
|
2021-09-12 23:10:12 +02:00
|
|
|
socket.on('remove_download', (downloadId) => this.downloadManager.removeSocketRequest(socket, downloadId))
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
socket.on('test', () => {
|
|
|
|
socket.emit('test_received', socket.id)
|
|
|
|
})
|
|
|
|
|
|
|
|
socket.on('disconnect', () => {
|
|
|
|
var _client = this.clients[socket.id]
|
|
|
|
if (!_client) {
|
|
|
|
Logger.warn('[SOCKET] Socket disconnect, no client ' + socket.id)
|
|
|
|
} else if (!_client.user) {
|
|
|
|
Logger.info('[SOCKET] Unauth socket disconnected ' + socket.id)
|
|
|
|
delete this.clients[socket.id]
|
|
|
|
} else {
|
|
|
|
const disconnectTime = Date.now() - _client.connected_at
|
|
|
|
Logger.info(`[SOCKET] Socket ${socket.id} disconnected from client "${_client.user.username}" after ${disconnectTime}ms`)
|
|
|
|
delete this.clients[socket.id]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
logout(req, res) {
|
|
|
|
res.sendStatus(200)
|
|
|
|
}
|
|
|
|
|
2021-09-12 02:59:48 +02:00
|
|
|
audiobookProgressUpdate(client, progressPayload) {
|
|
|
|
if (!client || !client.user) {
|
|
|
|
Logger.error('[Server] audiobookProgressUpdate invalid socket client')
|
|
|
|
return
|
|
|
|
}
|
2021-09-13 01:22:52 +02:00
|
|
|
client.user.updateAudiobookProgress(progressPayload.audiobookId, progressPayload)
|
2021-09-12 02:59:48 +02:00
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
async authenticateSocket(socket, token) {
|
|
|
|
var user = await this.auth.verifyToken(token)
|
|
|
|
if (!user) {
|
|
|
|
Logger.error('Cannot validate socket - invalid token')
|
|
|
|
return socket.emit('invalid_token')
|
|
|
|
}
|
|
|
|
var client = this.clients[socket.id]
|
|
|
|
client.user = user
|
|
|
|
|
2021-08-18 00:43:29 +02:00
|
|
|
if (!client.user.toJSONForBrowser) {
|
|
|
|
Logger.error('Invalid user...', client.user)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
// Check if user has stream open
|
|
|
|
if (client.user.stream) {
|
|
|
|
Logger.info('User has stream open already', client.user.stream)
|
|
|
|
client.stream = this.streamManager.getStream(client.user.stream)
|
|
|
|
if (!client.stream) {
|
|
|
|
Logger.error('Invalid user stream id', client.user.stream)
|
|
|
|
this.streamManager.removeOrphanStreamFiles(client.user.stream)
|
|
|
|
await this.db.updateUserStream(client.user.id, null)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const initialPayload = {
|
2021-09-05 02:58:39 +02:00
|
|
|
serverSettings: this.serverSettings.toJSON(),
|
2021-08-18 00:01:11 +02:00
|
|
|
isScanning: this.isScanning,
|
|
|
|
isInitialized: this.isInitialized,
|
|
|
|
audiobookPath: this.AudiobookPath,
|
|
|
|
metadataPath: this.MetadataPath,
|
|
|
|
configPath: this.ConfigPath,
|
|
|
|
user: client.user.toJSONForBrowser(),
|
|
|
|
stream: client.stream || null
|
|
|
|
}
|
|
|
|
client.socket.emit('init', initialPayload)
|
|
|
|
}
|
|
|
|
|
|
|
|
async stop() {
|
|
|
|
await this.watcher.close()
|
|
|
|
Logger.info('Watcher Closed')
|
|
|
|
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
this.server.close((err) => {
|
|
|
|
if (err) {
|
|
|
|
Logger.error('Failed to close server', err)
|
|
|
|
} else {
|
|
|
|
Logger.info('Server successfully closed')
|
|
|
|
}
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = Server
|