1 import { truncate } from 'lodash'
2 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers'
3 import { logger } from './logger'
4 import { generateVideoImportTmpPath } from './utils'
5 import { join } from 'path'
6 import { root } from './core-utils'
7 import { ensureDir, writeFile, remove } from 'fs-extra'
8 import * as request from 'request'
9 import { createWriteStream } from 'fs'
11 export type YoutubeDLInfo = {
19 originallyPublishedAt?: string
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 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
51 return new Promise<string>(async (res, rej) => {
52 const youtubeDL = await safeGetYoutubeDL()
53 youtubeDL.exec(url, options, processOptions, err => {
58 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
66 timer = setTimeout(async () => {
69 return rej(new Error('YoutubeDL download timeout.'))
74 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
75 // We rewrote it to avoid sync calls
76 async function updateYoutubeDLBinary () {
77 logger.info('Updating youtubeDL binary.')
79 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
80 const bin = join(binDirectory, 'youtube-dl')
81 const detailsPath = join(binDirectory, 'details')
82 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
84 await ensureDir(binDirectory)
86 return new Promise(res => {
87 request.get(url, { followRedirect: false }, (err, result) => {
89 logger.error('Cannot update youtube-dl.', { err })
93 if (result.statusCode !== 302) {
94 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
98 const url = result.headers.location
99 const downloadFile = request.get(url)
100 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
102 downloadFile.on('response', result => {
103 if (result.statusCode !== 200) {
104 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
108 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
111 downloadFile.on('error', err => {
112 logger.error('youtube-dl update error.', { err })
116 downloadFile.on('end', () => {
117 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
118 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
120 logger.error('youtube-dl update error: cannot write details.', { err })
124 logger.info('youtube-dl updated to version %s.', newVersion)
132 async function safeGetYoutubeDL () {
136 youtubeDL = require('youtube-dl')
139 await updateYoutubeDLBinary()
140 youtubeDL = require('youtube-dl')
146 // ---------------------------------------------------------------------------
149 updateYoutubeDLBinary,
150 downloadYoutubeDLVideo,
155 // ---------------------------------------------------------------------------
157 function normalizeObject (obj: any) {
158 const newObj: any = {}
160 for (const key of Object.keys(obj)) {
162 if (key === 'resolution') continue
164 const value = obj[key]
166 if (typeof value === 'string') {
167 newObj[key] = value.normalize()
176 function buildVideoInfo (obj: any) {
178 const date = obj.upload_date.slice(0,4)+","+obj.upload_date.slice(4,6)+","+obj.upload_date.slice(6,8)
181 name: titleTruncation(obj.title),
182 description: descriptionTruncation(obj.description),
183 category: getCategory(obj.categories),
184 licence: getLicence(obj.license),
186 tags: getTags(obj.tags),
187 thumbnailUrl: obj.thumbnail || undefined,
188 originallyPublishedAt: new Date(date).toISOString()
192 function titleTruncation (title: string) {
193 return truncate(title, {
194 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
200 function descriptionTruncation (description: string) {
201 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
203 return truncate(description, {
204 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
210 function isNSFW (info: any) {
211 return info.age_limit && info.age_limit >= 16
214 function getTags (tags: any) {
215 if (Array.isArray(tags) === false) return []
218 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
219 .map(t => t.normalize())
223 function getLicence (licence: string) {
224 if (!licence) return undefined
226 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
231 function getCategory (categories: string[]) {
232 if (!categories) return undefined
234 const categoryString = categories[0]
235 if (!categoryString || typeof categoryString !== 'string') return undefined
237 if (categoryString === 'News & Politics') return 11
239 for (const key of Object.keys(VIDEO_CATEGORIES)) {
240 const category = VIDEO_CATEGORIES[key]
241 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)