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'
10 export type YoutubeDLInfo = {
18 originallyPublishedAt?: Date
21 const processOptions = {
22 maxBuffer: 1024 * 1024 * 10 // 10MB
25 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
26 return new Promise<YoutubeDLInfo>(async (res, rej) => {
27 const args = opts || [ '-j', '--flat-playlist' ]
29 const youtubeDL = await safeGetYoutubeDL()
30 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
31 if (err) return rej(err)
32 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
34 const obj = buildVideoInfo(normalizeObject(info))
35 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
42 function downloadYoutubeDLVideo (url: string, timeout: number) {
43 const path = generateVideoImportTmpPath(url)
46 logger.info('Importing youtubeDL video %s', url)
48 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
50 if (process.env.FFMPEG_PATH) {
51 options.push('--ffmpeg-location')
52 options.push(process.env.FFMPEG_PATH)
55 return new Promise<string>(async (res, rej) => {
56 const youtubeDL = await safeGetYoutubeDL()
57 youtubeDL.exec(url, options, processOptions, err => {
62 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
70 timer = setTimeout(async () => {
73 return rej(new Error('YoutubeDL download timeout.'))
78 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
79 // We rewrote it to avoid sync calls
80 async function updateYoutubeDLBinary () {
81 logger.info('Updating youtubeDL binary.')
83 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
84 const bin = join(binDirectory, 'youtube-dl')
85 const detailsPath = join(binDirectory, 'details')
86 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
88 await ensureDir(binDirectory)
90 return new Promise(res => {
91 request.get(url, { followRedirect: false }, (err, result) => {
93 logger.error('Cannot update youtube-dl.', { err })
97 if (result.statusCode !== 302) {
98 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
102 const url = result.headers.location
103 const downloadFile = request.get(url)
104 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
106 downloadFile.on('response', result => {
107 if (result.statusCode !== 200) {
108 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
112 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
115 downloadFile.on('error', err => {
116 logger.error('youtube-dl update error.', { err })
120 downloadFile.on('end', () => {
121 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
122 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
124 logger.error('youtube-dl update error: cannot write details.', { err })
128 logger.info('youtube-dl updated to version %s.', newVersion)
136 async function safeGetYoutubeDL () {
140 youtubeDL = require('youtube-dl')
143 await updateYoutubeDLBinary()
144 youtubeDL = require('youtube-dl')
150 function buildOriginallyPublishedAt (obj: any) {
151 let originallyPublishedAt: Date = null
153 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
154 if (uploadDateMatcher) {
155 originallyPublishedAt = new Date()
156 originallyPublishedAt.setHours(0, 0, 0, 0)
158 const year = parseInt(uploadDateMatcher[1], 10)
159 // Month starts from 0
160 const month = parseInt(uploadDateMatcher[2], 10) - 1
161 const day = parseInt(uploadDateMatcher[3], 10)
163 originallyPublishedAt.setFullYear(year, month, day)
166 return originallyPublishedAt
169 // ---------------------------------------------------------------------------
172 updateYoutubeDLBinary,
173 downloadYoutubeDLVideo,
176 buildOriginallyPublishedAt
179 // ---------------------------------------------------------------------------
181 function normalizeObject (obj: any) {
182 const newObj: any = {}
184 for (const key of Object.keys(obj)) {
186 if (key === 'resolution') continue
188 const value = obj[key]
190 if (typeof value === 'string') {
191 newObj[key] = value.normalize()
200 function buildVideoInfo (obj: any) {
202 name: titleTruncation(obj.title),
203 description: descriptionTruncation(obj.description),
204 category: getCategory(obj.categories),
205 licence: getLicence(obj.license),
207 tags: getTags(obj.tags),
208 thumbnailUrl: obj.thumbnail || undefined,
209 originallyPublishedAt: buildOriginallyPublishedAt(obj)
213 function titleTruncation (title: string) {
214 return peertubeTruncate(title, {
215 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
221 function descriptionTruncation (description: string) {
222 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
224 return peertubeTruncate(description, {
225 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
231 function isNSFW (info: any) {
232 return info.age_limit && info.age_limit >= 16
235 function getTags (tags: any) {
236 if (Array.isArray(tags) === false) return []
239 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
240 .map(t => t.normalize())
244 function getLicence (licence: string) {
245 if (!licence) return undefined
247 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
252 function getCategory (categories: string[]) {
253 if (!categories) return undefined
255 const categoryString = categories[0]
256 if (!categoryString || typeof categoryString !== 'string') return undefined
258 if (categoryString === 'News & Politics') return 11
260 for (const key of Object.keys(VIDEO_CATEGORIES)) {
261 const category = VIDEO_CATEGORIES[key]
262 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)