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 export type YoutubeDLSubs = {
29 const processOptions = {
30 maxBuffer: 1024 * 1024 * 10 // 10MB
33 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
34 return new Promise<YoutubeDLInfo>((res, rej) => {
35 let args = opts || [ '-j', '--flat-playlist' ]
36 args = wrapWithProxyOptions(args)
40 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
41 if (err) return rej(err)
42 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
44 const obj = buildVideoInfo(normalizeObject(info))
45 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
50 .catch(err => rej(err))
54 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
55 return new Promise<YoutubeDLSubs>((res, rej) => {
56 const cwd = CONFIG.STORAGE.TMP_DIR
57 const options = opts || { all: true, format: 'vtt', cwd }
61 youtubeDL.getSubs(url, options, (err, files) => {
62 if (err) return rej(err)
64 const subtitles = files.reduce((acc, filename) => {
65 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
70 path: join(cwd, filename),
79 .catch(err => rej(err))
83 function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) {
84 const path = generateVideoImportTmpPath(url, extension)
87 logger.info('Importing youtubeDL video %s to %s', url, path)
89 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
90 options = wrapWithProxyOptions(options)
92 if (process.env.FFMPEG_PATH) {
93 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
96 return new Promise<string>((res, rej) => {
99 youtubeDL.exec(url, options, processOptions, err => {
104 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
112 timer = setTimeout(() => {
113 const err = new Error('YoutubeDL download timeout.')
116 .finally(() => rej(err))
118 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
123 .catch(err => rej(err))
127 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
128 // We rewrote it to avoid sync calls
129 async function updateYoutubeDLBinary () {
130 logger.info('Updating youtubeDL binary.')
132 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
133 const bin = join(binDirectory, 'youtube-dl')
134 const detailsPath = join(binDirectory, 'details')
135 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
137 await ensureDir(binDirectory)
139 return new Promise(res => {
140 request.get(url, { followRedirect: false }, (err, result) => {
142 logger.error('Cannot update youtube-dl.', { err })
146 if (result.statusCode !== 302) {
147 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
151 const url = result.headers.location
152 const downloadFile = request.get(url)
153 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
155 downloadFile.on('response', result => {
156 if (result.statusCode !== 200) {
157 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
161 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
164 downloadFile.on('error', err => {
165 logger.error('youtube-dl update error.', { err })
169 downloadFile.on('end', () => {
170 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
171 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
173 logger.error('youtube-dl update error: cannot write details.', { err })
177 logger.info('youtube-dl updated to version %s.', newVersion)
185 async function safeGetYoutubeDL () {
189 youtubeDL = require('youtube-dl')
192 await updateYoutubeDLBinary()
193 youtubeDL = require('youtube-dl')
199 function buildOriginallyPublishedAt (obj: any) {
200 let originallyPublishedAt: Date = null
202 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
203 if (uploadDateMatcher) {
204 originallyPublishedAt = new Date()
205 originallyPublishedAt.setHours(0, 0, 0, 0)
207 const year = parseInt(uploadDateMatcher[1], 10)
208 // Month starts from 0
209 const month = parseInt(uploadDateMatcher[2], 10) - 1
210 const day = parseInt(uploadDateMatcher[3], 10)
212 originallyPublishedAt.setFullYear(year, month, day)
215 return originallyPublishedAt
218 // ---------------------------------------------------------------------------
221 updateYoutubeDLBinary,
222 downloadYoutubeDLVideo,
226 buildOriginallyPublishedAt
229 // ---------------------------------------------------------------------------
231 function normalizeObject (obj: any) {
232 const newObj: any = {}
234 for (const key of Object.keys(obj)) {
236 if (key === 'resolution') continue
238 const value = obj[key]
240 if (typeof value === 'string') {
241 newObj[key] = value.normalize()
250 function buildVideoInfo (obj: any) {
252 name: titleTruncation(obj.title),
253 description: descriptionTruncation(obj.description),
254 category: getCategory(obj.categories),
255 licence: getLicence(obj.license),
257 tags: getTags(obj.tags),
258 thumbnailUrl: obj.thumbnail || undefined,
259 originallyPublishedAt: buildOriginallyPublishedAt(obj),
264 function titleTruncation (title: string) {
265 return peertubeTruncate(title, {
266 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
272 function descriptionTruncation (description: string) {
273 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
275 return peertubeTruncate(description, {
276 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
282 function isNSFW (info: any) {
283 return info.age_limit && info.age_limit >= 16
286 function getTags (tags: any) {
287 if (Array.isArray(tags) === false) return []
290 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
291 .map(t => t.normalize())
295 function getLicence (licence: string) {
296 if (!licence) return undefined
298 if (licence.includes('Creative Commons Attribution')) return 1
303 function getCategory (categories: string[]) {
304 if (!categories) return undefined
306 const categoryString = categories[0]
307 if (!categoryString || typeof categoryString !== 'string') return undefined
309 if (categoryString === 'News & Politics') return 11
311 for (const key of Object.keys(VIDEO_CATEGORIES)) {
312 const category = VIDEO_CATEGORIES[key]
313 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
319 function wrapWithProxyOptions (options: string[]) {
320 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
321 logger.debug('Using proxy for YoutubeDL')
323 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)