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 { join } from 'path'
5 import { peertubeTruncate, root } from './core-utils'
6 import { ensureDir, remove, writeFile } from 'fs-extra'
7 import * as request from 'request'
8 import { createWriteStream } from 'fs'
9 import { CONFIG } from '@server/initializers/config'
11 export type YoutubeDLInfo = {
21 originallyPublishedAt?: Date
24 export type YoutubeDLSubs = {
30 const processOptions = {
31 maxBuffer: 1024 * 1024 * 10 // 10MB
34 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
35 return new Promise<YoutubeDLInfo>((res, rej) => {
36 let args = opts || [ '-j', '--flat-playlist' ]
38 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) {
39 args.push('--force-ipv4')
42 args = wrapWithProxyOptions(args)
46 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
47 if (err) return rej(err)
48 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
50 const obj = buildVideoInfo(normalizeObject(info))
51 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
56 .catch(err => rej(err))
60 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
61 return new Promise<YoutubeDLSubs>((res, rej) => {
62 const cwd = CONFIG.STORAGE.TMP_DIR
63 const options = opts || { all: true, format: 'vtt', cwd }
67 youtubeDL.getSubs(url, options, (err, files) => {
68 if (err) return rej(err)
71 logger.debug('Get subtitles from youtube dl.', { url, files })
73 const subtitles = files.reduce((acc, filename) => {
74 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
75 if (!matched || !matched[1]) return acc
81 path: join(cwd, filename),
90 .catch(err => rej(err))
94 function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) {
95 const path = generateVideoImportTmpPath(url, extension)
98 logger.info('Importing youtubeDL video %s to %s', url, path)
100 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
101 options = wrapWithProxyOptions(options)
103 if (process.env.FFMPEG_PATH) {
104 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
107 return new Promise<string>((res, rej) => {
110 youtubeDL.exec(url, options, processOptions, err => {
115 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
123 timer = setTimeout(() => {
124 const err = new Error('YoutubeDL download timeout.')
127 .finally(() => rej(err))
129 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
134 .catch(err => rej(err))
138 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
139 // We rewrote it to avoid sync calls
140 async function updateYoutubeDLBinary () {
141 logger.info('Updating youtubeDL binary.')
143 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
144 const bin = join(binDirectory, 'youtube-dl')
145 const detailsPath = join(binDirectory, 'details')
146 const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl'
148 await ensureDir(binDirectory)
150 return new Promise(res => {
151 request.get(url, { followRedirect: false }, (err, result) => {
153 logger.error('Cannot update youtube-dl.', { err })
157 if (result.statusCode !== 302) {
158 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
162 const url = result.headers.location
163 const downloadFile = request.get(url)
164 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
166 downloadFile.on('response', result => {
167 if (result.statusCode !== 200) {
168 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
172 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
175 downloadFile.on('error', err => {
176 logger.error('youtube-dl update error.', { err })
180 downloadFile.on('end', () => {
181 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
182 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
184 logger.error('youtube-dl update error: cannot write details.', { err })
188 logger.info('youtube-dl updated to version %s.', newVersion)
196 async function safeGetYoutubeDL () {
200 youtubeDL = require('youtube-dl')
203 await updateYoutubeDLBinary()
204 youtubeDL = require('youtube-dl')
210 function buildOriginallyPublishedAt (obj: any) {
211 let originallyPublishedAt: Date = null
213 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
214 if (uploadDateMatcher) {
215 originallyPublishedAt = new Date()
216 originallyPublishedAt.setHours(0, 0, 0, 0)
218 const year = parseInt(uploadDateMatcher[1], 10)
219 // Month starts from 0
220 const month = parseInt(uploadDateMatcher[2], 10) - 1
221 const day = parseInt(uploadDateMatcher[3], 10)
223 originallyPublishedAt.setFullYear(year, month, day)
226 return originallyPublishedAt
229 // ---------------------------------------------------------------------------
232 updateYoutubeDLBinary,
233 downloadYoutubeDLVideo,
237 buildOriginallyPublishedAt
240 // ---------------------------------------------------------------------------
242 function normalizeObject (obj: any) {
243 const newObj: any = {}
245 for (const key of Object.keys(obj)) {
247 if (key === 'resolution') continue
249 const value = obj[key]
251 if (typeof value === 'string') {
252 newObj[key] = value.normalize()
261 function buildVideoInfo (obj: any): YoutubeDLInfo {
263 name: titleTruncation(obj.title),
264 description: descriptionTruncation(obj.description),
265 category: getCategory(obj.categories),
266 licence: getLicence(obj.license),
267 language: getLanguage(obj.language),
269 tags: getTags(obj.tags),
270 thumbnailUrl: obj.thumbnail || undefined,
271 originallyPublishedAt: buildOriginallyPublishedAt(obj),
276 function titleTruncation (title: string) {
277 return peertubeTruncate(title, {
278 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
284 function descriptionTruncation (description: string) {
285 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
287 return peertubeTruncate(description, {
288 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
294 function isNSFW (info: any) {
295 return info.age_limit && info.age_limit >= 16
298 function getTags (tags: any) {
299 if (Array.isArray(tags) === false) return []
302 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
303 .map(t => t.normalize())
307 function getLicence (licence: string) {
308 if (!licence) return undefined
310 if (licence.includes('Creative Commons Attribution')) return 1
312 for (const key of Object.keys(VIDEO_LICENCES)) {
313 const peertubeLicence = VIDEO_LICENCES[key]
314 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
320 function getCategory (categories: string[]) {
321 if (!categories) return undefined
323 const categoryString = categories[0]
324 if (!categoryString || typeof categoryString !== 'string') return undefined
326 if (categoryString === 'News & Politics') return 11
328 for (const key of Object.keys(VIDEO_CATEGORIES)) {
329 const category = VIDEO_CATEGORIES[key]
330 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
336 function getLanguage (language: string) {
337 return VIDEO_LANGUAGES[language] ? language : undefined
340 function wrapWithProxyOptions (options: string[]) {
341 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
342 logger.debug('Using proxy for YoutubeDL')
344 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)