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-09-29 17:16:38 +02:00
|
|
|
const rateLimit = require('express-rate-limit')
|
2021-08-18 00:01:11 +02:00
|
|
|
|
2021-10-05 05:11:42 +02:00
|
|
|
const { version } = require('../package.json')
|
|
|
|
|
|
|
|
// Utils
|
2022-03-10 02:23:17 +01:00
|
|
|
const dbMigration = require('./utils/dbMigration')
|
2021-10-05 05:11:42 +02:00
|
|
|
const Logger = require('./Logger')
|
2021-10-01 01:52:32 +02:00
|
|
|
|
2021-10-05 05:11:42 +02:00
|
|
|
// Classes
|
2021-08-18 00:01:11 +02:00
|
|
|
const Auth = require('./Auth')
|
|
|
|
const Watcher = require('./Watcher')
|
2021-12-25 01:06:17 +01:00
|
|
|
const Scanner = require('./scanner/Scanner')
|
2021-08-18 00:01:11 +02:00
|
|
|
const Db = require('./Db')
|
2022-03-20 22:41:06 +01:00
|
|
|
|
2022-03-18 01:10:47 +01:00
|
|
|
const ApiRouter = require('./routers/ApiRouter')
|
|
|
|
const HlsRouter = require('./routers/HlsRouter')
|
|
|
|
const StaticRouter = require('./routers/StaticRouter')
|
2022-03-20 22:41:06 +01:00
|
|
|
|
|
|
|
const CoverManager = require('./managers/CoverManager')
|
|
|
|
const DownloadManager = require('./managers/DownloadManager')
|
|
|
|
const CacheManager = require('./managers/CacheManager')
|
|
|
|
const LogManager = require('./managers/LogManager')
|
|
|
|
const BackupManager = require('./managers/BackupManager')
|
|
|
|
const PlaybackSessionManager = require('./managers/PlaybackSessionManager')
|
|
|
|
const PodcastManager = require('./managers/PodcastManager')
|
2021-10-05 05:11:42 +02:00
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
class Server {
|
2022-03-17 12:06:52 +01:00
|
|
|
constructor(PORT, HOST, UID, GID, CONFIG_PATH, METADATA_PATH, AUDIOBOOK_PATH) {
|
2021-08-18 00:01:11 +02:00
|
|
|
this.Port = PORT
|
2022-03-17 12:06:52 +01:00
|
|
|
this.Host = HOST
|
2022-03-13 00:45:32 +01:00
|
|
|
global.Uid = isNaN(UID) ? 0 : Number(UID)
|
|
|
|
global.Gid = isNaN(GID) ? 0 : Number(GID)
|
2022-02-27 20:47:52 +01:00
|
|
|
global.ConfigPath = Path.normalize(CONFIG_PATH)
|
|
|
|
global.AudiobookPath = Path.normalize(AUDIOBOOK_PATH)
|
|
|
|
global.MetadataPath = Path.normalize(METADATA_PATH)
|
|
|
|
// Fix backslash if not on Windows
|
|
|
|
if (process.platform !== 'win32') {
|
|
|
|
global.ConfigPath = global.ConfigPath.replace(/\\/g, '/')
|
|
|
|
global.AudiobookPath = global.AudiobookPath.replace(/\\/g, '/')
|
|
|
|
global.MetadataPath = global.MetadataPath.replace(/\\/g, '/')
|
|
|
|
}
|
2021-08-18 00:01:11 +02:00
|
|
|
|
2022-02-27 20:47:52 +01:00
|
|
|
fs.ensureDirSync(global.ConfigPath, 0o774)
|
|
|
|
fs.ensureDirSync(global.MetadataPath, 0o774)
|
|
|
|
fs.ensureDirSync(global.AudiobookPath, 0o774)
|
2021-08-18 00:01:11 +02:00
|
|
|
|
2022-02-27 20:47:52 +01:00
|
|
|
this.db = new Db()
|
2022-03-20 22:41:06 +01:00
|
|
|
this.watcher = new Watcher()
|
2021-08-18 00:01:11 +02:00
|
|
|
this.auth = new Auth(this.db)
|
2022-03-20 22:41:06 +01:00
|
|
|
|
|
|
|
// Managers
|
2022-03-18 19:44:29 +01:00
|
|
|
this.backupManager = new BackupManager(this.db, this.emitter.bind(this))
|
2022-02-27 20:47:52 +01:00
|
|
|
this.logManager = new LogManager(this.db)
|
|
|
|
this.cacheManager = new CacheManager()
|
2022-03-13 00:45:32 +01:00
|
|
|
this.downloadManager = new DownloadManager(this.db)
|
2022-03-20 22:41:06 +01:00
|
|
|
this.playbackSessionManager = new PlaybackSessionManager(this.db, this.emitter.bind(this), this.clientEmitter.bind(this))
|
|
|
|
this.coverManager = new CoverManager(this.db, this.cacheManager)
|
2022-03-22 01:24:38 +01:00
|
|
|
this.podcastManager = new PodcastManager(this.db, this.watcher, this.emitter.bind(this))
|
2022-03-20 22:41:06 +01:00
|
|
|
|
|
|
|
this.scanner = new Scanner(this.db, this.coverManager, this.emitter.bind(this))
|
2022-03-18 01:10:47 +01:00
|
|
|
|
|
|
|
// Routers
|
2022-03-20 22:41:06 +01:00
|
|
|
this.apiRouter = new ApiRouter(this.db, this.auth, this.scanner, this.playbackSessionManager, this.downloadManager, this.coverManager, this.backupManager, this.watcher, this.cacheManager, this.podcastManager, this.emitter.bind(this), this.clientEmitter.bind(this))
|
2022-03-18 01:10:47 +01:00
|
|
|
this.hlsRouter = new HlsRouter(this.db, this.auth, this.playbackSessionManager, this.emitter.bind(this))
|
|
|
|
this.staticRouter = new StaticRouter(this.db)
|
2021-10-02 01:42:48 +02:00
|
|
|
|
2021-10-31 23:55:28 +01:00
|
|
|
Logger.logManager = this.logManager
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
this.server = null
|
|
|
|
this.io = null
|
|
|
|
|
|
|
|
this.clients = {}
|
|
|
|
}
|
|
|
|
|
2021-10-23 03:08:02 +02:00
|
|
|
get usersOnline() {
|
2022-03-16 01:28:54 +01:00
|
|
|
// TODO: Map open user sessions
|
2021-10-23 03:08:02 +02:00
|
|
|
return Object.values(this.clients).filter(c => c.user).map(client => {
|
2022-03-18 01:10:47 +01:00
|
|
|
return client.user.toJSONForPublic(this.playbackSessionManager.sessions, this.db.libraryItems)
|
2021-10-23 03:08:02 +02:00
|
|
|
})
|
|
|
|
}
|
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) {
|
2022-02-26 23:35:40 +01:00
|
|
|
return Logger.debug(`[Server] clientEmitter - no clients found for user ${userId}`)
|
2021-09-06 01:20:29 +02:00
|
|
|
}
|
|
|
|
clients.forEach((client) => {
|
|
|
|
if (client.socket) {
|
|
|
|
client.socket.emit(ev, data)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-10-13 03:07:42 +02:00
|
|
|
authMiddleware(req, res, next) {
|
|
|
|
this.auth.authMiddleware(req, res, next)
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
async init() {
|
2021-10-05 05:11:42 +02:00
|
|
|
Logger.info('[Server] Init v' + version)
|
2022-03-16 01:28:54 +01:00
|
|
|
// TODO: Remove orphan streams from playback session manager
|
|
|
|
// await this.streamManager.ensureStreamsDir()
|
|
|
|
// await this.streamManager.removeOrphanStreams()
|
2021-09-04 21:17:26 +02:00
|
|
|
await this.downloadManager.removeOrphanDownloads()
|
2021-09-23 03:40:35 +02:00
|
|
|
|
2022-04-10 17:05:05 +02:00
|
|
|
if (version.localeCompare('2.0.0') < 0) { // Old version data model migration
|
2022-03-19 16:13:10 +01:00
|
|
|
await dbMigration.migrate(this.db)
|
2022-03-16 00:57:15 +01:00
|
|
|
} else {
|
|
|
|
await this.db.init()
|
2022-03-10 02:23:17 +01:00
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
this.auth.init()
|
|
|
|
|
2022-03-26 17:59:34 +01:00
|
|
|
await this.checkUserMediaProgress() // Remove invalid user item progress
|
2022-03-19 16:13:10 +01:00
|
|
|
await this.purgeMetadata() // Remove metadata folders without library item
|
2022-03-10 02:23:17 +01:00
|
|
|
|
2021-10-09 00:30:20 +02:00
|
|
|
await this.backupManager.init()
|
2021-10-31 23:55:28 +01:00
|
|
|
await this.logManager.init()
|
2022-03-27 01:58:59 +01:00
|
|
|
this.podcastManager.init()
|
2021-10-02 01:42:48 +02:00
|
|
|
|
2022-02-24 00:52:21 +01:00
|
|
|
if (this.db.serverSettings.scannerDisableWatcher) {
|
|
|
|
Logger.info(`[Server] Watcher is disabled`)
|
|
|
|
this.watcher.disabled = true
|
|
|
|
} else {
|
2022-03-10 02:23:17 +01:00
|
|
|
this.watcher.initWatcher(this.db.libraries)
|
2022-02-24 00:52:21 +01:00
|
|
|
this.watcher.on('files', this.filesChanged.bind(this))
|
|
|
|
}
|
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())
|
2022-04-09 10:25:24 +02:00
|
|
|
app.use(express.urlencoded({ extended: true, limit: "3mb" }));
|
|
|
|
app.use(express.json({ limit: "3mb" }))
|
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-10-05 05:11:42 +02:00
|
|
|
app.use(express.static(distPath))
|
|
|
|
|
2022-03-18 19:44:29 +01:00
|
|
|
|
2021-10-05 05:11:42 +02:00
|
|
|
// Metadata folder static path
|
2022-03-18 19:44:29 +01:00
|
|
|
app.use('/metadata', this.authMiddleware.bind(this), express.static(global.MetadataPath))
|
|
|
|
|
|
|
|
// TODO: Are these necessary?
|
2021-10-06 14:23:32 +02:00
|
|
|
// Downloads folder static path
|
2022-03-18 17:51:55 +01:00
|
|
|
// app.use('/downloads', this.authMiddleware.bind(this), express.static(this.downloadManager.downloadDirPath))
|
2021-10-05 05:11:42 +02:00
|
|
|
// Static folder
|
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
|
|
|
|
2022-03-18 01:10:47 +01:00
|
|
|
app.use('/api', this.authMiddleware.bind(this), this.apiRouter.router)
|
|
|
|
app.use('/hls', this.authMiddleware.bind(this), this.hlsRouter.router)
|
|
|
|
app.use('/s', this.authMiddleware.bind(this), this.staticRouter.router)
|
2022-03-11 01:45:02 +01:00
|
|
|
|
2021-10-09 00:30:20 +02:00
|
|
|
// EBook static file routes
|
|
|
|
app.get('/ebook/:library/:folder/*', (req, res) => {
|
2022-03-10 02:23:17 +01:00
|
|
|
var library = this.db.libraries.find(lib => lib.id === req.params.library)
|
2021-10-09 00:30:20 +02:00
|
|
|
if (!library) return res.sendStatus(404)
|
|
|
|
var folder = library.folders.find(fol => fol.id === req.params.folder)
|
|
|
|
if (!folder) return res.status(404).send('Folder not found')
|
|
|
|
|
|
|
|
var remainingPath = req.params['0']
|
|
|
|
var fullPath = Path.join(folder.fullPath, remainingPath)
|
|
|
|
res.sendFile(fullPath)
|
|
|
|
})
|
|
|
|
|
2021-11-13 02:43:16 +01:00
|
|
|
// Client dynamic routes
|
2022-03-11 01:45:02 +01:00
|
|
|
app.get('/item/:id', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2022-03-17 18:25:12 +01:00
|
|
|
app.get('/audiobook/:id/edit', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-10-05 05:11:42 +02:00
|
|
|
app.get('/library/:library', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-12-03 02:40:42 +01:00
|
|
|
app.get('/library/:library/search', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-10-05 05:11:42 +02:00
|
|
|
app.get('/library/:library/bookshelf/:id?', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-12-03 02:40:42 +01:00
|
|
|
app.get('/library/:library/authors', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
|
|
|
app.get('/library/:library/series/:id?', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-11-13 02:43:16 +01:00
|
|
|
app.get('/config/users/:id', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
|
|
|
app.get('/collection/:id', (req, res) => res.sendFile(Path.join(distPath, 'index.html')))
|
2021-08-24 02:37:40 +02:00
|
|
|
|
2022-03-11 01:45:02 +01:00
|
|
|
app.post('/login', this.getLoginRateLimiter(), (req, res) => this.auth.login(req, res))
|
2021-10-23 03:08:02 +02:00
|
|
|
app.post('/logout', this.authMiddleware.bind(this), this.logout.bind(this))
|
2021-08-18 00:01:11 +02:00
|
|
|
app.get('/ping', (req, res) => {
|
|
|
|
Logger.info('Recieved ping')
|
|
|
|
res.json({ success: true })
|
|
|
|
})
|
|
|
|
|
|
|
|
this.server.listen(this.Port, this.Host, () => {
|
2022-03-11 01:45:02 +01:00
|
|
|
Logger.info(`Listening on http://${this.Host}:${this.Port}`)
|
2021-08-18 00:01:11 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
2022-03-11 01:45:02 +01:00
|
|
|
Logger.info('[Server] Socket Connected', socket.id)
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
socket.on('auth', (token) => this.authenticateSocket(socket, token))
|
2021-09-12 23:10:12 +02:00
|
|
|
|
|
|
|
// Scanning
|
2021-08-25 03:24:40 +02:00
|
|
|
socket.on('cancel_scan', this.cancelScan.bind(this))
|
2022-03-13 00:45:32 +01:00
|
|
|
socket.on('save_metadata', (libraryItemId) => this.saveMetadata(socket, libraryItemId))
|
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-10-09 00:30:20 +02:00
|
|
|
// Logs
|
2021-10-01 01:52:32 +02:00
|
|
|
socket.on('set_log_listener', (level) => Logger.addSocketListener(socket, level))
|
2021-11-01 01:10:45 +01:00
|
|
|
socket.on('fetch_daily_logs', () => this.logManager.socketRequestDailyLogs(socket))
|
2021-10-01 01:52:32 +02:00
|
|
|
|
2022-04-12 02:42:09 +02:00
|
|
|
socket.on('ping', () => {
|
|
|
|
var client = this.clients[socket.id] || {}
|
|
|
|
var user = client.user || {}
|
|
|
|
Logger.debug(`[Server] Received ping from socket ${user.username || 'No User'}`)
|
|
|
|
socket.emit('pong')
|
|
|
|
})
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
socket.on('disconnect', () => {
|
2021-10-01 01:52:32 +02:00
|
|
|
Logger.removeSocketListener(socket.id)
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
var _client = this.clients[socket.id]
|
|
|
|
if (!_client) {
|
2021-10-23 03:08:02 +02:00
|
|
|
Logger.warn('[Server] Socket disconnect, no client ' + socket.id)
|
2021-08-18 00:01:11 +02:00
|
|
|
} else if (!_client.user) {
|
2021-10-23 03:08:02 +02:00
|
|
|
Logger.info('[Server] Unauth socket disconnected ' + socket.id)
|
2021-08-18 00:01:11 +02:00
|
|
|
delete this.clients[socket.id]
|
|
|
|
} else {
|
2021-10-23 03:08:02 +02:00
|
|
|
Logger.debug('[Server] User Offline ' + _client.user.username)
|
2022-03-18 01:10:47 +01:00
|
|
|
this.io.emit('user_offline', _client.user.toJSONForPublic(this.playbackSessionManager.sessions, this.db.libraryItems))
|
2021-10-13 03:07:42 +02:00
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
const disconnectTime = Date.now() - _client.connected_at
|
2021-10-23 03:08:02 +02:00
|
|
|
Logger.info(`[Server] Socket ${socket.id} disconnected from client "${_client.user.username}" after ${disconnectTime}ms`)
|
2021-08-18 00:01:11 +02:00
|
|
|
delete this.clients[socket.id]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-10-05 05:11:42 +02:00
|
|
|
async filesChanged(fileUpdates) {
|
|
|
|
Logger.info('[Server]', fileUpdates.length, 'Files Changed')
|
2021-12-25 01:06:17 +01:00
|
|
|
await this.scanner.scanFilesChanged(fileUpdates)
|
2021-10-05 05:11:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
cancelScan(id) {
|
2021-10-06 04:10:49 +02:00
|
|
|
Logger.debug('[Server] Cancel scan', id)
|
2021-12-25 01:06:17 +01:00
|
|
|
this.scanner.setCancelLibraryScan(id)
|
2021-10-05 05:11:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Generates an NFO metadata file, if no audiobookId is passed then all audiobooks are done
|
|
|
|
async saveMetadata(socket, audiobookId = null) {
|
|
|
|
Logger.info('[Server] Starting save metadata files')
|
|
|
|
var response = await this.scanner.saveMetadata(audiobookId)
|
|
|
|
Logger.info(`[Server] Finished saving metadata files Successful: ${response.success}, Failed: ${response.failed}`)
|
|
|
|
socket.emit('save_metadata_complete', response)
|
|
|
|
}
|
|
|
|
|
2022-03-19 16:13:10 +01:00
|
|
|
// Remove unused /metadata/items/{id} folders
|
2021-10-05 05:11:42 +02:00
|
|
|
async purgeMetadata() {
|
2022-03-19 16:13:10 +01:00
|
|
|
var itemsMetadata = Path.join(global.MetadataPath, 'items')
|
|
|
|
if (!(await fs.pathExists(itemsMetadata))) return
|
|
|
|
var foldersInItemsMetadata = await fs.readdir(itemsMetadata)
|
2021-10-05 05:11:42 +02:00
|
|
|
|
|
|
|
var purged = 0
|
2022-03-19 16:13:10 +01:00
|
|
|
await Promise.all(foldersInItemsMetadata.map(async foldername => {
|
|
|
|
var hasMatchingItem = this.db.libraryItems.find(ab => ab.id === foldername)
|
|
|
|
if (!hasMatchingItem) {
|
|
|
|
var folderPath = Path.join(itemsMetadata, foldername)
|
2021-10-05 05:11:42 +02:00
|
|
|
Logger.debug(`[Server] Purging unused metadata ${folderPath}`)
|
|
|
|
|
|
|
|
await fs.remove(folderPath).then(() => {
|
|
|
|
purged++
|
|
|
|
}).catch((err) => {
|
|
|
|
Logger.error(`[Server] Failed to delete folder path ${folderPath}`, err)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
if (purged > 0) {
|
2022-03-19 16:13:10 +01:00
|
|
|
Logger.info(`[Server] Purged ${purged} unused library item metadata`)
|
2021-10-05 05:11:42 +02:00
|
|
|
}
|
|
|
|
return purged
|
|
|
|
}
|
|
|
|
|
2022-03-26 17:59:34 +01:00
|
|
|
// Remove user media progress entries that dont have a library item
|
|
|
|
// TODO: Check podcast episode exists still
|
|
|
|
async checkUserMediaProgress() {
|
2021-11-04 13:59:28 +01:00
|
|
|
for (let i = 0; i < this.db.users.length; i++) {
|
|
|
|
var _user = this.db.users[i]
|
2022-03-26 17:59:34 +01:00
|
|
|
if (_user.mediaProgress) {
|
|
|
|
var itemProgressIdsToRemove = _user.mediaProgress.map(lip => lip.id).filter(lipId => !this.db.libraryItems.find(_li => _li.id == lipId))
|
2022-03-19 16:13:10 +01:00
|
|
|
if (itemProgressIdsToRemove.length) {
|
2022-03-26 17:59:34 +01:00
|
|
|
Logger.debug(`[Server] Found ${itemProgressIdsToRemove.length} media progress data to remove from user ${_user.username}`)
|
2022-03-19 16:13:10 +01:00
|
|
|
for (const lipId of itemProgressIdsToRemove) {
|
2022-03-26 17:59:34 +01:00
|
|
|
_user.removeMediaProgress(lipId)
|
2021-11-04 13:59:28 +01:00
|
|
|
}
|
|
|
|
await this.db.updateEntity('user', _user)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-05 05:11:42 +02:00
|
|
|
// First time login rate limit is hit
|
|
|
|
loginLimitReached(req, res, options) {
|
|
|
|
Logger.error(`[Server] Login rate limit (${options.max}) was hit for ip ${req.ip}`)
|
|
|
|
options.message = 'Too many attempts. Login temporarily locked.'
|
|
|
|
}
|
|
|
|
|
|
|
|
getLoginRateLimiter() {
|
|
|
|
return rateLimit({
|
|
|
|
windowMs: this.db.serverSettings.rateLimitLoginWindow, // 5 minutes
|
|
|
|
max: this.db.serverSettings.rateLimitLoginRequests,
|
|
|
|
skipSuccessfulRequests: true,
|
|
|
|
onLimitReached: this.loginLimitReached
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
logout(req, res) {
|
2021-10-23 03:08:02 +02:00
|
|
|
var { socketId } = req.body
|
|
|
|
Logger.info(`[Server] User ${req.user ? req.user.username : 'Unknown'} is logging out with socket ${socketId}`)
|
|
|
|
|
|
|
|
// Strip user and client from client and client socket
|
|
|
|
if (socketId && this.clients[socketId]) {
|
|
|
|
var client = this.clients[socketId]
|
|
|
|
var clientSocket = client.socket
|
|
|
|
Logger.debug(`[Server] Found user client ${clientSocket.id}, Has user: ${!!client.user}, Socket has client: ${!!clientSocket.sheepClient}`)
|
|
|
|
|
|
|
|
if (client.user) {
|
|
|
|
Logger.debug('[Server] User Offline ' + client.user.username)
|
2022-03-18 01:10:47 +01:00
|
|
|
this.io.emit('user_offline', client.user.toJSONForPublic(null, this.db.libraryItems))
|
2021-10-23 03:08:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
delete this.clients[socketId].user
|
|
|
|
if (clientSocket && clientSocket.sheepClient) delete this.clients[socketId].socket.sheepClient
|
|
|
|
} else if (socketId) {
|
|
|
|
Logger.warn(`[Server] No client for socket ${socketId}`)
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
res.sendStatus(200)
|
|
|
|
}
|
|
|
|
|
|
|
|
async authenticateSocket(socket, token) {
|
2021-11-13 02:43:16 +01:00
|
|
|
var user = await this.auth.authenticateUser(token)
|
2021-08-18 00:01:11 +02:00
|
|
|
if (!user) {
|
|
|
|
Logger.error('Cannot validate socket - invalid token')
|
|
|
|
return socket.emit('invalid_token')
|
|
|
|
}
|
|
|
|
var client = this.clients[socket.id]
|
2021-10-23 03:08:02 +02:00
|
|
|
|
|
|
|
if (client.user !== undefined) {
|
|
|
|
Logger.debug(`[Server] Authenticating socket client already has user`, client.user)
|
|
|
|
}
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
client.user = user
|
|
|
|
|
2021-08-18 00:43:29 +02:00
|
|
|
if (!client.user.toJSONForBrowser) {
|
|
|
|
Logger.error('Invalid user...', client.user)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-18 01:10:47 +01:00
|
|
|
// Check if user has session open
|
|
|
|
var session = this.playbackSessionManager.getUserSession(user.id)
|
|
|
|
if (session) {
|
|
|
|
Logger.debug(`[Server] User Online "${client.user.username}" with session open "${session.id}"`)
|
|
|
|
var sessionLibraryItem = this.db.libraryItems.find(li => li.id === session.libraryItemId)
|
|
|
|
if (!sessionLibraryItem) {
|
|
|
|
Logger.error(`[Server] Library Item for session "${session.id}" does not exist "${session.libraryItemId}"`)
|
|
|
|
this.playbackSessionManager.removeSession(session.id)
|
|
|
|
session = null
|
2022-03-26 23:41:26 +01:00
|
|
|
} else if (session.mediaType === 'podcast' && !sessionLibraryItem.media.checkHasEpisode(session.episodeId)) {
|
|
|
|
Logger.error(`[Server] Library Item for session "${session.id}" episode ${session.episodeId} does not exist "${session.libraryItemId}"`)
|
|
|
|
this.playbackSessionManager.removeSession(session.id)
|
|
|
|
session = null
|
2022-03-26 17:59:34 +01:00
|
|
|
}
|
|
|
|
if (session) {
|
|
|
|
session = session.toJSONForClient(sessionLibraryItem)
|
2022-03-18 01:10:47 +01:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Logger.debug(`[Server] User Online ${client.user.username}`)
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
2022-03-18 01:10:47 +01:00
|
|
|
this.io.emit('user_online', client.user.toJSONForPublic(this.playbackSessionManager.sessions, this.db.libraryItems))
|
2021-10-13 03:07:42 +02:00
|
|
|
|
|
|
|
user.lastSeen = Date.now()
|
|
|
|
await this.db.updateEntity('user', user)
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
const initialPayload = {
|
2022-03-10 02:23:17 +01:00
|
|
|
serverSettings: this.db.serverSettings.toJSON(),
|
2022-02-27 20:47:52 +01:00
|
|
|
audiobookPath: global.AudiobookPath,
|
|
|
|
metadataPath: global.MetadataPath,
|
|
|
|
configPath: global.ConfigPath,
|
2021-08-18 00:01:11 +02:00
|
|
|
user: client.user.toJSONForBrowser(),
|
2022-03-18 01:10:47 +01:00
|
|
|
session,
|
2021-12-25 01:06:17 +01:00
|
|
|
librariesScanning: this.scanner.librariesScanning,
|
2021-10-09 00:30:20 +02:00
|
|
|
backups: (this.backupManager.backups || []).map(b => b.toJSON())
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
2021-10-23 03:08:02 +02:00
|
|
|
if (user.type === 'root') {
|
|
|
|
initialPayload.usersOnline = this.usersOnline
|
|
|
|
}
|
2021-08-18 00:01:11 +02:00
|
|
|
client.socket.emit('init', initialPayload)
|
2021-10-01 01:52:32 +02:00
|
|
|
|
|
|
|
// Setup log listener for root user
|
|
|
|
if (user.type === 'root') {
|
|
|
|
Logger.addSocketListener(socket, this.db.serverSettings.logLevel || 0)
|
|
|
|
}
|
2021-08-18 00:01:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2022-03-17 12:06:52 +01:00
|
|
|
module.exports = Server
|