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' ]
37 args = wrapWithProxyOptions(args)
41 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
42 if (err) return rej(err)
43 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
45 const obj = buildVideoInfo(normalizeObject(info))
46 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
51 .catch(err => rej(err))
55 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
56 return new Promise<YoutubeDLSubs>((res, rej) => {
57 const cwd = CONFIG.STORAGE.TMP_DIR
58 const options = opts || { all: true, format: 'vtt', cwd }
62 youtubeDL.getSubs(url, options, (err, files) => {
63 if (err) return rej(err)
66 logger.debug('Get subtitles from youtube dl.', { url, files })
68 const subtitles = files.reduce((acc, filename) => {
69 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
70 if (!matched || !matched[1]) return acc
76 path: join(cwd, filename),
85 .catch(err => rej(err))
89 function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) {
90 const path = generateVideoImportTmpPath(url, extension)
93 logger.info('Importing youtubeDL video %s to %s', url, path)
95 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
96 options = wrapWithProxyOptions(options)
98 if (process.env.FFMPEG_PATH) {
99 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
102 return new Promise<string>((res, rej) => {
105 youtubeDL.exec(url, options, processOptions, err => {
110 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
118 timer = setTimeout(() => {
119 const err = new Error('YoutubeDL download timeout.')
122 .finally(() => rej(err))
124 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
129 .catch(err => rej(err))
133 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
134 // We rewrote it to avoid sync calls
135 async function updateYoutubeDLBinary () {
136 logger.info('Updating youtubeDL binary.')
138 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
139 const bin = join(binDirectory, 'youtube-dl')
140 const detailsPath = join(binDirectory, 'details')
141 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
143 await ensureDir(binDirectory)
145 return new Promise(res => {
146 request.get(url, { followRedirect: false }, (err, result) => {
148 logger.error('Cannot update youtube-dl.', { err })
152 if (result.statusCode !== 302) {
153 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
157 const url = result.headers.location
158 const downloadFile = request.get(url)
159 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
161 downloadFile.on('response', result => {
162 if (result.statusCode !== 200) {
163 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
167 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
170 downloadFile.on('error', err => {
171 logger.error('youtube-dl update error.', { err })
175 downloadFile.on('end', () => {
176 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
177 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
179 logger.error('youtube-dl update error: cannot write details.', { err })
183 logger.info('youtube-dl updated to version %s.', newVersion)
191 async function safeGetYoutubeDL () {
195 youtubeDL = require('youtube-dl')
198 await updateYoutubeDLBinary()
199 youtubeDL = require('youtube-dl')
205 function buildOriginallyPublishedAt (obj: any) {
206 let originallyPublishedAt: Date = null
208 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
209 if (uploadDateMatcher) {
210 originallyPublishedAt = new Date()
211 originallyPublishedAt.setHours(0, 0, 0, 0)
213 const year = parseInt(uploadDateMatcher[1], 10)
214 // Month starts from 0
215 const month = parseInt(uploadDateMatcher[2], 10) - 1
216 const day = parseInt(uploadDateMatcher[3], 10)
218 originallyPublishedAt.setFullYear(year, month, day)
221 return originallyPublishedAt
224 // ---------------------------------------------------------------------------
227 updateYoutubeDLBinary,
228 downloadYoutubeDLVideo,
232 buildOriginallyPublishedAt
235 // ---------------------------------------------------------------------------
237 function normalizeObject (obj: any) {
238 const newObj: any = {}
240 for (const key of Object.keys(obj)) {
242 if (key === 'resolution') continue
244 const value = obj[key]
246 if (typeof value === 'string') {
247 newObj[key] = value.normalize()
256 function buildVideoInfo (obj: any): YoutubeDLInfo {
258 name: titleTruncation(obj.title),
259 description: descriptionTruncation(obj.description),
260 category: getCategory(obj.categories),
261 licence: getLicence(obj.license),
262 language: getLanguage(obj.language),
264 tags: getTags(obj.tags),
265 thumbnailUrl: obj.thumbnail || undefined,
266 originallyPublishedAt: buildOriginallyPublishedAt(obj),
271 function titleTruncation (title: string) {
272 return peertubeTruncate(title, {
273 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
279 function descriptionTruncation (description: string) {
280 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
282 return peertubeTruncate(description, {
283 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
289 function isNSFW (info: any) {
290 return info.age_limit && info.age_limit >= 16
293 function getTags (tags: any) {
294 if (Array.isArray(tags) === false) return []
297 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
298 .map(t => t.normalize())
302 function getLicence (licence: string) {
303 if (!licence) return undefined
305 if (licence.includes('Creative Commons Attribution')) return 1
307 for (const key of Object.keys(VIDEO_LICENCES)) {
308 const peertubeLicence = VIDEO_LICENCES[key]
309 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
315 function getCategory (categories: string[]) {
316 if (!categories) return undefined
318 const categoryString = categories[0]
319 if (!categoryString || typeof categoryString !== 'string') return undefined
321 if (categoryString === 'News & Politics') return 11
323 for (const key of Object.keys(VIDEO_CATEGORIES)) {
324 const category = VIDEO_CATEGORIES[key]
325 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
331 function getLanguage (language: string) {
332 return VIDEO_LANGUAGES[language] ? language : undefined
335 function wrapWithProxyOptions (options: string[]) {
336 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
337 logger.debug('Using proxy for YoutubeDL')
339 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)