1 import { move, pathExists, readdir, remove } from 'fs-extra'
2 import { dirname, join } from 'path'
3 import { inspect } from 'util'
4 import { CONFIG } from '@server/initializers/config'
5 import { isVideoFileExtnameValid } from '../custom-validators/videos'
6 import { logger, loggerTagsFactory } from '../logger'
7 import { generateVideoImportTmpPath } from '../utils'
8 import { YoutubeDLCLI } from './youtube-dl-cli'
9 import { YoutubeDLInfo, YoutubeDLInfoBuilder } from './youtube-dl-info-builder'
11 const lTags = loggerTagsFactory('youtube-dl')
13 export type YoutubeDLSubs = {
19 const processOptions = {
20 maxBuffer: 1024 * 1024 * 30 // 30MB
23 class YoutubeDLWrapper {
26 private readonly url: string,
27 private readonly enabledResolutions: number[],
28 private readonly useBestFormat: boolean
33 async getInfoForDownload (youtubeDLArgs: string[] = []): Promise<YoutubeDLInfo> {
34 const youtubeDL = await YoutubeDLCLI.safeGet()
36 const info = await youtubeDL.getInfo({
38 format: YoutubeDLCLI.getYoutubeDLVideoFormat(this.enabledResolutions, this.useBestFormat),
39 additionalYoutubeDLArgs: youtubeDLArgs,
43 if (!info) throw new Error(`YoutubeDL could not get info from ${this.url}`)
45 if (info.is_live === true) throw new Error('Cannot download a live streaming.')
47 const infoBuilder = new YoutubeDLInfoBuilder(info)
49 return infoBuilder.getInfo()
52 async getInfoForListImport (options: {
53 latestVideosCount?: number
55 const youtubeDL = await YoutubeDLCLI.safeGet()
57 const list = await youtubeDL.getListInfo({
59 latestVideosCount: options.latestVideosCount,
63 if (!Array.isArray(list)) throw new Error(`YoutubeDL could not get list info from ${this.url}: ${inspect(list)}`)
65 return list.map(info => info.webpage_url)
68 async getSubtitles (): Promise<YoutubeDLSubs> {
69 const cwd = CONFIG.STORAGE.TMP_DIR
71 const youtubeDL = await YoutubeDLCLI.safeGet()
73 const files = await youtubeDL.getSubs({ url: this.url, format: 'vtt', processOptions: { cwd } })
76 logger.debug('Get subtitles from youtube dl.', { url: this.url, files, ...lTags() })
78 const subtitles = files.reduce((acc, filename) => {
79 const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i)
80 if (!matched?.[1]) return acc
86 path: join(cwd, filename),
95 async downloadVideo (fileExt: string, timeout: number): Promise<string> {
96 // Leave empty the extension, youtube-dl will add it
97 const pathWithoutExtension = generateVideoImportTmpPath(this.url, '')
99 logger.info('Importing youtubeDL video %s to %s', this.url, pathWithoutExtension, lTags())
101 const youtubeDL = await YoutubeDLCLI.safeGet()
104 await youtubeDL.download({
106 format: YoutubeDLCLI.getYoutubeDLVideoFormat(this.enabledResolutions, this.useBestFormat),
107 output: pathWithoutExtension,
112 // If youtube-dl did not guess an extension for our file, just use .mp4 as default
113 if (await pathExists(pathWithoutExtension)) {
114 await move(pathWithoutExtension, pathWithoutExtension + '.mp4')
117 return this.guessVideoPathWithExtension(pathWithoutExtension, fileExt)
119 this.guessVideoPathWithExtension(pathWithoutExtension, fileExt)
121 logger.debug('Error in youtube-dl import, deleting file %s.', path, { err, ...lTags() })
125 .catch(innerErr => logger.error('Cannot remove file in youtubeDL error.', { innerErr, ...lTags() }))
131 private async guessVideoPathWithExtension (tmpPath: string, sourceExt: string) {
132 if (!isVideoFileExtnameValid(sourceExt)) {
133 throw new Error('Invalid video extension ' + sourceExt)
136 const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ]
138 for (const extension of extensions) {
139 const path = tmpPath + extension
141 if (await pathExists(path)) return path
144 const directoryContent = await readdir(dirname(tmpPath))
146 throw new Error(`Cannot guess path of ${tmpPath}. Directory content: ${directoryContent.join(', ')}`)
150 // ---------------------------------------------------------------------------