2021-09-04 21:17:26 +02:00
|
|
|
const Path = require('path')
|
|
|
|
const fs = require('fs-extra')
|
2021-09-15 03:45:00 +02:00
|
|
|
const archiver = require('archiver')
|
2021-09-04 21:17:26 +02:00
|
|
|
|
|
|
|
const workerThreads = require('worker_threads')
|
|
|
|
const Logger = require('./Logger')
|
|
|
|
const Download = require('./objects/Download')
|
2021-11-16 03:09:42 +01:00
|
|
|
const { getId } = require('./utils/index')
|
2021-09-08 16:15:54 +02:00
|
|
|
const { writeConcatFile, writeMetadataFile } = require('./utils/ffmpegHelpers')
|
2021-09-04 21:17:26 +02:00
|
|
|
const { getFileSize } = require('./utils/fileUtils')
|
2021-09-25 17:35:33 +02:00
|
|
|
const TAG = 'DownloadManager'
|
2021-09-04 21:17:26 +02:00
|
|
|
class DownloadManager {
|
2021-09-15 03:45:00 +02:00
|
|
|
constructor(db, MetadataPath, AudiobookPath, emitter) {
|
2021-09-04 21:17:26 +02:00
|
|
|
this.db = db
|
|
|
|
this.MetadataPath = MetadataPath
|
2021-09-15 03:45:00 +02:00
|
|
|
this.AudiobookPath = AudiobookPath
|
2021-09-04 21:17:26 +02:00
|
|
|
this.emitter = emitter
|
|
|
|
|
|
|
|
this.downloadDirPath = Path.join(this.MetadataPath, 'downloads')
|
|
|
|
|
|
|
|
this.pendingDownloads = []
|
|
|
|
this.downloads = []
|
|
|
|
}
|
|
|
|
|
|
|
|
getDownload(downloadId) {
|
|
|
|
return this.downloads.find(d => d.id === downloadId)
|
|
|
|
}
|
|
|
|
|
|
|
|
async removeOrphanDownloads() {
|
|
|
|
try {
|
|
|
|
var dirs = await fs.readdir(this.downloadDirPath)
|
|
|
|
if (!dirs || !dirs.length) return true
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
downloadSocketRequest(socket, payload) {
|
|
|
|
var client = socket.sheepClient
|
|
|
|
var audiobook = this.db.audiobooks.find(a => a.id === payload.audiobookId)
|
|
|
|
var options = {
|
|
|
|
...payload
|
|
|
|
}
|
|
|
|
delete options.audiobookId
|
|
|
|
this.prepareDownload(client, audiobook, options)
|
|
|
|
}
|
|
|
|
|
2021-09-12 23:10:12 +02:00
|
|
|
removeSocketRequest(socket, downloadId) {
|
|
|
|
var download = this.downloads.find(d => d.id === downloadId)
|
|
|
|
if (!download) {
|
|
|
|
Logger.error('Remove download request download not found ' + downloadId)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
this.removeDownload(download)
|
|
|
|
}
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
async prepareDownload(client, audiobook, options = {}) {
|
2021-11-16 03:09:42 +01:00
|
|
|
var downloadId = getId('dl')
|
2021-09-04 21:17:26 +02:00
|
|
|
var dlpath = Path.join(this.downloadDirPath, downloadId)
|
|
|
|
Logger.info(`Start Download for ${audiobook.id} - DownloadId: ${downloadId} - ${dlpath}`)
|
|
|
|
|
|
|
|
await fs.ensureDir(dlpath)
|
|
|
|
|
|
|
|
var downloadType = options.type || 'singleAudio'
|
|
|
|
delete options.type
|
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
var fileext = null
|
|
|
|
var audiobookDirname = Path.basename(audiobook.path)
|
|
|
|
|
|
|
|
if (downloadType === 'singleAudio') {
|
2021-09-09 12:10:55 +02:00
|
|
|
var audioFileType = options.audioFileType || '.m4b'
|
2021-09-04 21:17:26 +02:00
|
|
|
delete options.audioFileType
|
2021-09-09 12:10:55 +02:00
|
|
|
if (audioFileType === 'same') {
|
|
|
|
var firstTrack = audiobook.tracks[0]
|
|
|
|
audioFileType = firstTrack.ext
|
|
|
|
}
|
|
|
|
fileext = audioFileType
|
2021-09-15 03:45:00 +02:00
|
|
|
} else if (downloadType === 'zip') {
|
|
|
|
fileext = '.zip'
|
2021-09-04 21:17:26 +02:00
|
|
|
}
|
2021-09-15 03:45:00 +02:00
|
|
|
var filename = audiobookDirname + fileext
|
2021-09-04 21:17:26 +02:00
|
|
|
var downloadData = {
|
|
|
|
id: downloadId,
|
|
|
|
audiobookId: audiobook.id,
|
|
|
|
type: downloadType,
|
|
|
|
options: options,
|
|
|
|
dirpath: dlpath,
|
2021-09-15 03:45:00 +02:00
|
|
|
fullPath: Path.join(dlpath, filename),
|
2021-09-04 21:17:26 +02:00
|
|
|
filename,
|
|
|
|
ext: fileext,
|
|
|
|
userId: (client && client.user) ? client.user.id : null,
|
|
|
|
socket: (client && client.socket) ? client.socket : null
|
|
|
|
}
|
|
|
|
var download = new Download()
|
|
|
|
download.setData(downloadData)
|
2021-09-15 03:45:00 +02:00
|
|
|
download.setTimeoutTimer(this.downloadTimedOut.bind(this))
|
2021-09-04 21:17:26 +02:00
|
|
|
|
|
|
|
if (downloadData.socket) {
|
|
|
|
downloadData.socket.emit('download_started', download.toJSON())
|
|
|
|
}
|
|
|
|
|
|
|
|
if (download.type === 'singleAudio') {
|
|
|
|
this.processSingleAudioDownload(audiobook, download)
|
2021-09-15 03:45:00 +02:00
|
|
|
} else if (download.type === 'zip') {
|
|
|
|
this.processZipDownload(audiobook, download)
|
2021-09-04 21:17:26 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
async processZipDownload(audiobook, download) {
|
|
|
|
this.pendingDownloads.push({
|
|
|
|
id: download.id,
|
|
|
|
download
|
|
|
|
})
|
|
|
|
Logger.info(`[DownloadManager] Processing Zip download ${download.fullPath}`)
|
|
|
|
var success = await this.zipAudiobookDir(audiobook.fullPath, download.fullPath).then(() => {
|
|
|
|
return true
|
|
|
|
}).catch((error) => {
|
|
|
|
Logger.error('[DownloadManager] Process Zip Failed', error)
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
this.sendResult(download, { success })
|
|
|
|
}
|
|
|
|
|
|
|
|
zipAudiobookDir(audiobookPath, downloadPath) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
// create a file to stream archive data to
|
|
|
|
const output = fs.createWriteStream(downloadPath)
|
|
|
|
const archive = archiver('zip', {
|
|
|
|
zlib: { level: 9 } // Sets the compression level.
|
|
|
|
})
|
|
|
|
|
|
|
|
// listen for all archive data to be written
|
|
|
|
// 'close' event is fired only when a file descriptor is involved
|
|
|
|
output.on('close', () => {
|
|
|
|
Logger.info(archive.pointer() + ' total bytes')
|
|
|
|
Logger.debug('archiver has been finalized and the output file descriptor has closed.')
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
|
|
|
|
// This event is fired when the data source is drained no matter what was the data source.
|
|
|
|
// It is not part of this library but rather from the NodeJS Stream API.
|
|
|
|
// @see: https://nodejs.org/api/stream.html#stream_event_end
|
|
|
|
output.on('end', () => {
|
|
|
|
Logger.debug('Data has been drained')
|
|
|
|
})
|
|
|
|
|
|
|
|
// good practice to catch warnings (ie stat failures and other non-blocking errors)
|
|
|
|
archive.on('warning', function (err) {
|
|
|
|
if (err.code === 'ENOENT') {
|
|
|
|
// log warning
|
|
|
|
Logger.warn(`[DownloadManager] Archiver warning: ${err.message}`)
|
|
|
|
} else {
|
|
|
|
// throw error
|
|
|
|
Logger.error(`[DownloadManager] Archiver error: ${err.message}`)
|
|
|
|
// throw err
|
|
|
|
reject(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
archive.on('error', function (err) {
|
|
|
|
Logger.error(`[DownloadManager] Archiver error: ${err.message}`)
|
|
|
|
reject(err)
|
|
|
|
})
|
|
|
|
|
|
|
|
// pipe archive data to the file
|
|
|
|
archive.pipe(output)
|
|
|
|
|
|
|
|
archive.directory(audiobookPath, false)
|
|
|
|
|
|
|
|
archive.finalize()
|
|
|
|
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
async processSingleAudioDownload(audiobook, download) {
|
2021-09-09 12:10:55 +02:00
|
|
|
|
|
|
|
// If changing audio file type then encoding is needed
|
2021-09-15 03:45:00 +02:00
|
|
|
var audioRequiresEncode = audiobook.tracks[0].ext !== download.ext
|
|
|
|
var shouldIncludeCover = download.includeCover && audiobook.book.cover
|
|
|
|
var firstTrackIsM4b = audiobook.tracks[0].ext.toLowerCase() === '.m4b'
|
|
|
|
var isOneTrack = audiobook.tracks.length === 1
|
2021-09-09 12:10:55 +02:00
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
const ffmpegInputs = []
|
2021-09-04 21:17:26 +02:00
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
if (!isOneTrack) {
|
|
|
|
var concatFilePath = Path.join(download.dirpath, 'files.txt')
|
|
|
|
await writeConcatFile(audiobook.tracks, concatFilePath)
|
|
|
|
ffmpegInputs.push({
|
2021-09-08 16:15:54 +02:00
|
|
|
input: concatFilePath,
|
|
|
|
options: ['-safe 0', '-f concat']
|
2021-09-15 03:45:00 +02:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
ffmpegInputs.push({
|
|
|
|
input: audiobook.tracks[0].fullPath,
|
|
|
|
options: firstTrackIsM4b ? ['-f mp4'] : []
|
|
|
|
})
|
|
|
|
}
|
2021-09-08 16:15:54 +02:00
|
|
|
|
|
|
|
const logLevel = process.env.NODE_ENV === 'production' ? 'error' : 'warning'
|
2021-09-09 12:10:55 +02:00
|
|
|
var ffmpegOptions = [`-loglevel ${logLevel}`]
|
2021-09-12 02:59:48 +02:00
|
|
|
var ffmpegOutputOptions = []
|
2021-09-09 12:10:55 +02:00
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
if (audioRequiresEncode) {
|
2021-09-09 12:10:55 +02:00
|
|
|
ffmpegOptions = ffmpegOptions.concat([
|
|
|
|
'-map 0:a',
|
|
|
|
'-acodec aac',
|
|
|
|
'-ac 2',
|
|
|
|
'-b:a 64k',
|
|
|
|
'-id3v2_version 3'
|
|
|
|
])
|
|
|
|
} else {
|
2021-09-15 03:45:00 +02:00
|
|
|
ffmpegOptions.push('-max_muxing_queue_size 1000')
|
|
|
|
|
|
|
|
if (isOneTrack && firstTrackIsM4b && !shouldIncludeCover) {
|
|
|
|
ffmpegOptions.push('-c copy')
|
|
|
|
} else {
|
|
|
|
ffmpegOptions.push('-c:a copy')
|
2021-09-12 02:59:48 +02:00
|
|
|
}
|
2021-09-09 12:10:55 +02:00
|
|
|
}
|
2021-09-15 03:45:00 +02:00
|
|
|
if (download.ext === '.m4b') {
|
|
|
|
Logger.info('Concat m4b\'s use -f mp4')
|
|
|
|
ffmpegOutputOptions.push('-f mp4')
|
|
|
|
}
|
2021-09-09 12:10:55 +02:00
|
|
|
|
|
|
|
if (download.includeMetadata) {
|
|
|
|
var metadataFilePath = Path.join(download.dirpath, 'metadata.txt')
|
|
|
|
await writeMetadataFile(audiobook, metadataFilePath)
|
|
|
|
|
|
|
|
ffmpegInputs.push({
|
|
|
|
input: metadataFilePath
|
|
|
|
})
|
|
|
|
|
|
|
|
ffmpegOptions.push('-map_metadata 1')
|
|
|
|
}
|
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
if (shouldIncludeCover) {
|
2021-11-06 23:26:44 +01:00
|
|
|
var _cover = audiobook.book.coverFullPath.replace(/\\/g, '/')
|
2021-10-16 03:31:00 +02:00
|
|
|
|
|
|
|
// Supporting old local file prefix
|
2021-11-06 23:26:44 +01:00
|
|
|
var bookCoverPath = audiobook.book.cover ? audiobook.book.cover.replace(/\\/g, '/') : null
|
|
|
|
if (!_cover && bookCoverPath && bookCoverPath.startsWith('/local')) {
|
|
|
|
_cover = Path.posix.join(this.AudiobookPath.replace(/\\/g, '/'), _cover.replace('/local', ''))
|
2021-09-15 03:45:00 +02:00
|
|
|
Logger.debug('Local cover url', _cover)
|
|
|
|
}
|
2021-10-16 03:31:00 +02:00
|
|
|
|
2021-09-08 16:15:54 +02:00
|
|
|
ffmpegInputs.push({
|
2021-09-15 03:45:00 +02:00
|
|
|
input: _cover,
|
2021-09-08 16:15:54 +02:00
|
|
|
options: ['-f image2pipe']
|
|
|
|
})
|
|
|
|
ffmpegOptions.push('-vf [2:v]crop=trunc(iw/2)*2:trunc(ih/2)*2')
|
|
|
|
ffmpegOptions.push('-map 2:v')
|
|
|
|
}
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
var workerData = {
|
2021-09-08 16:15:54 +02:00
|
|
|
inputs: ffmpegInputs,
|
|
|
|
options: ffmpegOptions,
|
2021-09-12 02:59:48 +02:00
|
|
|
outputOptions: ffmpegOutputOptions,
|
2021-09-08 16:15:54 +02:00
|
|
|
output: download.fullPath,
|
2021-09-04 21:17:26 +02:00
|
|
|
}
|
2021-09-08 16:15:54 +02:00
|
|
|
|
2021-09-25 17:35:33 +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(`[${TAG}] Start worker thread failed`, error)
|
|
|
|
if (download.socket) {
|
|
|
|
var downloadJson = download.toJSON()
|
|
|
|
download.socket.emit('download_failed', downloadJson)
|
|
|
|
}
|
|
|
|
this.removeDownload(download)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
worker.on('message', (message) => {
|
|
|
|
if (message != null && typeof message === 'object') {
|
|
|
|
if (message.type === 'RESULT') {
|
2021-09-15 03:45:00 +02:00
|
|
|
if (!download.isTimedOut) {
|
|
|
|
this.sendResult(download, message)
|
|
|
|
}
|
2021-11-10 03:30:44 +01:00
|
|
|
} else if (message.type === 'FFMPEG') {
|
|
|
|
if (Logger[message.level]) {
|
|
|
|
Logger[message.level](message.log)
|
|
|
|
}
|
2021-09-04 21:17:26 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Logger.error('Invalid worker message', message)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
this.pendingDownloads.push({
|
|
|
|
id: download.id,
|
|
|
|
download,
|
|
|
|
worker
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
async downloadTimedOut(download) {
|
|
|
|
Logger.info(`[DownloadManager] Download ${download.id} timed out (${download.timeoutTimeMs}ms)`)
|
|
|
|
|
|
|
|
if (download.socket) {
|
|
|
|
var downloadJson = download.toJSON()
|
|
|
|
downloadJson.isTimedOut = true
|
|
|
|
download.socket.emit('download_failed', downloadJson)
|
|
|
|
}
|
|
|
|
this.removeDownload(download)
|
|
|
|
}
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
async downloadExpired(download) {
|
|
|
|
Logger.info(`[DownloadManager] Download ${download.id} expired`)
|
|
|
|
|
|
|
|
if (download.socket) {
|
|
|
|
download.socket.emit('download_expired', download.toJSON())
|
|
|
|
}
|
|
|
|
this.removeDownload(download)
|
|
|
|
}
|
|
|
|
|
|
|
|
async sendResult(download, result) {
|
2021-09-15 03:45:00 +02:00
|
|
|
download.clearTimeoutTimer()
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
// Remove pending download
|
|
|
|
this.pendingDownloads = this.pendingDownloads.filter(d => d.id !== download.id)
|
|
|
|
|
|
|
|
if (result.isKilled) {
|
|
|
|
if (download.socket) {
|
|
|
|
download.socket.emit('download_killed', download.toJSON())
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!result.success) {
|
|
|
|
if (download.socket) {
|
|
|
|
download.socket.emit('download_failed', download.toJSON())
|
|
|
|
}
|
|
|
|
this.removeDownload(download)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
var filesize = await getFileSize(download.fullPath)
|
|
|
|
download.setComplete(filesize)
|
2021-09-04 21:17:26 +02:00
|
|
|
if (download.socket) {
|
|
|
|
download.socket.emit('download_ready', download.toJSON())
|
|
|
|
}
|
|
|
|
download.setExpirationTimer(this.downloadExpired.bind(this))
|
|
|
|
|
|
|
|
this.downloads.push(download)
|
|
|
|
Logger.info(`[DownloadManager] Download Ready ${download.id}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
async removeDownload(download) {
|
|
|
|
Logger.info('[DownloadManager] Removing download ' + download.id)
|
|
|
|
|
2021-09-15 03:45:00 +02:00
|
|
|
download.clearTimeoutTimer()
|
|
|
|
download.clearExpirationTimer()
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
var pendingDl = this.pendingDownloads.find(d => d.id === download.id)
|
|
|
|
|
|
|
|
if (pendingDl) {
|
|
|
|
this.pendingDownloads = this.pendingDownloads.filter(d => d.id !== download.id)
|
|
|
|
Logger.warn(`[DownloadManager] Removing download in progress - stopping worker`)
|
2021-09-15 03:45:00 +02:00
|
|
|
if (pendingDl.worker) {
|
|
|
|
try {
|
|
|
|
pendingDl.worker.postMessage('STOP')
|
|
|
|
} catch (error) {
|
|
|
|
Logger.error('[DownloadManager] Error posting stop message to worker', error)
|
|
|
|
}
|
2021-09-04 21:17:26 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
await fs.remove(download.dirpath).then(() => {
|
|
|
|
Logger.info('[DownloadManager] Deleted download', download.dirpath)
|
|
|
|
}).catch((err) => {
|
|
|
|
Logger.error('[DownloadManager] Failed to delete download', err)
|
|
|
|
})
|
|
|
|
this.downloads = this.downloads.filter(d => d.id !== download.id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = DownloadManager
|