1 import { truncate } from 'lodash'
2 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers'
3 import { logger } from './logger'
4 import { generateVideoTmpPath } from './utils'
5 import { join } from 'path'
6 import { root } from './core-utils'
7 import { ensureDir, writeFile } from 'fs-extra'
8 import * as request from 'request'
9 import { createWriteStream } from 'fs'
11 export type YoutubeDLInfo = {
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 options = opts || [ '-j', '--flat-playlist' ]
29 const youtubeDL = await safeGetYoutubeDL()
30 youtubeDL.getInfo(url, options, (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) {
43 const path = generateVideoTmpPath(url)
45 logger.info('Importing youtubeDL video %s', url)
47 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
49 return new Promise<string>(async (res, rej) => {
50 const youtubeDL = await safeGetYoutubeDL()
51 youtubeDL.exec(url, options, processOptions, err => {
52 if (err) return rej(err)
59 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
60 // We rewrote it to avoid sync calls
61 async function updateYoutubeDLBinary () {
62 logger.info('Updating youtubeDL binary.')
64 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
65 const bin = join(binDirectory, 'youtube-dl')
66 const detailsPath = join(binDirectory, 'details')
67 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
69 await ensureDir(binDirectory)
71 return new Promise(res => {
72 request.get(url, { followRedirect: false }, (err, result) => {
74 logger.error('Cannot update youtube-dl.', { err })
78 if (result.statusCode !== 302) {
79 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
83 const url = result.headers.location
84 const downloadFile = request.get(url)
85 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
87 downloadFile.on('response', result => {
88 if (result.statusCode !== 200) {
89 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
93 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
96 downloadFile.on('error', err => {
97 logger.error('youtube-dl update error.', { err })
101 downloadFile.on('end', () => {
102 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
103 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
105 logger.error('youtube-dl update error: cannot write details.', { err })
109 logger.info('youtube-dl updated to version %s.', newVersion)
117 async function safeGetYoutubeDL () {
121 youtubeDL = require('youtube-dl')
124 await updateYoutubeDLBinary()
125 youtubeDL = require('youtube-dl')
131 // ---------------------------------------------------------------------------
134 updateYoutubeDLBinary,
135 downloadYoutubeDLVideo,
140 // ---------------------------------------------------------------------------
142 function normalizeObject (obj: any) {
143 const newObj: any = {}
145 for (const key of Object.keys(obj)) {
147 if (key === 'resolution') continue
149 const value = obj[key]
151 if (typeof value === 'string') {
152 newObj[key] = value.normalize()
161 function buildVideoInfo (obj: any) {
163 name: titleTruncation(obj.title),
164 description: descriptionTruncation(obj.description),
165 category: getCategory(obj.categories),
166 licence: getLicence(obj.license),
168 tags: getTags(obj.tags),
169 thumbnailUrl: obj.thumbnail || undefined
173 function titleTruncation (title: string) {
174 return truncate(title, {
175 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
181 function descriptionTruncation (description: string) {
182 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
184 return truncate(description, {
185 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
191 function isNSFW (info: any) {
192 return info.age_limit && info.age_limit >= 16
195 function getTags (tags: any) {
196 if (Array.isArray(tags) === false) return []
199 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
200 .map(t => t.normalize())
204 function getLicence (licence: string) {
205 if (!licence) return undefined
207 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
212 function getCategory (categories: string[]) {
213 if (!categories) return undefined
215 const categoryString = categories[0]
216 if (!categoryString || typeof categoryString !== 'string') return undefined
218 if (categoryString === 'News & Politics') return 11
220 for (const key of Object.keys(VIDEO_CATEGORIES)) {
221 const category = VIDEO_CATEGORIES[key]
222 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)