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>((res, rej) => {
28 let args = opts || [ '-j', '--flat-playlist' ]
29 args = wrapWithProxyOptions(args)
33 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
34 if (err) return rej(err)
35 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
37 const obj = buildVideoInfo(normalizeObject(info))
38 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
43 .catch(err => rej(err))
47 function downloadYoutubeDLVideo (url: string, timeout: number) {
48 const path = generateVideoImportTmpPath(url)
51 logger.info('Importing youtubeDL video %s', url)
53 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
54 options = wrapWithProxyOptions(options)
56 if (process.env.FFMPEG_PATH) {
57 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
60 return new Promise<string>((res, rej) => {
63 youtubeDL.exec(url, options, processOptions, err => {
68 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
76 timer = setTimeout(() => {
77 const err = new Error('YoutubeDL download timeout.')
80 .finally(() => rej(err))
82 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
87 .catch(err => rej(err))
91 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
92 // We rewrote it to avoid sync calls
93 async function updateYoutubeDLBinary () {
94 logger.info('Updating youtubeDL binary.')
96 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
97 const bin = join(binDirectory, 'youtube-dl')
98 const detailsPath = join(binDirectory, 'details')
99 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
101 await ensureDir(binDirectory)
103 return new Promise(res => {
104 request.get(url, { followRedirect: false }, (err, result) => {
106 logger.error('Cannot update youtube-dl.', { err })
110 if (result.statusCode !== 302) {
111 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
115 const url = result.headers.location
116 const downloadFile = request.get(url)
117 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
119 downloadFile.on('response', result => {
120 if (result.statusCode !== 200) {
121 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
125 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
128 downloadFile.on('error', err => {
129 logger.error('youtube-dl update error.', { err })
133 downloadFile.on('end', () => {
134 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
135 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
137 logger.error('youtube-dl update error: cannot write details.', { err })
141 logger.info('youtube-dl updated to version %s.', newVersion)
149 async function safeGetYoutubeDL () {
153 youtubeDL = require('youtube-dl')
156 await updateYoutubeDLBinary()
157 youtubeDL = require('youtube-dl')
163 function buildOriginallyPublishedAt (obj: any) {
164 let originallyPublishedAt: Date = null
166 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
167 if (uploadDateMatcher) {
168 originallyPublishedAt = new Date()
169 originallyPublishedAt.setHours(0, 0, 0, 0)
171 const year = parseInt(uploadDateMatcher[1], 10)
172 // Month starts from 0
173 const month = parseInt(uploadDateMatcher[2], 10) - 1
174 const day = parseInt(uploadDateMatcher[3], 10)
176 originallyPublishedAt.setFullYear(year, month, day)
179 return originallyPublishedAt
182 // ---------------------------------------------------------------------------
185 updateYoutubeDLBinary,
186 downloadYoutubeDLVideo,
189 buildOriginallyPublishedAt
192 // ---------------------------------------------------------------------------
194 function normalizeObject (obj: any) {
195 const newObj: any = {}
197 for (const key of Object.keys(obj)) {
199 if (key === 'resolution') continue
201 const value = obj[key]
203 if (typeof value === 'string') {
204 newObj[key] = value.normalize()
213 function buildVideoInfo (obj: any) {
215 name: titleTruncation(obj.title),
216 description: descriptionTruncation(obj.description),
217 category: getCategory(obj.categories),
218 licence: getLicence(obj.license),
220 tags: getTags(obj.tags),
221 thumbnailUrl: obj.thumbnail || undefined,
222 originallyPublishedAt: buildOriginallyPublishedAt(obj)
226 function titleTruncation (title: string) {
227 return peertubeTruncate(title, {
228 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
234 function descriptionTruncation (description: string) {
235 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
237 return peertubeTruncate(description, {
238 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
244 function isNSFW (info: any) {
245 return info.age_limit && info.age_limit >= 16
248 function getTags (tags: any) {
249 if (Array.isArray(tags) === false) return []
252 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
253 .map(t => t.normalize())
257 function getLicence (licence: string) {
258 if (!licence) return undefined
260 if (licence.includes('Creative Commons Attribution')) return 1
265 function getCategory (categories: string[]) {
266 if (!categories) return undefined
268 const categoryString = categories[0]
269 if (!categoryString || typeof categoryString !== 'string') return undefined
271 if (categoryString === 'News & Politics') return 11
273 for (const key of Object.keys(VIDEO_CATEGORIES)) {
274 const category = VIDEO_CATEGORIES[key]
275 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
281 function wrapWithProxyOptions (options: string[]) {
282 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
283 logger.debug('Using proxy for YoutubeDL')
285 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)