Fix video import with URL with small titles
[oweals/peertube.git] / server / helpers / youtube-dl.ts
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 { YoutubeDlUpdateScheduler } from '../lib/schedulers/youtube-dl-update-scheduler'
6
7 export type YoutubeDLInfo = {
8   name?: string
9   description?: string
10   category?: number
11   licence?: number
12   nsfw?: boolean
13   tags?: string[]
14   thumbnailUrl?: string
15 }
16
17 function getYoutubeDLInfo (url: string): Promise<YoutubeDLInfo> {
18   return new Promise<YoutubeDLInfo>(async (res, rej) => {
19     const options = [ '-j', '--flat-playlist' ]
20
21     const youtubeDL = await safeGetYoutubeDL()
22     youtubeDL.getInfo(url, options, (err, info) => {
23       if (err) return rej(err)
24
25       const obj = buildVideoInfo(normalizeObject(info))
26       if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
27
28       return res(obj)
29     })
30   })
31 }
32
33 function downloadYoutubeDLVideo (url: string) {
34   const path = generateVideoTmpPath(url)
35
36   logger.info('Importing youtubeDL video %s', url)
37
38   const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
39
40   return new Promise<string>(async (res, rej) => {
41     const youtubeDL = await safeGetYoutubeDL()
42     youtubeDL.exec(url, options, async (err, output) => {
43       if (err) return rej(err)
44
45       return res(path)
46     })
47   })
48 }
49
50 // ---------------------------------------------------------------------------
51
52 export {
53   downloadYoutubeDLVideo,
54   getYoutubeDLInfo
55 }
56
57 // ---------------------------------------------------------------------------
58
59 async function safeGetYoutubeDL () {
60   let youtubeDL
61
62   try {
63     youtubeDL = require('youtube-dl')
64   } catch (e) {
65     // Download binary
66     await YoutubeDlUpdateScheduler.Instance.execute()
67     youtubeDL = require('youtube-dl')
68   }
69
70   return youtubeDL
71 }
72
73 function normalizeObject (obj: any) {
74   const newObj: any = {}
75
76   for (const key of Object.keys(obj)) {
77     // Deprecated key
78     if (key === 'resolution') continue
79
80     const value = obj[key]
81
82     if (typeof value === 'string') {
83       newObj[key] = value.normalize()
84     } else {
85       newObj[key] = value
86     }
87   }
88
89   return newObj
90 }
91
92 function buildVideoInfo (obj: any) {
93   return {
94     name: titleTruncation(obj.title),
95     description: descriptionTruncation(obj.description),
96     category: getCategory(obj.categories),
97     licence: getLicence(obj.license),
98     nsfw: isNSFW(obj),
99     tags: getTags(obj.tags),
100     thumbnailUrl: obj.thumbnail || undefined
101   }
102 }
103
104 function titleTruncation (title: string) {
105   return truncate(title, {
106     'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
107     'separator': /,? +/,
108     'omission': ' […]'
109   })
110 }
111
112 function descriptionTruncation (description: string) {
113   if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
114
115   return truncate(description, {
116     'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
117     'separator': /,? +/,
118     'omission': ' […]'
119   })
120 }
121
122 function isNSFW (info: any) {
123   return info.age_limit && info.age_limit >= 16
124 }
125
126 function getTags (tags: any) {
127   if (Array.isArray(tags) === false) return []
128
129   return tags
130     .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
131     .map(t => t.normalize())
132     .slice(0, 5)
133 }
134
135 function getLicence (licence: string) {
136   if (!licence) return undefined
137
138   if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
139
140   return undefined
141 }
142
143 function getCategory (categories: string[]) {
144   if (!categories) return undefined
145
146   const categoryString = categories[0]
147   if (!categoryString || typeof categoryString !== 'string') return undefined
148
149   if (categoryString === 'News & Politics') return 11
150
151   for (const key of Object.keys(VIDEO_CATEGORIES)) {
152     const category = VIDEO_CATEGORIES[key]
153     if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
154   }
155
156   return undefined
157 }