1 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } 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 = {
19 originallyPublishedAt?: Date
22 const processOptions = {
23 maxBuffer: 1024 * 1024 * 10 // 10MB
26 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
27 return new Promise<YoutubeDLInfo>(async (res, rej) => {
28 let args = opts || [ '-j', '--flat-playlist' ]
29 args = wrapWithProxyOptions(args)
31 const youtubeDL = await safeGetYoutubeDL()
32 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
33 if (err) return rej(err)
34 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
36 const obj = buildVideoInfo(normalizeObject(info))
37 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
44 function downloadYoutubeDLVideo (url: string, timeout: number) {
45 const path = generateVideoImportTmpPath(url)
48 logger.info('Importing youtubeDL video %s', url)
50 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
51 options = wrapWithProxyOptions(options)
53 if (process.env.FFMPEG_PATH) {
54 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
57 return new Promise<string>(async (res, rej) => {
58 const youtubeDL = await safeGetYoutubeDL()
59 youtubeDL.exec(url, options, processOptions, err => {
64 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
72 timer = setTimeout(async () => {
75 return rej(new Error('YoutubeDL download timeout.'))
80 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
81 // We rewrote it to avoid sync calls
82 async function updateYoutubeDLBinary () {
83 logger.info('Updating youtubeDL binary.')
85 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
86 const bin = join(binDirectory, 'youtube-dl')
87 const detailsPath = join(binDirectory, 'details')
88 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
90 await ensureDir(binDirectory)
92 return new Promise(res => {
93 request.get(url, { followRedirect: false }, (err, result) => {
95 logger.error('Cannot update youtube-dl.', { err })
99 if (result.statusCode !== 302) {
100 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
104 const url = result.headers.location
105 const downloadFile = request.get(url)
106 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
108 downloadFile.on('response', result => {
109 if (result.statusCode !== 200) {
110 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
114 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
117 downloadFile.on('error', err => {
118 logger.error('youtube-dl update error.', { err })
122 downloadFile.on('end', () => {
123 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
124 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
126 logger.error('youtube-dl update error: cannot write details.', { err })
130 logger.info('youtube-dl updated to version %s.', newVersion)
138 async function safeGetYoutubeDL () {
142 youtubeDL = require('youtube-dl')
145 await updateYoutubeDLBinary()
146 youtubeDL = require('youtube-dl')
152 function buildOriginallyPublishedAt (obj: any) {
153 let originallyPublishedAt: Date = null
155 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
156 if (uploadDateMatcher) {
157 originallyPublishedAt = new Date()
158 originallyPublishedAt.setHours(0, 0, 0, 0)
160 const year = parseInt(uploadDateMatcher[1], 10)
161 // Month starts from 0
162 const month = parseInt(uploadDateMatcher[2], 10) - 1
163 const day = parseInt(uploadDateMatcher[3], 10)
165 originallyPublishedAt.setFullYear(year, month, day)
168 return originallyPublishedAt
171 // ---------------------------------------------------------------------------
174 updateYoutubeDLBinary,
175 downloadYoutubeDLVideo,
178 buildOriginallyPublishedAt
181 // ---------------------------------------------------------------------------
183 function normalizeObject (obj: any) {
184 const newObj: any = {}
186 for (const key of Object.keys(obj)) {
188 if (key === 'resolution') continue
190 const value = obj[key]
192 if (typeof value === 'string') {
193 newObj[key] = value.normalize()
202 function buildVideoInfo (obj: any) {
204 name: titleTruncation(obj.title),
205 description: descriptionTruncation(obj.description),
206 category: getCategory(obj.categories),
207 licence: getLicence(obj.license),
209 tags: getTags(obj.tags),
210 thumbnailUrl: obj.thumbnail || undefined,
211 originallyPublishedAt: buildOriginallyPublishedAt(obj)
215 function titleTruncation (title: string) {
216 return peertubeTruncate(title, {
217 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
223 function descriptionTruncation (description: string) {
224 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
226 return peertubeTruncate(description, {
227 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
233 function isNSFW (info: any) {
234 return info.age_limit && info.age_limit >= 16
237 function getTags (tags: any) {
238 if (Array.isArray(tags) === false) return []
241 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
242 .map(t => t.normalize())
246 function getLicence (licence: string) {
247 if (!licence) return undefined
249 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
254 function getCategory (categories: string[]) {
255 if (!categories) return undefined
257 const categoryString = categories[0]
258 if (!categoryString || typeof categoryString !== 'string') return undefined
260 if (categoryString === 'News & Politics') return 11
262 for (const key of Object.keys(VIDEO_CATEGORIES)) {
263 const category = VIDEO_CATEGORIES[key]
264 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
270 function wrapWithProxyOptions (options: string[]) {
271 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
272 logger.debug('Using proxy for YoutubeDL')
274 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)