mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-07-15 22:01:37 +00:00
Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
b3f9a40f18
227 changed files with 11338 additions and 3382 deletions
|
|
@ -15,8 +15,6 @@ class AbMergeManager {
|
|||
this.taskManager = taskManager
|
||||
|
||||
this.itemsCacheDir = Path.join(global.MetadataPath, 'cache/items')
|
||||
this.downloadDirPath = Path.join(global.MetadataPath, 'downloads')
|
||||
this.downloadDirPathExist = false
|
||||
|
||||
this.pendingTasks = []
|
||||
}
|
||||
|
|
@ -29,22 +27,6 @@ class AbMergeManager {
|
|||
return this.removeTask(task, true)
|
||||
}
|
||||
|
||||
async ensureDownloadDirPath() { // Creates download path if necessary and sets owner and permissions
|
||||
if (this.downloadDirPathExist) return
|
||||
|
||||
var pathCreated = false
|
||||
if (!(await fs.pathExists(this.downloadDirPath))) {
|
||||
await fs.mkdir(this.downloadDirPath)
|
||||
pathCreated = true
|
||||
}
|
||||
|
||||
if (pathCreated) {
|
||||
await filePerms.setDefault(this.downloadDirPath)
|
||||
}
|
||||
|
||||
this.downloadDirPathExist = true
|
||||
}
|
||||
|
||||
async startAudiobookMerge(user, libraryItem, options = {}) {
|
||||
const task = new Task()
|
||||
|
||||
|
|
@ -64,7 +46,7 @@ class AbMergeManager {
|
|||
toneJsonObject: null
|
||||
}
|
||||
const taskDescription = `Encoding audiobook "${libraryItem.media.metadata.title}" into a single m4b file.`
|
||||
task.setData('encode-m4b', 'Encoding M4b', taskDescription, taskData)
|
||||
task.setData('encode-m4b', 'Encoding M4b', taskDescription, false, taskData)
|
||||
this.taskManager.addTask(task)
|
||||
Logger.info(`Start m4b encode for ${libraryItem.id} - TaskId: ${task.id}`)
|
||||
|
||||
|
|
@ -130,7 +112,7 @@ class AbMergeManager {
|
|||
let toneJsonPath = null
|
||||
try {
|
||||
toneJsonPath = Path.join(task.data.itemCachePath, 'metadata.json')
|
||||
await toneHelpers.writeToneMetadataJsonFile(libraryItem, libraryItem.media.chapters, toneJsonPath, 1)
|
||||
await toneHelpers.writeToneMetadataJsonFile(libraryItem, libraryItem.media.chapters, toneJsonPath, 1, 'audio/mp4')
|
||||
} catch (error) {
|
||||
Logger.error(`[AbMergeManager] Write metadata.json failed`, error)
|
||||
toneJsonPath = null
|
||||
|
|
|
|||
|
|
@ -5,18 +5,45 @@ const Logger = require('../Logger')
|
|||
|
||||
const fs = require('../libs/fsExtra')
|
||||
|
||||
const { secondsToTimestamp } = require('../utils/index')
|
||||
const toneHelpers = require('../utils/toneHelpers')
|
||||
const filePerms = require('../utils/filePerms')
|
||||
|
||||
const Task = require('../objects/Task')
|
||||
|
||||
class AudioMetadataMangaer {
|
||||
constructor(db, taskManager) {
|
||||
this.db = db
|
||||
this.taskManager = taskManager
|
||||
|
||||
this.itemsCacheDir = Path.join(global.MetadataPath, 'cache/items')
|
||||
|
||||
this.MAX_CONCURRENT_TASKS = 1
|
||||
this.tasksRunning = []
|
||||
this.tasksQueued = []
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queued task data
|
||||
* @return {Array}
|
||||
*/
|
||||
getQueuedTaskData() {
|
||||
return this.tasksQueued.map(t => t.data)
|
||||
}
|
||||
|
||||
getIsLibraryItemQueuedOrProcessing(libraryItemId) {
|
||||
return this.tasksQueued.some(t => t.data.libraryItemId === libraryItemId) || this.tasksRunning.some(t => t.data.libraryItemId === libraryItemId)
|
||||
}
|
||||
|
||||
getToneMetadataObjectForApi(libraryItem) {
|
||||
return toneHelpers.getToneMetadataObject(libraryItem)
|
||||
const audioFiles = libraryItem.media.includedAudioFiles
|
||||
let mimeType = audioFiles[0].mimeType
|
||||
if (audioFiles.some(a => a.mimeType !== mimeType)) mimeType = null
|
||||
return toneHelpers.getToneMetadataObject(libraryItem, libraryItem.media.chapters, libraryItem.media.tracks.length, mimeType)
|
||||
}
|
||||
|
||||
handleBatchEmbed(user, libraryItems, options = {}) {
|
||||
libraryItems.forEach((li) => {
|
||||
this.updateMetadataForItem(user, li, options)
|
||||
})
|
||||
}
|
||||
|
||||
async updateMetadataForItem(user, libraryItem, options = {}) {
|
||||
|
|
@ -25,99 +52,147 @@ class AudioMetadataMangaer {
|
|||
|
||||
const audioFiles = libraryItem.media.includedAudioFiles
|
||||
|
||||
const itemAudioMetadataPayload = {
|
||||
userId: user.id,
|
||||
const task = new Task()
|
||||
|
||||
const itemCachePath = Path.join(this.itemsCacheDir, libraryItem.id)
|
||||
|
||||
// Only writing chapters for single file audiobooks
|
||||
const chapters = (audioFiles.length == 1 || forceEmbedChapters) ? libraryItem.media.chapters.map(c => ({ ...c })) : null
|
||||
|
||||
let mimeType = audioFiles[0].mimeType
|
||||
if (audioFiles.some(a => a.mimeType !== mimeType)) mimeType = null
|
||||
|
||||
// Create task
|
||||
const taskData = {
|
||||
libraryItemId: libraryItem.id,
|
||||
startedAt: Date.now(),
|
||||
audioFiles: audioFiles.map(af => ({ index: af.index, ino: af.ino, filename: af.metadata.filename }))
|
||||
libraryItemPath: libraryItem.path,
|
||||
userId: user.id,
|
||||
audioFiles: audioFiles.map(af => (
|
||||
{
|
||||
index: af.index,
|
||||
ino: af.ino,
|
||||
filename: af.metadata.filename,
|
||||
path: af.metadata.path,
|
||||
cachePath: Path.join(itemCachePath, af.metadata.filename)
|
||||
}
|
||||
)),
|
||||
coverPath: libraryItem.media.coverPath,
|
||||
metadataObject: toneHelpers.getToneMetadataObject(libraryItem, chapters, audioFiles.length, mimeType),
|
||||
itemCachePath,
|
||||
chapters,
|
||||
options: {
|
||||
forceEmbedChapters,
|
||||
backupFiles
|
||||
}
|
||||
}
|
||||
const taskDescription = `Embedding metadata in audiobook "${libraryItem.media.metadata.title}".`
|
||||
task.setData('embed-metadata', 'Embedding Metadata', taskDescription, false, taskData)
|
||||
|
||||
SocketAuthority.emitter('audio_metadata_started', itemAudioMetadataPayload)
|
||||
if (this.tasksRunning.length >= this.MAX_CONCURRENT_TASKS) {
|
||||
Logger.info(`[AudioMetadataManager] Queueing embed metadata for audiobook "${libraryItem.media.metadata.title}"`)
|
||||
SocketAuthority.adminEmitter('metadata_embed_queue_update', {
|
||||
libraryItemId: libraryItem.id,
|
||||
queued: true
|
||||
})
|
||||
this.tasksQueued.push(task)
|
||||
} else {
|
||||
this.runMetadataEmbed(task)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure folder for backup files
|
||||
const itemCacheDir = Path.join(global.MetadataPath, `cache/items/${libraryItem.id}`)
|
||||
async runMetadataEmbed(task) {
|
||||
this.tasksRunning.push(task)
|
||||
this.taskManager.addTask(task)
|
||||
|
||||
Logger.info(`[AudioMetadataManager] Starting metadata embed task`, task.description)
|
||||
|
||||
// Ensure item cache dir exists
|
||||
let cacheDirCreated = false
|
||||
if (!await fs.pathExists(itemCacheDir)) {
|
||||
await fs.mkdir(itemCacheDir)
|
||||
await filePerms.setDefault(itemCacheDir, true)
|
||||
if (!await fs.pathExists(task.data.itemCachePath)) {
|
||||
await fs.mkdir(task.data.itemCachePath)
|
||||
cacheDirCreated = true
|
||||
}
|
||||
|
||||
// Write chapters file
|
||||
const toneJsonPath = Path.join(itemCacheDir, 'metadata.json')
|
||||
|
||||
// Create metadata json file
|
||||
const toneJsonPath = Path.join(task.data.itemCachePath, 'metadata.json')
|
||||
try {
|
||||
const chapters = (audioFiles.length == 1 || forceEmbedChapters) ? libraryItem.media.chapters : null
|
||||
await toneHelpers.writeToneMetadataJsonFile(libraryItem, chapters, toneJsonPath, audioFiles.length)
|
||||
await fs.writeFile(toneJsonPath, JSON.stringify({ meta: task.data.metadataObject }, null, 2))
|
||||
} catch (error) {
|
||||
Logger.error(`[AudioMetadataManager] Write metadata.json failed`, error)
|
||||
|
||||
itemAudioMetadataPayload.failed = true
|
||||
itemAudioMetadataPayload.error = 'Failed to write metadata.json'
|
||||
SocketAuthority.emitter('audio_metadata_finished', itemAudioMetadataPayload)
|
||||
task.setFailed('Failed to write metadata.json')
|
||||
this.handleTaskFinished(task)
|
||||
return
|
||||
}
|
||||
|
||||
const results = []
|
||||
for (const af of audioFiles) {
|
||||
const result = await this.updateAudioFileMetadataWithTone(libraryItem, af, toneJsonPath, itemCacheDir, backupFiles)
|
||||
results.push(result)
|
||||
// Tag audio files
|
||||
for (const af of task.data.audioFiles) {
|
||||
SocketAuthority.adminEmitter('audiofile_metadata_started', {
|
||||
libraryItemId: task.data.libraryItemId,
|
||||
ino: af.ino
|
||||
})
|
||||
|
||||
// Backup audio file
|
||||
if (task.data.options.backupFiles) {
|
||||
try {
|
||||
const backupFilePath = Path.join(task.data.itemCachePath, af.filename)
|
||||
await fs.copy(af.path, backupFilePath)
|
||||
Logger.debug(`[AudioMetadataManager] Backed up audio file at "${backupFilePath}"`)
|
||||
} catch (err) {
|
||||
Logger.error(`[AudioMetadataManager] Failed to backup audio file "${af.path}"`, err)
|
||||
}
|
||||
}
|
||||
|
||||
const _toneMetadataObject = {
|
||||
'ToneJsonFile': toneJsonPath,
|
||||
'TrackNumber': af.index,
|
||||
}
|
||||
|
||||
if (task.data.coverPath) {
|
||||
_toneMetadataObject['CoverFile'] = task.data.coverPath
|
||||
}
|
||||
|
||||
const success = await toneHelpers.tagAudioFile(af.path, _toneMetadataObject)
|
||||
if (success) {
|
||||
Logger.info(`[AudioMetadataManager] Successfully tagged audio file "${af.path}"`)
|
||||
}
|
||||
|
||||
SocketAuthority.adminEmitter('audiofile_metadata_finished', {
|
||||
libraryItemId: task.data.libraryItemId,
|
||||
ino: af.ino
|
||||
})
|
||||
}
|
||||
|
||||
// Remove temp cache file/folder if not backing up
|
||||
if (!backupFiles) {
|
||||
if (!task.data.options.backupFiles) {
|
||||
// If cache dir was created from this then remove it
|
||||
if (cacheDirCreated) {
|
||||
await fs.remove(itemCacheDir)
|
||||
await fs.remove(task.data.itemCachePath)
|
||||
} else {
|
||||
await fs.remove(toneJsonPath)
|
||||
}
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - itemAudioMetadataPayload.startedAt
|
||||
Logger.debug(`[AudioMetadataManager] Elapsed ${secondsToTimestamp(elapsed / 1000, true)}`)
|
||||
itemAudioMetadataPayload.results = results
|
||||
itemAudioMetadataPayload.elapsed = elapsed
|
||||
itemAudioMetadataPayload.finishedAt = Date.now()
|
||||
SocketAuthority.emitter('audio_metadata_finished', itemAudioMetadataPayload)
|
||||
task.setFinished()
|
||||
this.handleTaskFinished(task)
|
||||
}
|
||||
|
||||
async updateAudioFileMetadataWithTone(libraryItem, audioFile, toneJsonPath, itemCacheDir, backupFiles) {
|
||||
const resultPayload = {
|
||||
libraryItemId: libraryItem.id,
|
||||
index: audioFile.index,
|
||||
ino: audioFile.ino,
|
||||
filename: audioFile.metadata.filename
|
||||
}
|
||||
SocketAuthority.emitter('audiofile_metadata_started', resultPayload)
|
||||
handleTaskFinished(task) {
|
||||
this.taskManager.taskFinished(task)
|
||||
this.tasksRunning = this.tasksRunning.filter(t => t.id !== task.id)
|
||||
|
||||
// Backup audio file
|
||||
if (backupFiles) {
|
||||
try {
|
||||
const backupFilePath = Path.join(itemCacheDir, audioFile.metadata.filename)
|
||||
await fs.copy(audioFile.metadata.path, backupFilePath)
|
||||
Logger.debug(`[AudioMetadataManager] Backed up audio file at "${backupFilePath}"`)
|
||||
} catch (err) {
|
||||
Logger.error(`[AudioMetadataManager] Failed to backup audio file "${audioFile.metadata.path}"`, err)
|
||||
}
|
||||
if (this.tasksRunning.length < this.MAX_CONCURRENT_TASKS && this.tasksQueued.length) {
|
||||
Logger.info(`[AudioMetadataManager] Task finished and dequeueing next task. ${this.tasksQueued} tasks queued.`)
|
||||
const nextTask = this.tasksQueued.shift()
|
||||
SocketAuthority.emitter('metadata_embed_queue_update', {
|
||||
libraryItemId: nextTask.data.libraryItemId,
|
||||
queued: false
|
||||
})
|
||||
this.runMetadataEmbed(nextTask)
|
||||
} else if (this.tasksRunning.length > 0) {
|
||||
Logger.debug(`[AudioMetadataManager] Task finished but not dequeueing. Currently running ${this.tasksRunning.length} tasks. ${this.tasksQueued.length} tasks queued.`)
|
||||
} else {
|
||||
Logger.debug(`[AudioMetadataManager] Task finished and no tasks remain in queue`)
|
||||
}
|
||||
|
||||
const _toneMetadataObject = {
|
||||
'ToneJsonFile': toneJsonPath,
|
||||
'TrackNumber': audioFile.index,
|
||||
}
|
||||
|
||||
if (libraryItem.media.coverPath) {
|
||||
_toneMetadataObject['CoverFile'] = libraryItem.media.coverPath
|
||||
}
|
||||
|
||||
resultPayload.success = await toneHelpers.tagAudioFile(audioFile.metadata.path, _toneMetadataObject)
|
||||
if (resultPayload.success) {
|
||||
Logger.info(`[AudioMetadataManager] Successfully tagged audio file "${audioFile.metadata.path}"`)
|
||||
}
|
||||
|
||||
SocketAuthority.emitter('audiofile_metadata_finished', resultPayload)
|
||||
return resultPayload
|
||||
}
|
||||
}
|
||||
module.exports = AudioMetadataMangaer
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@ class CronManager {
|
|||
for (const libraryItem of libraryItems) {
|
||||
const keepAutoDownloading = await this.podcastManager.runEpisodeCheck(libraryItem)
|
||||
if (!keepAutoDownloading) { // auto download was disabled
|
||||
podcastCron.libraryItemIds = podcastCron.libraryItemIds.filter(lid => lid !== libraryItemId) // Filter it out
|
||||
podcastCron.libraryItemIds = podcastCron.libraryItemIds.filter(lid => lid !== libraryItem.id) // Filter it out
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,80 +0,0 @@
|
|||
const Logger = require('../Logger')
|
||||
const StreamZip = require('../libs/nodeStreamZip')
|
||||
|
||||
const parseEpub = require('../utils/parsers/parseEpub')
|
||||
|
||||
class EBookManager {
|
||||
constructor() {
|
||||
this.extractedEpubs = {}
|
||||
}
|
||||
|
||||
async extractBookData(libraryItem, user, isDev = false) {
|
||||
if (!libraryItem || !libraryItem.isBook || !libraryItem.media.ebookFile) return null
|
||||
|
||||
if (this.extractedEpubs[libraryItem.id]) return this.extractedEpubs[libraryItem.id]
|
||||
|
||||
const ebookFile = libraryItem.media.ebookFile
|
||||
if (!ebookFile.isEpub) {
|
||||
Logger.error(`[EBookManager] get book data is not supported for format ${ebookFile.ebookFormat}`)
|
||||
return null
|
||||
}
|
||||
|
||||
this.extractedEpubs[libraryItem.id] = await parseEpub.parse(ebookFile, libraryItem.id, user.token, isDev)
|
||||
|
||||
return this.extractedEpubs[libraryItem.id]
|
||||
}
|
||||
|
||||
async getBookInfo(libraryItem, user, isDev = false) {
|
||||
if (!libraryItem || !libraryItem.isBook || !libraryItem.media.ebookFile) return null
|
||||
|
||||
const bookData = await this.extractBookData(libraryItem, user, isDev)
|
||||
|
||||
return {
|
||||
title: libraryItem.media.metadata.title,
|
||||
pages: bookData.pages.length
|
||||
}
|
||||
}
|
||||
|
||||
async getBookPage(libraryItem, user, pageIndex, isDev = false) {
|
||||
if (!libraryItem || !libraryItem.isBook || !libraryItem.media.ebookFile) return null
|
||||
|
||||
const bookData = await this.extractBookData(libraryItem, user, isDev)
|
||||
|
||||
const pageObj = bookData.pages[pageIndex]
|
||||
|
||||
if (!pageObj) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = await parseEpub.parsePage(pageObj.path, bookData, libraryItem.id, user.token, isDev)
|
||||
|
||||
if (parsed.error) {
|
||||
Logger.error(`[EBookManager] Failed to parse epub page at "${pageObj.path}"`, parsed.error)
|
||||
return null
|
||||
}
|
||||
|
||||
return parsed.html
|
||||
}
|
||||
|
||||
async getBookResource(libraryItem, user, resourcePath, isDev = false, res) {
|
||||
if (!libraryItem || !libraryItem.isBook || !libraryItem.media.ebookFile) return res.sendStatus(500)
|
||||
const bookData = await this.extractBookData(libraryItem, user, isDev)
|
||||
const resourceItem = bookData.resources.find(r => r.path === resourcePath)
|
||||
|
||||
if (!resourceItem) {
|
||||
return res.status(404).send('Resource not found')
|
||||
}
|
||||
|
||||
const zip = new StreamZip.async({ file: bookData.filepath })
|
||||
const stm = await zip.stream(resourceItem.path)
|
||||
|
||||
res.set('content-type', resourceItem['media-type'])
|
||||
|
||||
stm.pipe(res)
|
||||
stm.on('end', () => {
|
||||
zip.close()
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
module.exports = EBookManager
|
||||
73
server/managers/EmailManager.js
Normal file
73
server/managers/EmailManager.js
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
const nodemailer = require('nodemailer')
|
||||
const Logger = require("../Logger")
|
||||
const SocketAuthority = require('../SocketAuthority')
|
||||
|
||||
class EmailManager {
|
||||
constructor(db) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
getTransporter() {
|
||||
return nodemailer.createTransport(this.db.emailSettings.getTransportObject())
|
||||
}
|
||||
|
||||
async sendTest(res) {
|
||||
Logger.info(`[EmailManager] Sending test email`)
|
||||
const transporter = this.getTransporter()
|
||||
|
||||
const success = await transporter.verify().catch((error) => {
|
||||
Logger.error(`[EmailManager] Failed to verify SMTP connection config`, error)
|
||||
return false
|
||||
})
|
||||
|
||||
if (!success) {
|
||||
return res.status(400).send('Failed to verify SMTP connection configuration')
|
||||
}
|
||||
|
||||
transporter.sendMail({
|
||||
from: this.db.emailSettings.fromAddress,
|
||||
to: this.db.emailSettings.fromAddress,
|
||||
subject: 'Test email from Audiobookshelf',
|
||||
text: 'Success!'
|
||||
}).then((result) => {
|
||||
Logger.info(`[EmailManager] Test email sent successfully`, result)
|
||||
res.sendStatus(200)
|
||||
}).catch((error) => {
|
||||
Logger.error(`[EmailManager] Failed to send test email`, error)
|
||||
res.status(400).send(error.message || 'Failed to send test email')
|
||||
})
|
||||
}
|
||||
|
||||
async sendEBookToDevice(ebookFile, device, res) {
|
||||
Logger.info(`[EmailManager] Sending ebook "${ebookFile.metadata.filename}" to device "${device.name}"/"${device.email}"`)
|
||||
const transporter = this.getTransporter()
|
||||
|
||||
const success = await transporter.verify().catch((error) => {
|
||||
Logger.error(`[EmailManager] Failed to verify SMTP connection config`, error)
|
||||
return false
|
||||
})
|
||||
|
||||
if (!success) {
|
||||
return res.status(400).send('Failed to verify SMTP connection configuration')
|
||||
}
|
||||
|
||||
transporter.sendMail({
|
||||
from: this.db.emailSettings.fromAddress,
|
||||
to: device.email,
|
||||
html: '<div dir="auto"></div>',
|
||||
attachments: [
|
||||
{
|
||||
filename: ebookFile.metadata.filename,
|
||||
path: ebookFile.metadata.path,
|
||||
}
|
||||
]
|
||||
}).then((result) => {
|
||||
Logger.info(`[EmailManager] Ebook sent to device successfully`, result)
|
||||
res.sendStatus(200)
|
||||
}).catch((error) => {
|
||||
Logger.error(`[EmailManager] Failed to send ebook to device`, error)
|
||||
res.status(400).send(error.message || 'Failed to send ebook to device')
|
||||
})
|
||||
}
|
||||
}
|
||||
module.exports = EmailManager
|
||||
|
|
@ -14,7 +14,6 @@ const PlaybackSession = require('../objects/PlaybackSession')
|
|||
const DeviceInfo = require('../objects/DeviceInfo')
|
||||
const Stream = require('../objects/Stream')
|
||||
|
||||
|
||||
class PlaybackSessionManager {
|
||||
constructor(db) {
|
||||
this.db = db
|
||||
|
|
@ -31,13 +30,14 @@ class PlaybackSessionManager {
|
|||
}
|
||||
getStream(sessionId) {
|
||||
const session = this.getSession(sessionId)
|
||||
return session ? session.stream : null
|
||||
return session?.stream || null
|
||||
}
|
||||
|
||||
getDeviceInfo(req) {
|
||||
const ua = uaParserJs(req.headers['user-agent'])
|
||||
const ip = requestIp.getClientIp(req)
|
||||
const clientDeviceInfo = req.body ? req.body.deviceInfo || null : null // From mobile client
|
||||
|
||||
const clientDeviceInfo = req.body?.deviceInfo || null
|
||||
|
||||
const deviceInfo = new DeviceInfo()
|
||||
deviceInfo.setData(ip, ua, clientDeviceInfo, serverVersion)
|
||||
|
|
@ -130,6 +130,8 @@ class PlaybackSessionManager {
|
|||
const itemProgress = user.getMediaProgress(session.libraryItemId, session.episodeId)
|
||||
SocketAuthority.clientEmitter(user.id, 'user_item_progress_updated', {
|
||||
id: itemProgress.id,
|
||||
sessionId: session.id,
|
||||
deviceDescription: session.deviceDescription,
|
||||
data: itemProgress.toJSON()
|
||||
})
|
||||
}
|
||||
|
|
@ -138,18 +140,6 @@ class PlaybackSessionManager {
|
|||
}
|
||||
|
||||
async syncLocalSessionRequest(user, sessionJson, res) {
|
||||
// If server session is open for this same media item then close it
|
||||
const userSessionForThisItem = this.sessions.find(playbackSession => {
|
||||
if (playbackSession.userId !== user.id) return false
|
||||
if (sessionJson.episodeId) return playbackSession.episodeId !== sessionJson.episodeId
|
||||
return playbackSession.libraryItemId === sessionJson.libraryItemId
|
||||
})
|
||||
if (userSessionForThisItem) {
|
||||
Logger.info(`[PlaybackSessionManager] syncLocalSessionRequest: Closing open session "${userSessionForThisItem.displayTitle}" for user "${user.username}"`)
|
||||
await this.closeSession(user, userSessionForThisItem, null)
|
||||
}
|
||||
|
||||
// Sync
|
||||
const result = await this.syncLocalSession(user, sessionJson)
|
||||
if (result.error) {
|
||||
res.status(500).send(result.error)
|
||||
|
|
@ -164,8 +154,8 @@ class PlaybackSessionManager {
|
|||
}
|
||||
|
||||
async startSession(user, deviceInfo, libraryItem, episodeId, options) {
|
||||
// Close any sessions already open for user
|
||||
const userSessions = this.sessions.filter(playbackSession => playbackSession.userId === user.id)
|
||||
// Close any sessions already open for user and device
|
||||
const userSessions = this.sessions.filter(playbackSession => playbackSession.userId === user.id && playbackSession.deviceId === deviceInfo.deviceId)
|
||||
for (const session of userSessions) {
|
||||
Logger.info(`[PlaybackSessionManager] startSession: Closing open session "${session.displayTitle}" for user "${user.username}" (Device: ${session.deviceDescription})`)
|
||||
await this.closeSession(user, session, null)
|
||||
|
|
@ -251,6 +241,8 @@ class PlaybackSessionManager {
|
|||
const itemProgress = user.getMediaProgress(session.libraryItemId, session.episodeId)
|
||||
SocketAuthority.clientEmitter(user.id, 'user_item_progress_updated', {
|
||||
id: itemProgress.id,
|
||||
sessionId: session.id,
|
||||
deviceDescription: session.deviceDescription,
|
||||
data: itemProgress.toJSON()
|
||||
})
|
||||
}
|
||||
|
|
@ -268,6 +260,7 @@ class PlaybackSessionManager {
|
|||
}
|
||||
Logger.debug(`[PlaybackSessionManager] closeSession "${session.id}"`)
|
||||
SocketAuthority.adminEmitter('user_stream_update', user.toJSONForPublic(this.sessions, this.db.libraryItems))
|
||||
SocketAuthority.clientEmitter(session.userId, 'user_session_closed', session.id)
|
||||
return this.removeSession(session.id)
|
||||
}
|
||||
|
||||
|
|
@ -317,7 +310,7 @@ class PlaybackSessionManager {
|
|||
// See https://github.com/advplyr/audiobookshelf/issues/868
|
||||
// Remove playback sessions with listening time too high
|
||||
async removeInvalidSessions() {
|
||||
const selectFunc = (session) => isNaN(session.timeListening) || Number(session.timeListening) > 3600000000
|
||||
const selectFunc = (session) => isNaN(session.timeListening) || Number(session.timeListening) > 36000000
|
||||
const numSessionsRemoved = await this.db.removeEntities('session', selectFunc, true)
|
||||
if (numSessionsRemoved) {
|
||||
Logger.info(`[PlaybackSessionManager] Removed ${numSessionsRemoved} invalid playback sessions`)
|
||||
|
|
|
|||
|
|
@ -4,22 +4,26 @@ const SocketAuthority = require('../SocketAuthority')
|
|||
const fs = require('../libs/fsExtra')
|
||||
|
||||
const { getPodcastFeed } = require('../utils/podcastUtils')
|
||||
const { downloadFile, removeFile } = require('../utils/fileUtils')
|
||||
const { removeFile, downloadFile } = require('../utils/fileUtils')
|
||||
const filePerms = require('../utils/filePerms')
|
||||
const { levenshteinDistance } = require('../utils/index')
|
||||
const opmlParser = require('../utils/parsers/parseOPML')
|
||||
const opmlGenerator = require('../utils/generators/opmlGenerator')
|
||||
const prober = require('../utils/prober')
|
||||
const ffmpegHelpers = require('../utils/ffmpegHelpers')
|
||||
|
||||
const LibraryFile = require('../objects/files/LibraryFile')
|
||||
const PodcastEpisodeDownload = require('../objects/PodcastEpisodeDownload')
|
||||
const PodcastEpisode = require('../objects/entities/PodcastEpisode')
|
||||
const AudioFile = require('../objects/files/AudioFile')
|
||||
const Task = require("../objects/Task")
|
||||
|
||||
class PodcastManager {
|
||||
constructor(db, watcher, notificationManager) {
|
||||
constructor(db, watcher, notificationManager, taskManager) {
|
||||
this.db = db
|
||||
this.watcher = watcher
|
||||
this.notificationManager = notificationManager
|
||||
this.taskManager = taskManager
|
||||
|
||||
this.downloadQueue = []
|
||||
this.currentDownload = null
|
||||
|
|
@ -50,27 +54,44 @@ class PodcastManager {
|
|||
}
|
||||
|
||||
async downloadPodcastEpisodes(libraryItem, episodesToDownload, isAutoDownload) {
|
||||
var index = libraryItem.media.episodes.length + 1
|
||||
episodesToDownload.forEach((ep) => {
|
||||
var newPe = new PodcastEpisode()
|
||||
let index = libraryItem.media.episodes.length + 1
|
||||
for (const ep of episodesToDownload) {
|
||||
const newPe = new PodcastEpisode()
|
||||
newPe.setData(ep, index++)
|
||||
newPe.libraryItemId = libraryItem.id
|
||||
var newPeDl = new PodcastEpisodeDownload()
|
||||
newPeDl.setData(newPe, libraryItem, isAutoDownload)
|
||||
const newPeDl = new PodcastEpisodeDownload()
|
||||
newPeDl.setData(newPe, libraryItem, isAutoDownload, libraryItem.libraryId)
|
||||
this.startPodcastEpisodeDownload(newPeDl)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async startPodcastEpisodeDownload(podcastEpisodeDownload) {
|
||||
SocketAuthority.emitter('episode_download_queue_updated', this.getDownloadQueueDetails())
|
||||
if (this.currentDownload) {
|
||||
this.downloadQueue.push(podcastEpisodeDownload)
|
||||
SocketAuthority.emitter('episode_download_queued', podcastEpisodeDownload.toJSONForClient())
|
||||
return
|
||||
}
|
||||
|
||||
const task = new Task()
|
||||
const taskDescription = `Downloading episode "${podcastEpisodeDownload.podcastEpisode.title}".`
|
||||
const taskData = {
|
||||
libraryId: podcastEpisodeDownload.libraryId,
|
||||
libraryItemId: podcastEpisodeDownload.libraryItemId,
|
||||
}
|
||||
task.setData('download-podcast-episode', 'Downloading Episode', taskDescription, false, taskData)
|
||||
this.taskManager.addTask(task)
|
||||
|
||||
SocketAuthority.emitter('episode_download_started', podcastEpisodeDownload.toJSONForClient())
|
||||
this.currentDownload = podcastEpisodeDownload
|
||||
|
||||
// If this file already exists then append the episode id to the filename
|
||||
// e.g. "/tagesschau 20 Uhr.mp3" becomes "/tagesschau 20 Uhr (ep_asdfasdf).mp3"
|
||||
// this handles podcasts where every title is the same (ref https://github.com/advplyr/audiobookshelf/issues/1802)
|
||||
if (await fs.pathExists(this.currentDownload.targetPath)) {
|
||||
this.currentDownload.appendEpisodeId = true
|
||||
}
|
||||
|
||||
// Ignores all added files to this dir
|
||||
this.watcher.addIgnoreDir(this.currentDownload.libraryItem.path)
|
||||
|
||||
|
|
@ -81,24 +102,41 @@ class PodcastManager {
|
|||
await filePerms.setDefault(this.currentDownload.libraryItem.path)
|
||||
}
|
||||
|
||||
var success = await downloadFile(this.currentDownload.url, this.currentDownload.targetPath).then(() => true).catch((error) => {
|
||||
Logger.error(`[PodcastManager] Podcast Episode download failed`, error)
|
||||
return false
|
||||
})
|
||||
let success = false
|
||||
if (this.currentDownload.urlFileExtension === 'mp3') {
|
||||
// Download episode and tag it
|
||||
success = await ffmpegHelpers.downloadPodcastEpisode(this.currentDownload).catch((error) => {
|
||||
Logger.error(`[PodcastManager] Podcast Episode download failed`, error)
|
||||
return false
|
||||
})
|
||||
} else {
|
||||
// Download episode only
|
||||
success = await downloadFile(this.currentDownload.url, this.currentDownload.targetPath).then(() => true).catch((error) => {
|
||||
Logger.error(`[PodcastManager] Podcast Episode download failed`, error)
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
if (success) {
|
||||
success = await this.scanAddPodcastEpisodeAudioFile()
|
||||
if (!success) {
|
||||
await fs.remove(this.currentDownload.targetPath)
|
||||
this.currentDownload.setFinished(false)
|
||||
task.setFailed('Failed to download episode')
|
||||
} else {
|
||||
Logger.info(`[PodcastManager] Successfully downloaded podcast episode "${this.currentDownload.podcastEpisode.title}"`)
|
||||
this.currentDownload.setFinished(true)
|
||||
task.setFinished()
|
||||
}
|
||||
} else {
|
||||
task.setFailed('Failed to download episode')
|
||||
this.currentDownload.setFinished(false)
|
||||
}
|
||||
|
||||
this.taskManager.taskFinished(task)
|
||||
|
||||
SocketAuthority.emitter('episode_download_finished', this.currentDownload.toJSONForClient())
|
||||
SocketAuthority.emitter('episode_download_queue_updated', this.getDownloadQueueDetails())
|
||||
|
||||
this.watcher.removeIgnoreDir(this.currentDownload.libraryItem.path)
|
||||
this.currentDownload = null
|
||||
|
|
@ -108,23 +146,26 @@ class PodcastManager {
|
|||
}
|
||||
|
||||
async scanAddPodcastEpisodeAudioFile() {
|
||||
var libraryFile = await this.getLibraryFile(this.currentDownload.targetPath, this.currentDownload.targetRelPath)
|
||||
const libraryFile = await this.getLibraryFile(this.currentDownload.targetPath, this.currentDownload.targetRelPath)
|
||||
|
||||
// TODO: Set meta tags on new audio file
|
||||
|
||||
var audioFile = await this.probeAudioFile(libraryFile)
|
||||
const audioFile = await this.probeAudioFile(libraryFile)
|
||||
if (!audioFile) {
|
||||
return false
|
||||
}
|
||||
|
||||
var libraryItem = this.db.libraryItems.find(li => li.id === this.currentDownload.libraryItem.id)
|
||||
const libraryItem = this.db.libraryItems.find(li => li.id === this.currentDownload.libraryItem.id)
|
||||
if (!libraryItem) {
|
||||
Logger.error(`[PodcastManager] Podcast Episode finished but library item was not found ${this.currentDownload.libraryItem.id}`)
|
||||
return false
|
||||
}
|
||||
|
||||
var podcastEpisode = this.currentDownload.podcastEpisode
|
||||
const podcastEpisode = this.currentDownload.podcastEpisode
|
||||
podcastEpisode.audioFile = audioFile
|
||||
|
||||
if (audioFile.chapters?.length) {
|
||||
podcastEpisode.chapters = audioFile.chapters.map(ch => ({ ...ch }))
|
||||
}
|
||||
|
||||
libraryItem.media.addPodcastEpisode(podcastEpisode)
|
||||
if (libraryItem.isInvalid) {
|
||||
// First episode added to an empty podcast
|
||||
|
|
@ -143,6 +184,9 @@ class PodcastManager {
|
|||
libraryItem.updatedAt = Date.now()
|
||||
await this.db.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
const podcastEpisodeExpanded = podcastEpisode.toJSONExpanded()
|
||||
podcastEpisodeExpanded.libraryItem = libraryItem.toJSONExpanded()
|
||||
SocketAuthority.emitter('episode_added', podcastEpisodeExpanded)
|
||||
|
||||
if (this.currentDownload.isAutoDownload) { // Notifications only for auto downloaded episodes
|
||||
this.notificationManager.onPodcastEpisodeDownloaded(libraryItem, podcastEpisode)
|
||||
|
|
@ -183,13 +227,13 @@ class PodcastManager {
|
|||
}
|
||||
|
||||
async probeAudioFile(libraryFile) {
|
||||
var path = libraryFile.metadata.path
|
||||
var mediaProbeData = await prober.probe(path)
|
||||
const path = libraryFile.metadata.path
|
||||
const mediaProbeData = await prober.probe(path)
|
||||
if (mediaProbeData.error) {
|
||||
Logger.error(`[PodcastManager] Podcast Episode downloaded but failed to probe "${path}"`, mediaProbeData.error)
|
||||
return false
|
||||
}
|
||||
var newAudioFile = new AudioFile()
|
||||
const newAudioFile = new AudioFile()
|
||||
newAudioFile.setDataFromProbe(libraryFile, mediaProbeData)
|
||||
return newAudioFile
|
||||
}
|
||||
|
|
@ -329,5 +373,19 @@ class PodcastManager {
|
|||
feeds: rssFeedData
|
||||
}
|
||||
}
|
||||
|
||||
generateOPMLFileText(libraryItems) {
|
||||
return opmlGenerator.generate(libraryItems)
|
||||
}
|
||||
|
||||
getDownloadQueueDetails(libraryId = null) {
|
||||
let _currentDownload = this.currentDownload
|
||||
if (libraryId && _currentDownload?.libraryId !== libraryId) _currentDownload = null
|
||||
|
||||
return {
|
||||
currentDownload: _currentDownload?.toJSONForClient(),
|
||||
queue: this.downloadQueue.filter(item => !libraryId || item.libraryId === libraryId).map(item => item.toJSONForClient())
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports = PodcastManager
|
||||
module.exports = PodcastManager
|
||||
|
|
|
|||
|
|
@ -188,9 +188,12 @@ class RssFeedManager {
|
|||
async openFeedForItem(user, libraryItem, options) {
|
||||
const serverAddress = options.serverAddress
|
||||
const slug = options.slug
|
||||
const preventIndexing = options.metadataDetails?.preventIndexing ?? true
|
||||
const ownerName = options.metadataDetails?.ownerName
|
||||
const ownerEmail = options.metadataDetails?.ownerEmail
|
||||
|
||||
const feed = new Feed()
|
||||
feed.setFromItem(user.id, slug, libraryItem, serverAddress)
|
||||
feed.setFromItem(user.id, slug, libraryItem, serverAddress, preventIndexing, ownerName, ownerEmail)
|
||||
this.feeds[feed.id] = feed
|
||||
|
||||
Logger.debug(`[RssFeedManager] Opened RSS feed "${feed.feedUrl}"`)
|
||||
|
|
@ -202,9 +205,12 @@ class RssFeedManager {
|
|||
async openFeedForCollection(user, collectionExpanded, options) {
|
||||
const serverAddress = options.serverAddress
|
||||
const slug = options.slug
|
||||
const preventIndexing = options.metadataDetails?.preventIndexing ?? true
|
||||
const ownerName = options.metadataDetails?.ownerName
|
||||
const ownerEmail = options.metadataDetails?.ownerEmail
|
||||
|
||||
const feed = new Feed()
|
||||
feed.setFromCollection(user.id, slug, collectionExpanded, serverAddress)
|
||||
feed.setFromCollection(user.id, slug, collectionExpanded, serverAddress, preventIndexing, ownerName, ownerEmail)
|
||||
this.feeds[feed.id] = feed
|
||||
|
||||
Logger.debug(`[RssFeedManager] Opened RSS feed "${feed.feedUrl}"`)
|
||||
|
|
@ -216,9 +222,12 @@ class RssFeedManager {
|
|||
async openFeedForSeries(user, seriesExpanded, options) {
|
||||
const serverAddress = options.serverAddress
|
||||
const slug = options.slug
|
||||
const preventIndexing = options.metadataDetails?.preventIndexing ?? true
|
||||
const ownerName = options.metadataDetails?.ownerName
|
||||
const ownerEmail = options.metadataDetails?.ownerEmail
|
||||
|
||||
const feed = new Feed()
|
||||
feed.setFromSeries(user.id, slug, seriesExpanded, serverAddress)
|
||||
feed.setFromSeries(user.id, slug, seriesExpanded, serverAddress, preventIndexing, ownerName, ownerEmail)
|
||||
this.feeds[feed.id] = feed
|
||||
|
||||
Logger.debug(`[RssFeedManager] Opened RSS feed "${feed.feedUrl}"`)
|
||||
|
|
@ -246,4 +255,4 @@ class RssFeedManager {
|
|||
return this.handleCloseFeed(feed)
|
||||
}
|
||||
}
|
||||
module.exports = RssFeedManager
|
||||
module.exports = RssFeedManager
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue