1 import { truncate } from 'lodash'
2 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers/constants'
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?: 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 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
51 if (process.env.FFMPEG_PATH) {
52 options.push('--ffmpeg-location')
53 options.push(process.env.FFMPEG_PATH)
56 return new Promise<string>(async (res, rej) => {
57 const youtubeDL = await safeGetYoutubeDL()
58 youtubeDL.exec(url, options, processOptions, err => {
63 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
71 timer = setTimeout(async () => {
74 return rej(new Error('YoutubeDL download timeout.'))
79 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
80 // We rewrote it to avoid sync calls
81 async function updateYoutubeDLBinary () {
82 logger.info('Updating youtubeDL binary.')
84 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
85 const bin = join(binDirectory, 'youtube-dl')
86 const detailsPath = join(binDirectory, 'details')
87 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
89 await ensureDir(binDirectory)
91 return new Promise(res => {
92 request.get(url, { followRedirect: false }, (err, result) => {
94 logger.error('Cannot update youtube-dl.', { err })
98 if (result.statusCode !== 302) {
99 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
103 const url = result.headers.location
104 const downloadFile = request.get(url)
105 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
107 downloadFile.on('response', result => {
108 if (result.statusCode !== 200) {
109 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
113 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
116 downloadFile.on('error', err => {
117 logger.error('youtube-dl update error.', { err })
121 downloadFile.on('end', () => {
122 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
123 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
125 logger.error('youtube-dl update error: cannot write details.', { err })
129 logger.info('youtube-dl updated to version %s.', newVersion)
137 async function safeGetYoutubeDL () {
141 youtubeDL = require('youtube-dl')
144 await updateYoutubeDLBinary()
145 youtubeDL = require('youtube-dl')
151 function buildOriginallyPublishedAt (obj: any) {
152 let originallyPublishedAt: Date = null
154 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
155 if (uploadDateMatcher) {
156 originallyPublishedAt = new Date()
157 originallyPublishedAt.setHours(0, 0, 0, 0)
159 const year = parseInt(uploadDateMatcher[1], 10)
160 // Month starts from 0
161 const month = parseInt(uploadDateMatcher[2], 10) - 1
162 const day = parseInt(uploadDateMatcher[3], 10)
164 originallyPublishedAt.setFullYear(year, month, day)
167 return originallyPublishedAt
170 // ---------------------------------------------------------------------------
173 updateYoutubeDLBinary,
174 downloadYoutubeDLVideo,
177 buildOriginallyPublishedAt
180 // ---------------------------------------------------------------------------
182 function normalizeObject (obj: any) {
183 const newObj: any = {}
185 for (const key of Object.keys(obj)) {
187 if (key === 'resolution') continue
189 const value = obj[key]
191 if (typeof value === 'string') {
192 newObj[key] = value.normalize()
201 function buildVideoInfo (obj: any) {
203 name: titleTruncation(obj.title),
204 description: descriptionTruncation(obj.description),
205 category: getCategory(obj.categories),
206 licence: getLicence(obj.license),
208 tags: getTags(obj.tags),
209 thumbnailUrl: obj.thumbnail || undefined,
210 originallyPublishedAt: buildOriginallyPublishedAt(obj)
214 function titleTruncation (title: string) {
215 return truncate(title, {
216 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
222 function descriptionTruncation (description: string) {
223 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
225 return truncate(description, {
226 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
232 function isNSFW (info: any) {
233 return info.age_limit && info.age_limit >= 16
236 function getTags (tags: any) {
237 if (Array.isArray(tags) === false) return []
240 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
241 .map(t => t.normalize())
245 function getLicence (licence: string) {
246 if (!licence) return undefined
248 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
253 function getCategory (categories: string[]) {
254 if (!categories) return undefined
256 const categoryString = categories[0]
257 if (!categoryString || typeof categoryString !== 'string') return undefined
259 if (categoryString === 'News & Politics') return 11
261 for (const key of Object.keys(VIDEO_CATEGORIES)) {
262 const category = VIDEO_CATEGORIES[key]
263 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)