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