1 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
2 import { logger } from './logger'
3 import { generateVideoImportTmpPath } from './utils'
4 import { getEnabledResolutions } from '../lib/video-transcoding'
5 import { join } from 'path'
6 import { peertubeTruncate, root } from './core-utils'
7 import { ensureDir, remove, writeFile } from 'fs-extra'
8 import * as request from 'request'
9 import { createWriteStream } from 'fs'
10 import { CONFIG } from '@server/initializers/config'
11 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
12 import { VideoResolution } from '../../shared/models/videos'
14 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.'))
54 if (info.format_id?.includes('+')) {
55 // this is a merge format and its extension will be appended
56 if (info.ext === 'mp4') {
58 } else if (info.ext === 'webm') {
59 info.mergeExt = 'webm'
65 const obj = buildVideoInfo(normalizeObject(info))
66 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
71 .catch(err => rej(err))
75 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
76 return new Promise<YoutubeDLSubs>((res, rej) => {
77 const cwd = CONFIG.STORAGE.TMP_DIR
78 const options = opts || { all: true, format: 'vtt', cwd }
82 youtubeDL.getSubs(url, options, (err, files) => {
83 if (err) return rej(err)
86 logger.debug('Get subtitles from youtube dl.', { url, files })
88 const subtitles = files.reduce((acc, filename) => {
89 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
90 if (!matched || !matched[1]) return acc
96 path: join(cwd, filename),
102 return res(subtitles)
105 .catch(err => rej(err))
109 function getYoutubeDLVideoFormat () {
111 * list of format selectors in order or preference
112 * see https://github.com/ytdl-org/youtube-dl#format-selection
114 * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope
115 * of being able to do a "quick-transcode"
116 * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9)
117 * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback
119 * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499
121 const enabledResolutions = getEnabledResolutions('vod')
122 const resolution = enabledResolutions.length === 0
123 ? VideoResolution.H_720P
124 : Math.max(...enabledResolutions)
127 `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1
128 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2
129 `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]`, // case #3
130 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio`,
131 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats
132 'best' // Ultimate fallback
136 function downloadYoutubeDLVideo (url: string, extension: string, timeout: number, mergeExtension?: string) {
137 let path = generateVideoImportTmpPath(url, extension)
139 path = mergeExtension
140 ? path.replace(new RegExp(`${extension}$`), mergeExtension)
145 logger.info('Importing youtubeDL video %s to %s', url, path)
147 let options = [ '-f', getYoutubeDLVideoFormat(), '-o', path ]
148 options = wrapWithProxyOptions(options)
150 if (process.env.FFMPEG_PATH) {
151 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
154 logger.debug('YoutubeDL options for %s.', url, { options })
156 return new Promise<string>((res, rej) => {
159 youtubeDL.exec(url, options, processOptions, err => {
164 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
172 timer = setTimeout(() => {
173 const err = new Error('YoutubeDL download timeout.')
176 .finally(() => rej(err))
178 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
183 .catch(err => rej(err))
187 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
188 // We rewrote it to avoid sync calls
189 async function updateYoutubeDLBinary () {
190 logger.info('Updating youtubeDL binary.')
192 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
193 const bin = join(binDirectory, 'youtube-dl')
194 const detailsPath = join(binDirectory, 'details')
195 const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl'
197 await ensureDir(binDirectory)
199 return new Promise(res => {
200 request.get(url, { followRedirect: false }, (err, result) => {
202 logger.error('Cannot update youtube-dl.', { err })
206 if (result.statusCode !== HttpStatusCode.FOUND_302) {
207 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
211 const url = result.headers.location
212 const downloadFile = request.get(url)
213 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
215 downloadFile.on('response', result => {
216 if (result.statusCode !== HttpStatusCode.OK_200) {
217 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
221 const writeStream = createWriteStream(bin, { mode: 493 }).on('error', err => {
222 logger.error('youtube-dl update error in write stream', { err })
226 downloadFile.pipe(writeStream)
229 downloadFile.on('error', err => {
230 logger.error('youtube-dl update error.', { err })
234 downloadFile.on('end', () => {
235 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
236 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
238 logger.error('youtube-dl update error: cannot write details.', { err })
242 logger.info('youtube-dl updated to version %s.', newVersion)
250 async function safeGetYoutubeDL () {
254 youtubeDL = require('youtube-dl')
257 await updateYoutubeDLBinary()
258 youtubeDL = require('youtube-dl')
264 function buildOriginallyPublishedAt (obj: any) {
265 let originallyPublishedAt: Date = null
267 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
268 if (uploadDateMatcher) {
269 originallyPublishedAt = new Date()
270 originallyPublishedAt.setHours(0, 0, 0, 0)
272 const year = parseInt(uploadDateMatcher[1], 10)
273 // Month starts from 0
274 const month = parseInt(uploadDateMatcher[2], 10) - 1
275 const day = parseInt(uploadDateMatcher[3], 10)
277 originallyPublishedAt.setFullYear(year, month, day)
280 return originallyPublishedAt
283 // ---------------------------------------------------------------------------
286 updateYoutubeDLBinary,
287 getYoutubeDLVideoFormat,
288 downloadYoutubeDLVideo,
292 buildOriginallyPublishedAt
295 // ---------------------------------------------------------------------------
297 function normalizeObject (obj: any) {
298 const newObj: any = {}
300 for (const key of Object.keys(obj)) {
302 if (key === 'resolution') continue
304 const value = obj[key]
306 if (typeof value === 'string') {
307 newObj[key] = value.normalize()
316 function buildVideoInfo (obj: any): YoutubeDLInfo {
318 name: titleTruncation(obj.title),
319 description: descriptionTruncation(obj.description),
320 category: getCategory(obj.categories),
321 licence: getLicence(obj.license),
322 language: getLanguage(obj.language),
324 tags: getTags(obj.tags),
325 thumbnailUrl: obj.thumbnail || undefined,
326 originallyPublishedAt: buildOriginallyPublishedAt(obj),
328 mergeExt: obj.mergeExt
332 function titleTruncation (title: string) {
333 return peertubeTruncate(title, {
334 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
340 function descriptionTruncation (description: string) {
341 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
343 return peertubeTruncate(description, {
344 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
350 function isNSFW (info: any) {
351 return info.age_limit && info.age_limit >= 16
354 function getTags (tags: any) {
355 if (Array.isArray(tags) === false) return []
358 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
359 .map(t => t.normalize())
363 function getLicence (licence: string) {
364 if (!licence) return undefined
366 if (licence.includes('Creative Commons Attribution')) return 1
368 for (const key of Object.keys(VIDEO_LICENCES)) {
369 const peertubeLicence = VIDEO_LICENCES[key]
370 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
376 function getCategory (categories: string[]) {
377 if (!categories) return undefined
379 const categoryString = categories[0]
380 if (!categoryString || typeof categoryString !== 'string') return undefined
382 if (categoryString === 'News & Politics') return 11
384 for (const key of Object.keys(VIDEO_CATEGORIES)) {
385 const category = VIDEO_CATEGORIES[key]
386 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
392 function getLanguage (language: string) {
393 return VIDEO_LANGUAGES[language] ? language : undefined
396 function wrapWithProxyOptions (options: string[]) {
397 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
398 logger.debug('Using proxy for YoutubeDL')
400 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)