1 import * as youtubeDL from 'youtube-dl'
2 import { truncate } from 'lodash'
3 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers'
4 import { logger } from './logger'
5 import { generateVideoTmpPath } from './utils'
7 export type YoutubeDLInfo = {
17 function getYoutubeDLInfo (url: string): Promise<YoutubeDLInfo> {
18 return new Promise<YoutubeDLInfo>((res, rej) => {
19 const options = [ '-j', '--flat-playlist' ]
21 youtubeDL.getInfo(url, options, (err, info) => {
22 if (err) return rej(err)
24 const obj = normalizeObject(info)
26 return res(buildVideoInfo(obj))
31 function downloadYoutubeDLVideo (url: string) {
32 const path = generateVideoTmpPath(url)
34 logger.info('Importing youtubeDL video %s', url)
36 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
38 return new Promise<string>((res, rej) => {
39 youtubeDL.exec(url, options, async (err, output) => {
40 if (err) return rej(err)
47 // ---------------------------------------------------------------------------
50 downloadYoutubeDLVideo,
54 // ---------------------------------------------------------------------------
56 function normalizeObject (obj: any) {
57 const newObj: any = {}
59 for (const key of Object.keys(obj)) {
61 if (key === 'resolution') continue
63 const value = obj[key]
65 if (typeof value === 'string') {
66 newObj[key] = value.normalize()
75 function buildVideoInfo (obj: any) {
77 name: titleTruncation(obj.title),
78 description: descriptionTruncation(obj.description),
79 category: getCategory(obj.categories),
80 licence: getLicence(obj.license),
82 tags: getTags(obj.tags),
83 thumbnailUrl: obj.thumbnail || undefined
87 function titleTruncation (title: string) {
88 return truncate(title, {
89 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
95 function descriptionTruncation (description: string) {
96 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
98 return truncate(description, {
99 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
105 function isNSFW (info: any) {
106 return info.age_limit && info.age_limit >= 16
109 function getTags (tags: any) {
110 if (Array.isArray(tags) === false) return []
113 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
114 .map(t => t.normalize())
118 function getLicence (licence: string) {
119 if (!licence) return undefined
121 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
126 function getCategory (categories: string[]) {
127 if (!categories) return undefined
129 const categoryString = categories[0]
130 if (!categoryString || typeof categoryString !== 'string') return undefined
132 if (categoryString === 'News & Politics') return 11
134 for (const key of Object.keys(VIDEO_CATEGORIES)) {
135 const category = VIDEO_CATEGORIES[key]
136 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)