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 function getYoutubeDLInfo (url: string): Promise<YoutubeDLInfo> {
22 return new Promise<YoutubeDLInfo>(async (res, rej) => {
23 const options = [ '-j', '--flat-playlist' ]
25 const youtubeDL = await safeGetYoutubeDL()
26 youtubeDL.getInfo(url, options, (err, info) => {
27 if (err) return rej(err)
28 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
30 const obj = buildVideoInfo(normalizeObject(info))
31 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
38 function downloadYoutubeDLVideo (url: string) {
39 const path = generateVideoTmpPath(url)
41 logger.info('Importing youtubeDL video %s', url)
43 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
45 return new Promise<string>(async (res, rej) => {
46 const youtubeDL = await safeGetYoutubeDL()
47 youtubeDL.exec(url, options, err => {
48 if (err) return rej(err)
55 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
56 // We rewrote it to avoid sync calls
57 async function updateYoutubeDLBinary () {
58 logger.info('Updating youtubeDL binary.')
60 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
61 const bin = join(binDirectory, 'youtube-dl')
62 const detailsPath = join(binDirectory, 'details')
63 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
65 await ensureDir(binDirectory)
67 return new Promise(res => {
68 request.get(url, { followRedirect: false }, (err, result) => {
70 logger.error('Cannot update youtube-dl.', { err })
74 if (result.statusCode !== 302) {
75 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
79 const url = result.headers.location
80 const downloadFile = request.get(url)
81 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
83 downloadFile.on('response', result => {
84 if (result.statusCode !== 200) {
85 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
89 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
92 downloadFile.on('error', err => {
93 logger.error('youtube-dl update error.', { err })
97 downloadFile.on('end', () => {
98 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
99 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
101 logger.error('youtube-dl update error: cannot write details.', { err })
105 logger.info('youtube-dl updated to version %s.', newVersion)
113 // ---------------------------------------------------------------------------
116 updateYoutubeDLBinary,
117 downloadYoutubeDLVideo,
121 // ---------------------------------------------------------------------------
123 async function safeGetYoutubeDL () {
127 youtubeDL = require('youtube-dl')
130 await updateYoutubeDLBinary()
131 youtubeDL = require('youtube-dl')
137 function normalizeObject (obj: any) {
138 const newObj: any = {}
140 for (const key of Object.keys(obj)) {
142 if (key === 'resolution') continue
144 const value = obj[key]
146 if (typeof value === 'string') {
147 newObj[key] = value.normalize()
156 function buildVideoInfo (obj: any) {
158 name: titleTruncation(obj.title),
159 description: descriptionTruncation(obj.description),
160 category: getCategory(obj.categories),
161 licence: getLicence(obj.license),
163 tags: getTags(obj.tags),
164 thumbnailUrl: obj.thumbnail || undefined
168 function titleTruncation (title: string) {
169 return truncate(title, {
170 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
176 function descriptionTruncation (description: string) {
177 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
179 return truncate(description, {
180 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
186 function isNSFW (info: any) {
187 return info.age_limit && info.age_limit >= 16
190 function getTags (tags: any) {
191 if (Array.isArray(tags) === false) return []
194 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
195 .map(t => t.normalize())
199 function getLicence (licence: string) {
200 if (!licence) return undefined
202 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
207 function getCategory (categories: string[]) {
208 if (!categories) return undefined
210 const categoryString = categories[0]
211 if (!categoryString || typeof categoryString !== 'string') return undefined
213 if (categoryString === 'News & Politics') return 11
215 for (const key of Object.keys(VIDEO_CATEGORIES)) {
216 const category = VIDEO_CATEGORIES[key]
217 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)