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 = {
20 originallyPublishedAt?: Date
23 const processOptions = {
24 maxBuffer: 1024 * 1024 * 10 // 10MB
27 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
28 return new Promise<YoutubeDLInfo>((res, rej) => {
29 let args = opts || [ '-j', '--flat-playlist' ]
30 args = wrapWithProxyOptions(args)
34 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
35 if (err) return rej(err)
36 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
38 const obj = buildVideoInfo(normalizeObject(info))
39 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
44 .catch(err => rej(err))
48 function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) {
49 const path = generateVideoImportTmpPath(url, extension)
52 logger.info('Importing youtubeDL video %s to %s', url, path)
54 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
55 options = wrapWithProxyOptions(options)
57 if (process.env.FFMPEG_PATH) {
58 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
61 return new Promise<string>((res, rej) => {
64 youtubeDL.exec(url, options, processOptions, err => {
69 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
77 timer = setTimeout(() => {
78 const err = new Error('YoutubeDL download timeout.')
81 .finally(() => rej(err))
83 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
88 .catch(err => rej(err))
92 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
93 // We rewrote it to avoid sync calls
94 async function updateYoutubeDLBinary () {
95 logger.info('Updating youtubeDL binary.')
97 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
98 const bin = join(binDirectory, 'youtube-dl')
99 const detailsPath = join(binDirectory, 'details')
100 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
102 await ensureDir(binDirectory)
104 return new Promise(res => {
105 request.get(url, { followRedirect: false }, (err, result) => {
107 logger.error('Cannot update youtube-dl.', { err })
111 if (result.statusCode !== 302) {
112 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
116 const url = result.headers.location
117 const downloadFile = request.get(url)
118 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
120 downloadFile.on('response', result => {
121 if (result.statusCode !== 200) {
122 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
126 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
129 downloadFile.on('error', err => {
130 logger.error('youtube-dl update error.', { err })
134 downloadFile.on('end', () => {
135 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
136 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
138 logger.error('youtube-dl update error: cannot write details.', { err })
142 logger.info('youtube-dl updated to version %s.', newVersion)
150 async function safeGetYoutubeDL () {
154 youtubeDL = require('youtube-dl')
157 await updateYoutubeDLBinary()
158 youtubeDL = require('youtube-dl')
164 function buildOriginallyPublishedAt (obj: any) {
165 let originallyPublishedAt: Date = null
167 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
168 if (uploadDateMatcher) {
169 originallyPublishedAt = new Date()
170 originallyPublishedAt.setHours(0, 0, 0, 0)
172 const year = parseInt(uploadDateMatcher[1], 10)
173 // Month starts from 0
174 const month = parseInt(uploadDateMatcher[2], 10) - 1
175 const day = parseInt(uploadDateMatcher[3], 10)
177 originallyPublishedAt.setFullYear(year, month, day)
180 return originallyPublishedAt
183 // ---------------------------------------------------------------------------
186 updateYoutubeDLBinary,
187 downloadYoutubeDLVideo,
190 buildOriginallyPublishedAt
193 // ---------------------------------------------------------------------------
195 function normalizeObject (obj: any) {
196 const newObj: any = {}
198 for (const key of Object.keys(obj)) {
200 if (key === 'resolution') continue
202 const value = obj[key]
204 if (typeof value === 'string') {
205 newObj[key] = value.normalize()
214 function buildVideoInfo (obj: any) {
216 name: titleTruncation(obj.title),
217 description: descriptionTruncation(obj.description),
218 category: getCategory(obj.categories),
219 licence: getLicence(obj.license),
221 tags: getTags(obj.tags),
222 thumbnailUrl: obj.thumbnail || undefined,
223 originallyPublishedAt: buildOriginallyPublishedAt(obj),
228 function titleTruncation (title: string) {
229 return peertubeTruncate(title, {
230 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
236 function descriptionTruncation (description: string) {
237 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
239 return peertubeTruncate(description, {
240 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
246 function isNSFW (info: any) {
247 return info.age_limit && info.age_limit >= 16
250 function getTags (tags: any) {
251 if (Array.isArray(tags) === false) return []
254 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
255 .map(t => t.normalize())
259 function getLicence (licence: string) {
260 if (!licence) return undefined
262 if (licence.includes('Creative Commons Attribution')) return 1
267 function getCategory (categories: string[]) {
268 if (!categories) return undefined
270 const categoryString = categories[0]
271 if (!categoryString || typeof categoryString !== 'string') return undefined
273 if (categoryString === 'News & Politics') return 11
275 for (const key of Object.keys(VIDEO_CATEGORIES)) {
276 const category = VIDEO_CATEGORIES[key]
277 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
283 function wrapWithProxyOptions (options: string[]) {
284 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
285 logger.debug('Using proxy for YoutubeDL')
287 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)