audiobookshelf/server/Server.js

351 lines
12 KiB
JavaScript
Raw Normal View History

2021-08-18 00:01:11 +02:00
const Path = require('path')
const express = require('express')
const http = require('http')
2022-07-06 02:53:01 +02:00
const fs = require('./libs/fsExtra')
2022-07-07 02:10:25 +02:00
const fileUpload = require('./libs/expressFileupload')
2022-07-07 02:14:47 +02:00
const rateLimit = require('./libs/expressRateLimit')
2021-08-18 00:01:11 +02:00
const { version } = require('../package.json')
// Utils
const filePerms = require('./utils/filePerms')
const fileUtils = require('./utils/fileUtils')
const Logger = require('./Logger')
2021-08-18 00:01:11 +02:00
const Auth = require('./Auth')
const Watcher = require('./Watcher')
const Scanner = require('./scanner/Scanner')
2023-07-05 01:14:44 +02:00
const Database = require('./Database')
const SocketAuthority = require('./SocketAuthority')
2023-07-05 01:14:44 +02:00
const routes = require('./routes/index')
const ApiRouter = require('./routers/ApiRouter')
const HlsRouter = require('./routers/HlsRouter')
2022-09-21 01:08:41 +02:00
const NotificationManager = require('./managers/NotificationManager')
const EmailManager = require('./managers/EmailManager')
const CoverManager = require('./managers/CoverManager')
const AbMergeManager = require('./managers/AbMergeManager')
const CacheManager = require('./managers/CacheManager')
const LogManager = require('./managers/LogManager')
2023-07-08 21:40:49 +02:00
const BackupManager = require('./managers/BackupManager')
const PlaybackSessionManager = require('./managers/PlaybackSessionManager')
const PodcastManager = require('./managers/PodcastManager')
const AudioMetadataMangaer = require('./managers/AudioMetadataManager')
const RssFeedManager = require('./managers/RssFeedManager')
const CronManager = require('./managers/CronManager')
const TaskManager = require('./managers/TaskManager')
2021-08-18 00:01:11 +02:00
class Server {
constructor(SOURCE, PORT, HOST, UID, GID, CONFIG_PATH, METADATA_PATH, ROUTER_BASE_PATH) {
2021-08-18 00:01:11 +02:00
this.Port = PORT
this.Host = HOST
global.Source = SOURCE
global.isWin = process.platform === 'win32'
global.Uid = isNaN(UID) ? undefined : Number(UID)
global.Gid = isNaN(GID) ? undefined : Number(GID)
global.ConfigPath = fileUtils.filePathToPOSIX(Path.normalize(CONFIG_PATH))
global.MetadataPath = fileUtils.filePathToPOSIX(Path.normalize(METADATA_PATH))
global.RouterBasePath = ROUTER_BASE_PATH
Implement X-Accel Redirect This patch implements [X-Accel](https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/) redirect headers as an optional way for offloading static file delivery from Express to Nginx, which is far better optimized for static file delivery. This provides a really easy to configure way for getting a huge performance boost over delivering all files through Audiobookshelf. How it works ------------ The way this works is basically that Audiobookshelf gets an HTTP request for delivering a static file (let's say an audiobook). It will first check the user is authorized and then convert the API path to a local file path. Now, instead of reading and delivering the file, Audiobookshelf will return just the HTTP header with an additional `X-Accel-Redirect` pointing to the file location on the file syste. This header is picked up by Nginx which will then deliver the file. Configuration ------------- The configuration for this is very simple. You need to run Nginx as reverse proxy and it must have access to your Audiobookshelf data folder. You then configure Audiobookshelf to use X-Accel by setting `USE_X_ACCEL=/protected`. The path is the internal redirect path used by Nginx. In the Nginx configuration you then configure this location and map it to the storage area to serve like this: ``` location /protected/ { internal; alias /; } ``` That's all. Impact ------ I just did a very simple performance test, downloading a 1170620819 bytes large audiobook file from another machine on the same network like this, using `time -p` to measure how log the process took: ```sh URL='https://url to audiobook…' for i in `seq 1 50` do echo "$i" curl -s -o /dev/null "${URL}" done ``` This sequential test with 50 iterations and without x-accel resulted in: ``` real 413.42 user 197.11 sys 82.04 ``` That is an average download speed of about 1080 MBit/s. With X-Accel enabled, serving the files through Nginx, the same test yielded the following results: ``` real 200.37 user 86.95 sys 29.79 ``` That is an average download speed of about 2229 MBit/s, more than doubling the previous speed. I have also run the same test with 4 parallel processes and 25 downloads each. Without x-accel, that test resulted in: ``` real 364.89 user 273.09 sys 112.75 ``` That is an average speed of about 2448 MBit/s. With X-Accel enabled, the parallel test also shows a significant speedup: ``` real 167.19 user 195.62 sys 78.61 ``` That is an average speed of about 5342 MBit/s. While doing that, I also peaked at the system load which was a bit lower when using X-Accel. Even though the system was delivering far more data. But I just looked at the `load1` values and did not build a proper test for that. That means, I cant provide any definitive data. Supported Media --------------- The current implementation works for audio files and book covers. There are other media files which would benefit from this mechanism like feed covers or author pictures. But that's something for a future developer ;-)
2022-11-25 23:41:35 +01:00
global.XAccel = process.env.USE_X_ACCEL
if (!fs.pathExistsSync(global.ConfigPath)) {
fs.mkdirSync(global.ConfigPath)
filePerms.setDefaultDirSync(global.ConfigPath, false)
}
if (!fs.pathExistsSync(global.MetadataPath)) {
fs.mkdirSync(global.MetadataPath)
filePerms.setDefaultDirSync(global.MetadataPath, false)
}
2021-08-18 00:01:11 +02:00
this.watcher = new Watcher()
2023-07-05 01:14:44 +02:00
this.auth = new Auth()
// Managers
this.taskManager = new TaskManager()
2023-07-05 01:14:44 +02:00
this.notificationManager = new NotificationManager()
this.emailManager = new EmailManager()
2023-07-08 21:40:49 +02:00
this.backupManager = new BackupManager()
2023-07-05 01:14:44 +02:00
this.logManager = new LogManager()
this.cacheManager = new CacheManager()
2023-07-05 01:14:44 +02:00
this.abMergeManager = new AbMergeManager(this.taskManager)
this.playbackSessionManager = new PlaybackSessionManager()
this.coverManager = new CoverManager(this.cacheManager)
this.podcastManager = new PodcastManager(this.watcher, this.notificationManager, this.taskManager)
this.audioMetadataManager = new AudioMetadataMangaer(this.taskManager)
this.rssFeedManager = new RssFeedManager()
2023-07-05 01:14:44 +02:00
this.scanner = new Scanner(this.coverManager, this.taskManager)
this.cronManager = new CronManager(this.scanner, this.podcastManager)
// Routers
this.apiRouter = new ApiRouter(this)
2023-07-05 01:14:44 +02:00
this.hlsRouter = new HlsRouter(this.auth, this.playbackSessionManager)
Logger.logManager = this.logManager
2021-08-18 00:01:11 +02:00
this.server = null
this.io = null
}
authMiddleware(req, res, next) {
this.auth.authMiddleware(req, res, next)
}
2021-08-18 00:01:11 +02:00
async init() {
Logger.info('[Server] Init v' + version)
await this.playbackSessionManager.removeOrphanStreams()
2021-09-23 03:40:35 +02:00
2023-07-05 01:14:44 +02:00
await Database.init(false)
2022-07-19 00:19:16 +02:00
// Create token secret if does not exist (Added v2.1.0)
2023-07-05 01:14:44 +02:00
if (!Database.serverSettings.tokenSecret) {
2022-07-19 00:19:16 +02:00
await this.auth.initTokenSecret()
}
await this.cleanUserData() // Remove invalid user item progress
await this.purgeMetadata() // Remove metadata folders without library item
2022-05-15 18:19:04 +02:00
await this.cacheManager.ensureCachePaths()
2022-06-18 20:11:15 +02:00
2023-07-08 21:40:49 +02:00
await this.backupManager.init()
await this.logManager.init()
2023-07-05 01:14:44 +02:00
await this.apiRouter.checkRemoveEmptySeries(Database.series) // Remove empty series
await this.rssFeedManager.init()
this.cronManager.init()
2023-07-05 01:14:44 +02:00
if (Database.serverSettings.scannerDisableWatcher) {
Logger.info(`[Server] Watcher is disabled`)
this.watcher.disabled = true
} else {
2023-07-05 01:14:44 +02:00
this.watcher.initWatcher(Database.libraries)
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()
const router = express.Router()
app.use(global.RouterBasePath, router)
app.disable('x-powered-by')
2021-08-18 00:01:11 +02:00
this.server = http.createServer(app)
router.use(this.auth.cors)
2023-06-04 06:44:13 +02:00
router.use(fileUpload({
defCharset: 'utf8',
defParamCharset: 'utf8',
useTempFiles: true,
2023-06-06 22:40:52 +02:00
tempFileDir: Path.join(global.MetadataPath, 'tmp')
2023-06-04 06:44:13 +02:00
}))
router.use(express.urlencoded({ extended: true, limit: "5mb" }));
router.use(express.json({ limit: "5mb" }))
2021-08-18 00:01:11 +02:00
// Static path to generated nuxt
const distPath = Path.join(global.appRoot, '/client/dist')
router.use(express.static(distPath))
// Static folder
router.use(express.static(Path.join(global.appRoot, 'static')))
2021-08-18 00:01:11 +02:00
2023-07-05 01:14:44 +02:00
// router.use('/api/v1', routes) // TODO: New routes
router.use('/api', this.authMiddleware.bind(this), this.apiRouter.router)
router.use('/hls', this.authMiddleware.bind(this), this.hlsRouter.router)
// RSS Feed temp route
router.get('/feed/:slug', (req, res) => {
Logger.info(`[Server] Requesting rss feed ${req.params.slug}`)
this.rssFeedManager.getFeed(req, res)
})
router.get('/feed/:slug/cover', (req, res) => {
this.rssFeedManager.getFeedCover(req, res)
})
router.get('/feed/:slug/item/:episodeId/*', (req, res) => {
Logger.debug(`[Server] Requesting rss feed episode ${req.params.slug}/${req.params.episodeId}`)
this.rssFeedManager.getFeedItem(req, res)
})
// Client dynamic routes
const dyanimicRoutes = [
'/item/:id',
'/author/:id',
'/audiobook/:id/chapters',
'/audiobook/:id/edit',
'/audiobook/:id/manage',
'/library/:library',
'/library/:library/search',
'/library/:library/bookshelf/:id?',
'/library/:library/authors',
'/library/:library/series/:id?',
2022-09-17 22:23:33 +02:00
'/library/:library/podcast/search',
'/library/:library/podcast/latest',
'/config/users/:id',
'/config/users/:id/sessions',
'/config/item-metadata-utils/:id',
2022-11-27 21:23:28 +01:00
'/collection/:id',
'/playlist/:id'
]
dyanimicRoutes.forEach((route) => router.get(route, (req, res) => res.sendFile(Path.join(distPath, 'index.html'))))
router.post('/login', this.getLoginRateLimiter(), (req, res) => this.auth.login(req, res))
router.post('/logout', this.authMiddleware.bind(this), this.logout.bind(this))
router.post('/init', (req, res) => {
2023-07-05 01:14:44 +02:00
if (Database.hasRootUser) {
Logger.error(`[Server] attempt to init server when server already has a root user`)
return res.sendStatus(500)
}
this.initializeServer(req, res)
})
router.get('/status', (req, res) => {
// status check for client to see if server has been initialized
// server has been initialized if a root user exists
const payload = {
2023-07-05 01:14:44 +02:00
isInit: Database.hasRootUser,
language: Database.serverSettings.language
}
if (!payload.isInit) {
payload.ConfigPath = global.ConfigPath
payload.MetadataPath = global.MetadataPath
}
res.json(payload)
})
router.get('/ping', (req, res) => {
2022-07-30 15:37:35 +02:00
Logger.info('Received ping')
2021-08-18 00:01:11 +02:00
res.json({ success: true })
})
app.get('/healthcheck', (req, res) => res.sendStatus(200))
2021-08-18 00:01:11 +02:00
this.server.listen(this.Port, this.Host, () => {
if (this.Host) Logger.info(`Listening on http://${this.Host}:${this.Port}`)
else Logger.info(`Listening on port :${this.Port}`)
2021-08-18 00:01:11 +02:00
})
// Start listening for socket connections
SocketAuthority.initialize(this)
2021-08-18 00:01:11 +02:00
}
async initializeServer(req, res) {
Logger.info(`[Server] Initializing new server`)
const newRoot = req.body.newRoot
const rootUsername = newRoot.username || 'root'
const rootPash = newRoot.password ? await this.auth.hashPass(newRoot.password) : ''
if (!rootPash) Logger.warn(`[Server] Creating root user with no password`)
await Database.createRootUser(rootUsername, rootPash, this.auth)
res.sendStatus(200)
}
async filesChanged(fileUpdates) {
Logger.info('[Server]', fileUpdates.length, 'Files Changed')
await this.scanner.scanFilesChanged(fileUpdates)
}
// Remove unused /metadata/items/{id} folders
async purgeMetadata() {
const itemsMetadata = Path.join(global.MetadataPath, 'items')
if (!(await fs.pathExists(itemsMetadata))) return
const foldersInItemsMetadata = await fs.readdir(itemsMetadata)
let purged = 0
await Promise.all(foldersInItemsMetadata.map(async foldername => {
2023-07-11 00:00:31 +02:00
const itemFullPath = fileUtils.filePathToPOSIX(Path.join(itemsMetadata, foldername))
const hasMatchingItem = Database.libraryItems.find(li => {
if (!li.media.coverPath) return false
return itemFullPath === fileUtils.filePathToPOSIX(Path.dirname(li.media.coverPath))
})
if (!hasMatchingItem) {
2023-07-11 00:00:31 +02:00
Logger.debug(`[Server] Purging unused metadata ${itemFullPath}`)
2023-07-11 00:00:31 +02:00
await fs.remove(itemFullPath).then(() => {
purged++
}).catch((err) => {
2023-07-11 00:00:31 +02:00
Logger.error(`[Server] Failed to delete folder path ${itemFullPath}`, err)
})
}
}))
if (purged > 0) {
Logger.info(`[Server] Purged ${purged} unused library item metadata`)
}
return purged
}
// Remove user media progress with items that no longer exist & remove seriesHideFrom that no longer exist
async cleanUserData() {
2023-07-05 01:14:44 +02:00
for (const _user of Database.users) {
if (_user.mediaProgress.length) {
2023-07-05 01:14:44 +02:00
for (const mediaProgress of _user.mediaProgress) {
const libraryItem = Database.libraryItems.find(li => li.id === mediaProgress.libraryItemId)
if (libraryItem && mediaProgress.episodeId) {
const episode = libraryItem.media.checkHasEpisode?.(mediaProgress.episodeId)
if (episode) continue
} else {
continue
}
2023-07-05 01:14:44 +02:00
Logger.debug(`[Server] Removing media progress ${mediaProgress.id} data from user ${_user.username}`)
await Database.removeMediaProgress(mediaProgress.id)
}
}
2023-07-05 01:14:44 +02:00
let hasUpdated = false
if (_user.seriesHideFromContinueListening.length) {
_user.seriesHideFromContinueListening = _user.seriesHideFromContinueListening.filter(seriesId => {
2023-07-05 01:14:44 +02:00
if (!Database.series.some(se => se.id === seriesId)) { // Series removed
hasUpdated = true
return false
}
return true
})
}
if (hasUpdated) {
2023-07-05 01:14:44 +02:00
await Database.updateUser(_user)
}
}
}
// 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({
2023-07-05 01:14:44 +02:00
windowMs: Database.serverSettings.rateLimitLoginWindow, // 5 minutes
max: Database.serverSettings.rateLimitLoginRequests,
skipSuccessfulRequests: true,
onLimitReached: this.loginLimitReached
})
}
2021-08-18 00:01:11 +02:00
logout(req, res) {
if (req.body.socketId) {
Logger.info(`[Server] User ${req.user ? req.user.username : 'Unknown'} is logging out with socket ${req.body.socketId}`)
SocketAuthority.logout(req.body.socketId)
}
2021-08-18 00:01:11 +02:00
res.sendStatus(200)
}
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