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 const args = opts || [ '-j', '--flat-playlist' ]
30 const youtubeDL = await safeGetYoutubeDL()
31 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
32 if (err) return rej(err)
33 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
35 const obj = buildVideoInfo(normalizeObject(info))
36 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
43 function downloadYoutubeDLVideo (url: string, timeout: number) {
44 const path = generateVideoImportTmpPath(url)
47 logger.info('Importing youtubeDL video %s', url)
49 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
51 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
52 logger.debug('Using proxy for YoutubeDL')
54 options = [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)
57 if (process.env.FFMPEG_PATH) {
58 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
61 return new Promise<string>(async (res, rej) => {
62 const youtubeDL = await safeGetYoutubeDL()
63 youtubeDL.exec(url, options, processOptions, err => {
68 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
76 timer = setTimeout(async () => {
79 return rej(new Error('YoutubeDL download timeout.'))
84 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
85 // We rewrote it to avoid sync calls
86 async function updateYoutubeDLBinary () {
87 logger.info('Updating youtubeDL binary.')
89 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
90 const bin = join(binDirectory, 'youtube-dl')
91 const detailsPath = join(binDirectory, 'details')
92 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
94 await ensureDir(binDirectory)
96 return new Promise(res => {
97 request.get(url, { followRedirect: false }, (err, result) => {
99 logger.error('Cannot update youtube-dl.', { err })
103 if (result.statusCode !== 302) {
104 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
108 const url = result.headers.location
109 const downloadFile = request.get(url)
110 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
112 downloadFile.on('response', result => {
113 if (result.statusCode !== 200) {
114 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
118 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
121 downloadFile.on('error', err => {
122 logger.error('youtube-dl update error.', { err })
126 downloadFile.on('end', () => {
127 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
128 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
130 logger.error('youtube-dl update error: cannot write details.', { err })
134 logger.info('youtube-dl updated to version %s.', newVersion)
142 async function safeGetYoutubeDL () {
146 youtubeDL = require('youtube-dl')
149 await updateYoutubeDLBinary()
150 youtubeDL = require('youtube-dl')
156 function buildOriginallyPublishedAt (obj: any) {
157 let originallyPublishedAt: Date = null
159 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
160 if (uploadDateMatcher) {
161 originallyPublishedAt = new Date()
162 originallyPublishedAt.setHours(0, 0, 0, 0)
164 const year = parseInt(uploadDateMatcher[1], 10)
165 // Month starts from 0
166 const month = parseInt(uploadDateMatcher[2], 10) - 1
167 const day = parseInt(uploadDateMatcher[3], 10)
169 originallyPublishedAt.setFullYear(year, month, day)
172 return originallyPublishedAt
175 // ---------------------------------------------------------------------------
178 updateYoutubeDLBinary,
179 downloadYoutubeDLVideo,
182 buildOriginallyPublishedAt
185 // ---------------------------------------------------------------------------
187 function normalizeObject (obj: any) {
188 const newObj: any = {}
190 for (const key of Object.keys(obj)) {
192 if (key === 'resolution') continue
194 const value = obj[key]
196 if (typeof value === 'string') {
197 newObj[key] = value.normalize()
206 function buildVideoInfo (obj: any) {
208 name: titleTruncation(obj.title),
209 description: descriptionTruncation(obj.description),
210 category: getCategory(obj.categories),
211 licence: getLicence(obj.license),
213 tags: getTags(obj.tags),
214 thumbnailUrl: obj.thumbnail || undefined,
215 originallyPublishedAt: buildOriginallyPublishedAt(obj)
219 function titleTruncation (title: string) {
220 return peertubeTruncate(title, {
221 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
227 function descriptionTruncation (description: string) {
228 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
230 return peertubeTruncate(description, {
231 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
237 function isNSFW (info: any) {
238 return info.age_limit && info.age_limit >= 16
241 function getTags (tags: any) {
242 if (Array.isArray(tags) === false) return []
245 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
246 .map(t => t.normalize())
250 function getLicence (licence: string) {
251 if (!licence) return undefined
253 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
258 function getCategory (categories: string[]) {
259 if (!categories) return undefined
261 const categoryString = categories[0]
262 if (!categoryString || typeof categoryString !== 'string') return undefined
264 if (categoryString === 'News & Politics') return 11
266 for (const key of Object.keys(VIDEO_CATEGORIES)) {
267 const category = VIDEO_CATEGORIES[key]
268 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)