2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
const Path = require('path')
|
2022-07-06 02:53:01 +02:00
|
|
|
const fs = require('../libs/fsExtra')
|
2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
const workerThreads = require('worker_threads')
|
|
|
|
const Logger = require('../Logger')
|
2022-09-27 01:07:31 +02:00
|
|
|
const AbManagerTask = require('../objects/AbManagerTask')
|
2022-04-22 01:52:28 +02:00
|
|
|
const filePerms = require('../utils/filePerms')
|
|
|
|
const { getId } = require('../utils/index')
|
2022-09-27 01:07:31 +02:00
|
|
|
const { writeConcatFile } = require('../utils/ffmpegHelpers')
|
|
|
|
const toneHelpers = require('../utils/toneHelpers')
|
2022-04-22 01:52:28 +02:00
|
|
|
const { getFileSize } = require('../utils/fileUtils')
|
|
|
|
|
|
|
|
class AbMergeManager {
|
|
|
|
constructor(db, clientEmitter) {
|
|
|
|
this.db = db
|
|
|
|
this.clientEmitter = clientEmitter
|
|
|
|
|
|
|
|
this.downloadDirPath = Path.join(global.MetadataPath, 'downloads')
|
2022-06-07 03:51:08 +02:00
|
|
|
this.downloadDirPathExist = false
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
this.pendingTasks = []
|
|
|
|
this.tasks = []
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2022-06-07 03:51:08 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
getTask(taskId) {
|
|
|
|
return this.tasks.find(d => d.id === taskId)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
removeTaskById(taskId) {
|
|
|
|
var task = this.getTask(taskId)
|
|
|
|
if (task) {
|
|
|
|
this.removeTask(task)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async removeOrphanDownloads() {
|
|
|
|
try {
|
|
|
|
var dirs = await fs.readdir(this.downloadDirPath)
|
|
|
|
if (!dirs || !dirs.length) return true
|
|
|
|
|
|
|
|
dirs = dirs.filter(d => d.startsWith('abmerge'))
|
|
|
|
|
|
|
|
await Promise.all(dirs.map(async (dirname) => {
|
|
|
|
var fullPath = Path.join(this.downloadDirPath, dirname)
|
|
|
|
Logger.info(`Removing Orphan Download ${dirname}`)
|
|
|
|
return fs.remove(fullPath)
|
|
|
|
}))
|
|
|
|
return true
|
|
|
|
} catch (error) {
|
|
|
|
return false
|
|
|
|
}
|
2022-06-07 03:52:08 +02:00
|
|
|
}
|
2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
async startAudiobookMerge(user, libraryItem) {
|
2022-09-27 01:07:31 +02:00
|
|
|
var taskId = getId('abmerge')
|
|
|
|
var dlpath = Path.join(this.downloadDirPath, taskId)
|
|
|
|
Logger.info(`Start audiobook merge for ${libraryItem.id} - TaskId: ${taskId} - ${dlpath}`)
|
2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
var audiobookDirname = Path.basename(libraryItem.path)
|
|
|
|
var filename = audiobookDirname + '.m4b'
|
2022-09-27 01:07:31 +02:00
|
|
|
var taskData = {
|
|
|
|
id: taskId,
|
2022-04-22 01:52:28 +02:00
|
|
|
libraryItemId: libraryItem.id,
|
|
|
|
type: 'abmerge',
|
|
|
|
dirpath: dlpath,
|
|
|
|
path: Path.join(dlpath, filename),
|
|
|
|
filename,
|
|
|
|
ext: '.m4b',
|
2022-09-27 01:07:31 +02:00
|
|
|
userId: user.id,
|
|
|
|
libraryItemPath: libraryItem.path,
|
|
|
|
originalTrackPaths: libraryItem.media.tracks.map(t => t.metadata.path)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
var abManagerTask = new AbManagerTask()
|
|
|
|
abManagerTask.setData(taskData)
|
|
|
|
abManagerTask.setTimeoutTimer(this.downloadTimedOut.bind(this))
|
2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
try {
|
2022-09-27 01:07:31 +02:00
|
|
|
await fs.mkdir(abManagerTask.dirpath)
|
2022-04-22 01:52:28 +02:00
|
|
|
} catch (error) {
|
2022-09-27 01:07:31 +02:00
|
|
|
Logger.error(`[AbMergeManager] Failed to make directory ${abManagerTask.dirpath}`)
|
2022-06-06 17:12:58 +02:00
|
|
|
Logger.debug(`[AbMergeManager] Make directory error: ${error}`)
|
2022-09-27 01:07:31 +02:00
|
|
|
var taskJson = abManagerTask.toJSON()
|
|
|
|
this.clientEmitter(user.id, 'abmerge_failed', taskJson)
|
2022-04-22 01:52:28 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
this.clientEmitter(user.id, 'abmerge_started', abManagerTask.toJSON())
|
|
|
|
this.runAudiobookMerge(libraryItem, abManagerTask)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
async runAudiobookMerge(libraryItem, abManagerTask) {
|
2022-04-22 01:52:28 +02:00
|
|
|
// If changing audio file type then encoding is needed
|
|
|
|
var audioTracks = libraryItem.media.tracks
|
2022-09-27 01:07:31 +02:00
|
|
|
var audioRequiresEncode = audioTracks[0].metadata.ext !== abManagerTask.ext
|
2022-04-22 01:52:28 +02:00
|
|
|
var shouldIncludeCover = libraryItem.media.coverPath
|
|
|
|
var firstTrackIsM4b = audioTracks[0].metadata.ext.toLowerCase() === '.m4b'
|
|
|
|
var isOneTrack = audioTracks.length === 1
|
|
|
|
|
|
|
|
const ffmpegInputs = []
|
|
|
|
|
|
|
|
if (!isOneTrack) {
|
2022-09-27 01:07:31 +02:00
|
|
|
var concatFilePath = Path.join(abManagerTask.dirpath, 'files.txt')
|
2022-04-22 01:52:28 +02:00
|
|
|
console.log('Write files.txt', concatFilePath)
|
|
|
|
await writeConcatFile(audioTracks, concatFilePath)
|
|
|
|
ffmpegInputs.push({
|
|
|
|
input: concatFilePath,
|
|
|
|
options: ['-safe 0', '-f concat']
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
ffmpegInputs.push({
|
|
|
|
input: audioTracks[0].metadata.path,
|
|
|
|
options: firstTrackIsM4b ? ['-f mp4'] : []
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const logLevel = process.env.NODE_ENV === 'production' ? 'error' : 'warning'
|
|
|
|
var ffmpegOptions = [`-loglevel ${logLevel}`]
|
|
|
|
var ffmpegOutputOptions = []
|
|
|
|
|
|
|
|
if (audioRequiresEncode) {
|
|
|
|
ffmpegOptions = ffmpegOptions.concat([
|
|
|
|
'-map 0:a',
|
|
|
|
'-acodec aac',
|
|
|
|
'-ac 2',
|
2022-09-27 01:07:31 +02:00
|
|
|
'-b:a 64k'
|
|
|
|
// '-movflags use_metadata_tags'
|
2022-04-22 01:52:28 +02:00
|
|
|
])
|
|
|
|
} else {
|
|
|
|
ffmpegOptions.push('-max_muxing_queue_size 1000')
|
|
|
|
|
|
|
|
if (isOneTrack && firstTrackIsM4b && !shouldIncludeCover) {
|
|
|
|
ffmpegOptions.push('-c copy')
|
|
|
|
} else {
|
|
|
|
ffmpegOptions.push('-c:a copy')
|
|
|
|
}
|
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
if (abManagerTask.ext === '.m4b') {
|
2022-04-22 01:52:28 +02:00
|
|
|
ffmpegOutputOptions.push('-f mp4')
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
var chaptersFilePath = null
|
|
|
|
if (libraryItem.media.chapters.length) {
|
|
|
|
chaptersFilePath = Path.join(abManagerTask.dirpath, 'chapters.txt')
|
|
|
|
try {
|
|
|
|
await toneHelpers.writeToneChaptersFile(libraryItem.media.chapters, chaptersFilePath)
|
|
|
|
} catch (error) {
|
|
|
|
Logger.error(`[AbMergeManager] Write chapters.txt failed`, error)
|
|
|
|
chaptersFilePath = null
|
|
|
|
}
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
const toneMetadataObject = toneHelpers.getToneMetadataObject(libraryItem, chaptersFilePath)
|
|
|
|
toneMetadataObject.TrackNumber = 1
|
|
|
|
abManagerTask.toneMetadataObject = toneMetadataObject
|
|
|
|
|
|
|
|
Logger.debug(`[AbMergeManager] Book "${libraryItem.media.metadata.title}" tone metadata object=`, toneMetadataObject)
|
|
|
|
|
2022-04-22 01:52:28 +02:00
|
|
|
var workerData = {
|
|
|
|
inputs: ffmpegInputs,
|
|
|
|
options: ffmpegOptions,
|
|
|
|
outputOptions: ffmpegOutputOptions,
|
2022-09-27 01:07:31 +02:00
|
|
|
output: abManagerTask.path,
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var worker = null
|
|
|
|
try {
|
|
|
|
var workerPath = Path.join(global.appRoot, 'server/utils/downloadWorker.js')
|
|
|
|
worker = new workerThreads.Worker(workerPath, { workerData })
|
|
|
|
} catch (error) {
|
|
|
|
Logger.error(`[AbMergeManager] Start worker thread failed`, error)
|
2022-09-27 01:07:31 +02:00
|
|
|
if (abManagerTask.userId) {
|
|
|
|
var taskJson = abManagerTask.toJSON()
|
|
|
|
this.clientEmitter(abManagerTask.userId, 'abmerge_failed', taskJson)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
this.removeTask(abManagerTask)
|
2022-04-22 01:52:28 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
worker.on('message', (message) => {
|
|
|
|
if (message != null && typeof message === 'object') {
|
|
|
|
if (message.type === 'RESULT') {
|
2022-09-27 01:07:31 +02:00
|
|
|
if (!abManagerTask.isTimedOut) {
|
|
|
|
this.sendResult(abManagerTask, message)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
} else if (message.type === 'FFMPEG') {
|
|
|
|
if (Logger[message.level]) {
|
|
|
|
Logger[message.level](message.log)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Logger.error('Invalid worker message', message)
|
|
|
|
}
|
|
|
|
})
|
2022-09-27 01:07:31 +02:00
|
|
|
this.pendingTasks.push({
|
|
|
|
id: abManagerTask.id,
|
|
|
|
abManagerTask,
|
2022-04-22 01:52:28 +02:00
|
|
|
worker
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
async sendResult(abManagerTask, result) {
|
|
|
|
abManagerTask.clearTimeoutTimer()
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
// Remove pending task
|
|
|
|
this.pendingTasks = this.pendingTasks.filter(d => d.id !== abManagerTask.id)
|
2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
if (result.isKilled) {
|
2022-09-27 01:07:31 +02:00
|
|
|
if (abManagerTask.userId) {
|
|
|
|
this.clientEmitter(abManagerTask.userId, 'abmerge_killed', abManagerTask.toJSON())
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!result.success) {
|
2022-09-27 01:07:31 +02:00
|
|
|
if (abManagerTask.userId) {
|
|
|
|
this.clientEmitter(abManagerTask.userId, 'abmerge_failed', abManagerTask.toJSON())
|
|
|
|
}
|
|
|
|
this.removeTask(abManagerTask)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write metadata to merged file
|
|
|
|
const success = await toneHelpers.tagAudioFile(abManagerTask.path, abManagerTask.toneMetadataObject)
|
|
|
|
if (!success) {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to write metadata to file "${abManagerTask.path}"`)
|
|
|
|
if (abManagerTask.userId) {
|
|
|
|
this.clientEmitter(abManagerTask.userId, 'abmerge_failed', abManagerTask.toJSON())
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
this.removeTask(abManagerTask)
|
2022-04-22 01:52:28 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
// Move library item tracks to cache
|
|
|
|
const itemCacheDir = Path.join(global.MetadataPath, `cache/items/${abManagerTask.libraryItemId}`)
|
|
|
|
await fs.ensureDir(itemCacheDir)
|
|
|
|
for (const trackPath of abManagerTask.originalTrackPaths) {
|
|
|
|
const trackFilename = Path.basename(trackPath)
|
|
|
|
const moveToPath = Path.join(itemCacheDir, trackFilename)
|
|
|
|
Logger.debug(`[AbMergeManager] Backing up original track "${trackPath}" to ${moveToPath}`)
|
|
|
|
await fs.move(trackPath, moveToPath, { overwrite: true }).catch((err) => {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to move track "${trackPath}" to "${moveToPath}"`, err)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-04-22 01:52:28 +02:00
|
|
|
// Set file permissions and ownership
|
2022-09-27 01:07:31 +02:00
|
|
|
await filePerms.setDefault(abManagerTask.path)
|
|
|
|
await filePerms.setDefault(itemCacheDir)
|
|
|
|
|
|
|
|
// Move merged file to library item
|
|
|
|
const moveToPath = Path.join(abManagerTask.libraryItemPath, abManagerTask.filename)
|
|
|
|
Logger.debug(`[AbMergeManager] Moving merged audiobook to library item at "${moveToPath}"`)
|
|
|
|
const moveSuccess = await fs.move(abManagerTask.path, moveToPath, { overwrite: true }).then(() => true).catch((err) => {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to move merged audiobook from "${abManagerTask.path}" to "${moveToPath}"`, err)
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
if (!moveSuccess) {
|
|
|
|
// TODO: Revert cached og files?
|
|
|
|
}
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
var filesize = await getFileSize(abManagerTask.path)
|
|
|
|
abManagerTask.setComplete(filesize)
|
|
|
|
if (abManagerTask.userId) {
|
|
|
|
this.clientEmitter(abManagerTask.userId, 'abmerge_ready', abManagerTask.toJSON())
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
// abManagerTask.setExpirationTimer(this.downloadExpired.bind(this))
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
// this.tasks.push(abManagerTask)
|
|
|
|
await this.removeTask(abManagerTask)
|
|
|
|
Logger.info(`[AbMergeManager] Ab task finished ${abManagerTask.id}`)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
// async downloadExpired(abManagerTask) {
|
|
|
|
// Logger.info(`[AbMergeManager] Download ${abManagerTask.id} expired`)
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
// if (abManagerTask.userId) {
|
|
|
|
// this.clientEmitter(abManagerTask.userId, 'abmerge_expired', abManagerTask.toJSON())
|
|
|
|
// }
|
|
|
|
// this.removeTask(abManagerTask)
|
|
|
|
// }
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
async downloadTimedOut(abManagerTask) {
|
|
|
|
Logger.info(`[AbMergeManager] Download ${abManagerTask.id} timed out (${abManagerTask.timeoutTimeMs}ms)`)
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
if (abManagerTask.userId) {
|
|
|
|
var taskJson = abManagerTask.toJSON()
|
|
|
|
taskJson.isTimedOut = true
|
|
|
|
this.clientEmitter(abManagerTask.userId, 'abmerge_failed', taskJson)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
this.removeTask(abManagerTask)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
async removeTask(abManagerTask) {
|
|
|
|
Logger.info('[AbMergeManager] Removing task ' + abManagerTask.id)
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
abManagerTask.clearTimeoutTimer()
|
|
|
|
// abManagerTask.clearExpirationTimer()
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
var pendingDl = this.pendingTasks.find(d => d.id === abManagerTask.id)
|
2022-04-22 01:52:28 +02:00
|
|
|
|
|
|
|
if (pendingDl) {
|
2022-09-27 01:07:31 +02:00
|
|
|
this.pendingTasks = this.pendingTasks.filter(d => d.id !== abManagerTask.id)
|
2022-04-22 01:52:28 +02:00
|
|
|
Logger.warn(`[AbMergeManager] Removing download in progress - stopping worker`)
|
|
|
|
if (pendingDl.worker) {
|
|
|
|
try {
|
|
|
|
pendingDl.worker.postMessage('STOP')
|
|
|
|
} catch (error) {
|
|
|
|
Logger.error('[AbMergeManager] Error posting stop message to worker', error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
await fs.remove(abManagerTask.dirpath).then(() => {
|
|
|
|
Logger.info('[AbMergeManager] Deleted download', abManagerTask.dirpath)
|
2022-04-22 01:52:28 +02:00
|
|
|
}).catch((err) => {
|
|
|
|
Logger.error('[AbMergeManager] Failed to delete download', err)
|
|
|
|
})
|
2022-09-27 01:07:31 +02:00
|
|
|
this.tasks = this.tasks.filter(d => d.id !== abManagerTask.id)
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
}
|
2022-06-05 02:50:26 +02:00
|
|
|
module.exports = AbMergeManager
|