1 import { createWriteStream } from 'fs'
2 import { ensureDir, pathExists, remove, writeFile } from 'fs-extra'
3 import { join } from 'path'
4 import * as request from 'request'
5 import { CONFIG } from '@server/initializers/config'
6 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
7 import { VideoResolution } from '../../shared/models/videos'
8 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
9 import { getEnabledResolutions } from '../lib/video-transcoding'
10 import { peertubeTruncate, root } from './core-utils'
11 import { isVideoFileExtnameValid } from './custom-validators/videos'
12 import { logger } from './logger'
13 import { generateVideoImportTmpPath } from './utils'
15 export type YoutubeDLInfo = {
25 originallyPublishedAt?: Date
28 export type YoutubeDLSubs = {
34 const processOptions = {
35 maxBuffer: 1024 * 1024 * 10 // 10MB
38 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
39 return new Promise<YoutubeDLInfo>((res, rej) => {
40 let args = opts || [ '-j', '--flat-playlist' ]
42 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) {
43 args.push('--force-ipv4')
46 args = wrapWithProxyOptions(args)
47 args = [ '-f', getYoutubeDLVideoFormat() ].concat(args)
51 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
52 if (err) return rej(err)
53 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
55 const obj = buildVideoInfo(normalizeObject(info))
56 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
61 .catch(err => rej(err))
65 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
66 return new Promise<YoutubeDLSubs>((res, rej) => {
67 const cwd = CONFIG.STORAGE.TMP_DIR
68 const options = opts || { all: true, format: 'vtt', cwd }
72 youtubeDL.getSubs(url, options, (err, files) => {
73 if (err) return rej(err)
76 logger.debug('Get subtitles from youtube dl.', { url, files })
78 const subtitles = files.reduce((acc, filename) => {
79 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
80 if (!matched || !matched[1]) return acc
86 path: join(cwd, filename),
95 .catch(err => rej(err))
99 function getYoutubeDLVideoFormat () {
101 * list of format selectors in order or preference
102 * see https://github.com/ytdl-org/youtube-dl#format-selection
104 * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope
105 * of being able to do a "quick-transcode"
106 * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9)
107 * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback
109 * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499
111 const enabledResolutions = getEnabledResolutions('vod')
112 const resolution = enabledResolutions.length === 0
113 ? VideoResolution.H_720P
114 : Math.max(...enabledResolutions)
117 `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1
118 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2
119 `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]`, // case #3
120 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio`,
121 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats
122 'best' // Ultimate fallback
126 function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number) {
127 // Leave empty the extension, youtube-dl will add it
128 const pathWithoutExtension = generateVideoImportTmpPath(url, '')
132 logger.info('Importing youtubeDL video %s to %s', url, pathWithoutExtension)
134 let options = [ '-f', getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ]
135 options = wrapWithProxyOptions(options)
137 if (process.env.FFMPEG_PATH) {
138 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
141 logger.debug('YoutubeDL options for %s.', url, { options })
143 return new Promise<string>((res, rej) => {
146 youtubeDL.exec(url, options, processOptions, async err => {
150 const path = await guessVideoPathWithExtension(pathWithoutExtension, fileExt)
154 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
165 timer = setTimeout(() => {
166 const err = new Error('YoutubeDL download timeout.')
168 guessVideoPathWithExtension(pathWithoutExtension, fileExt)
169 .then(path => remove(path))
170 .finally(() => rej(err))
172 logger.error('Cannot remove file in youtubeDL timeout.', { err })
177 .catch(err => rej(err))
181 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
182 // We rewrote it to avoid sync calls
183 async function updateYoutubeDLBinary () {
184 logger.info('Updating youtubeDL binary.')
186 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
187 const bin = join(binDirectory, 'youtube-dl')
188 const detailsPath = join(binDirectory, 'details')
189 const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl'
191 await ensureDir(binDirectory)
193 return new Promise(res => {
194 request.get(url, { followRedirect: false }, (err, result) => {
196 logger.error('Cannot update youtube-dl.', { err })
200 if (result.statusCode !== HttpStatusCode.FOUND_302) {
201 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
205 const url = result.headers.location
206 const downloadFile = request.get(url)
207 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
209 downloadFile.on('response', result => {
210 if (result.statusCode !== HttpStatusCode.OK_200) {
211 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
215 const writeStream = createWriteStream(bin, { mode: 493 }).on('error', err => {
216 logger.error('youtube-dl update error in write stream', { err })
220 downloadFile.pipe(writeStream)
223 downloadFile.on('error', err => {
224 logger.error('youtube-dl update error.', { err })
228 downloadFile.on('end', () => {
229 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
230 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
232 logger.error('youtube-dl update error: cannot write details.', { err })
236 logger.info('youtube-dl updated to version %s.', newVersion)
244 async function safeGetYoutubeDL () {
248 youtubeDL = require('youtube-dl')
251 await updateYoutubeDLBinary()
252 youtubeDL = require('youtube-dl')
258 function buildOriginallyPublishedAt (obj: any) {
259 let originallyPublishedAt: Date = null
261 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
262 if (uploadDateMatcher) {
263 originallyPublishedAt = new Date()
264 originallyPublishedAt.setHours(0, 0, 0, 0)
266 const year = parseInt(uploadDateMatcher[1], 10)
267 // Month starts from 0
268 const month = parseInt(uploadDateMatcher[2], 10) - 1
269 const day = parseInt(uploadDateMatcher[3], 10)
271 originallyPublishedAt.setFullYear(year, month, day)
274 return originallyPublishedAt
277 // ---------------------------------------------------------------------------
280 updateYoutubeDLBinary,
281 getYoutubeDLVideoFormat,
282 downloadYoutubeDLVideo,
286 buildOriginallyPublishedAt
289 // ---------------------------------------------------------------------------
291 async function guessVideoPathWithExtension (tmpPath: string, sourceExt: string) {
292 if (!isVideoFileExtnameValid(sourceExt)) {
293 throw new Error('Invalid video extension ' + sourceExt)
296 const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ]
298 for (const extension of extensions) {
299 const path = tmpPath + extension
301 if (await pathExists(path)) return path
304 throw new Error('Cannot guess path of ' + tmpPath)
307 function normalizeObject (obj: any) {
308 const newObj: any = {}
310 for (const key of Object.keys(obj)) {
312 if (key === 'resolution') continue
314 const value = obj[key]
316 if (typeof value === 'string') {
317 newObj[key] = value.normalize()
326 function buildVideoInfo (obj: any): YoutubeDLInfo {
328 name: titleTruncation(obj.title),
329 description: descriptionTruncation(obj.description),
330 category: getCategory(obj.categories),
331 licence: getLicence(obj.license),
332 language: getLanguage(obj.language),
334 tags: getTags(obj.tags),
335 thumbnailUrl: obj.thumbnail || undefined,
336 originallyPublishedAt: buildOriginallyPublishedAt(obj),
341 function titleTruncation (title: string) {
342 return peertubeTruncate(title, {
343 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
349 function descriptionTruncation (description: string) {
350 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
352 return peertubeTruncate(description, {
353 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
359 function isNSFW (info: any) {
360 return info.age_limit && info.age_limit >= 16
363 function getTags (tags: any) {
364 if (Array.isArray(tags) === false) return []
367 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
368 .map(t => t.normalize())
372 function getLicence (licence: string) {
373 if (!licence) return undefined
375 if (licence.includes('Creative Commons Attribution')) return 1
377 for (const key of Object.keys(VIDEO_LICENCES)) {
378 const peertubeLicence = VIDEO_LICENCES[key]
379 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
385 function getCategory (categories: string[]) {
386 if (!categories) return undefined
388 const categoryString = categories[0]
389 if (!categoryString || typeof categoryString !== 'string') return undefined
391 if (categoryString === 'News & Politics') return 11
393 for (const key of Object.keys(VIDEO_CATEGORIES)) {
394 const category = VIDEO_CATEGORIES[key]
395 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
401 function getLanguage (language: string) {
402 return VIDEO_LANGUAGES[language] ? language : undefined
405 function wrapWithProxyOptions (options: string[]) {
406 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
407 logger.debug('Using proxy for YoutubeDL')
409 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)