1 import { move, pathExists, readdir, remove } from 'fs-extra'
2 import { dirname, join } from 'path'
3 import { CONFIG } from '@server/initializers/config'
4 import { isVideoFileExtnameValid } from '../custom-validators/videos'
5 import { logger, loggerTagsFactory } from '../logger'
6 import { generateVideoImportTmpPath } from '../utils'
7 import { YoutubeDLCLI } from './youtube-dl-cli'
8 import { YoutubeDLInfo, YoutubeDLInfoBuilder } from './youtube-dl-info-builder'
10 const lTags = loggerTagsFactory('youtube-dl')
12 export type YoutubeDLSubs = {
18 const processOptions = {
19 maxBuffer: 1024 * 1024 * 30 // 30MB
22 class YoutubeDLWrapper {
24 constructor (private readonly url: string = '', private readonly enabledResolutions: number[] = []) {
28 async getInfoForDownload (youtubeDLArgs: string[] = []): Promise<YoutubeDLInfo> {
29 const youtubeDL = await YoutubeDLCLI.safeGet()
31 const info = await youtubeDL.getInfo({
33 format: YoutubeDLCLI.getYoutubeDLVideoFormat(this.enabledResolutions),
34 additionalYoutubeDLArgs: youtubeDLArgs,
38 if (info.is_live === true) throw new Error('Cannot download a live streaming.')
40 const infoBuilder = new YoutubeDLInfoBuilder(info)
42 return infoBuilder.getInfo()
45 async getSubtitles (): Promise<YoutubeDLSubs> {
46 const cwd = CONFIG.STORAGE.TMP_DIR
48 const youtubeDL = await YoutubeDLCLI.safeGet()
50 const files = await youtubeDL.getSubs({ url: this.url, format: 'vtt', processOptions: { cwd } })
53 logger.debug('Get subtitles from youtube dl.', { url: this.url, files, ...lTags() })
55 const subtitles = files.reduce((acc, filename) => {
56 const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i)
57 if (!matched || !matched[1]) return acc
63 path: join(cwd, filename),
72 async downloadVideo (fileExt: string, timeout: number): Promise<string> {
73 // Leave empty the extension, youtube-dl will add it
74 const pathWithoutExtension = generateVideoImportTmpPath(this.url, '')
76 logger.info('Importing youtubeDL video %s to %s', this.url, pathWithoutExtension, lTags())
78 const youtubeDL = await YoutubeDLCLI.safeGet()
81 await youtubeDL.download({
83 format: YoutubeDLCLI.getYoutubeDLVideoFormat(this.enabledResolutions),
84 output: pathWithoutExtension,
89 // If youtube-dl did not guess an extension for our file, just use .mp4 as default
90 if (await pathExists(pathWithoutExtension)) {
91 await move(pathWithoutExtension, pathWithoutExtension + '.mp4')
94 return this.guessVideoPathWithExtension(pathWithoutExtension, fileExt)
96 this.guessVideoPathWithExtension(pathWithoutExtension, fileExt)
98 logger.debug('Error in youtube-dl import, deleting file %s.', path, { err, ...lTags() })
102 .catch(innerErr => logger.error('Cannot remove file in youtubeDL timeout.', { innerErr, ...lTags() }))
108 private async guessVideoPathWithExtension (tmpPath: string, sourceExt: string) {
109 if (!isVideoFileExtnameValid(sourceExt)) {
110 throw new Error('Invalid video extension ' + sourceExt)
113 const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ]
115 for (const extension of extensions) {
116 const path = tmpPath + extension
118 if (await pathExists(path)) return path
121 const directoryContent = await readdir(dirname(tmpPath))
123 throw new Error(`Cannot guess path of ${tmpPath}. Directory content: ${directoryContent.join(', ')}`)
127 // ---------------------------------------------------------------------------