2014aab0a486ae5f0007bbb35c638594e6f6a95c
[oweals/peertube.git] / server / helpers / youtube-dl.ts
1 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
2 import { logger } from './logger'
3 import { generateVideoImportTmpPath } from './utils'
4 import { join } from 'path'
5 import { peertubeTruncate, root } from './core-utils'
6 import { ensureDir, remove, writeFile } from 'fs-extra'
7 import * as request from 'request'
8 import { createWriteStream } from 'fs'
9 import { CONFIG } from '@server/initializers/config'
10
11 export type YoutubeDLInfo = {
12   name?: string
13   description?: string
14   category?: number
15   language?: string
16   licence?: number
17   nsfw?: boolean
18   tags?: string[]
19   thumbnailUrl?: string
20   fileExt?: string
21   originallyPublishedAt?: Date
22 }
23
24 export type YoutubeDLSubs = {
25   language: string
26   filename: string
27   path: string
28 }[]
29
30 const processOptions = {
31   maxBuffer: 1024 * 1024 * 10 // 10MB
32 }
33
34 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
35   return new Promise<YoutubeDLInfo>((res, rej) => {
36     let args = opts || [ '-j', '--flat-playlist' ]
37     args = wrapWithProxyOptions(args)
38
39     safeGetYoutubeDL()
40       .then(youtubeDL => {
41         youtubeDL.getInfo(url, args, processOptions, (err, info) => {
42           if (err) return rej(err)
43           if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
44
45           const obj = buildVideoInfo(normalizeObject(info))
46           if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
47
48           return res(obj)
49         })
50       })
51       .catch(err => rej(err))
52   })
53 }
54
55 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
56   return new Promise<YoutubeDLSubs>((res, rej) => {
57     const cwd = CONFIG.STORAGE.TMP_DIR
58     const options = opts || { all: true, format: 'vtt', cwd }
59
60     safeGetYoutubeDL()
61       .then(youtubeDL => {
62         youtubeDL.getSubs(url, options, (err, files) => {
63           if (err) return rej(err)
64           if (!files) return []
65
66           logger.debug('Get subtitles from youtube dl.', { url, files })
67
68           const subtitles = files.reduce((acc, filename) => {
69             const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
70
71             if (matched[1]) {
72               return [
73                 ...acc,
74                 {
75                   language: matched[1],
76                   path: join(cwd, filename),
77                   filename
78                 }
79               ]
80             }
81           }, [])
82
83           return res(subtitles)
84         })
85       })
86       .catch(err => rej(err))
87   })
88 }
89
90 function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) {
91   const path = generateVideoImportTmpPath(url, extension)
92   let timer
93
94   logger.info('Importing youtubeDL video %s to %s', url, path)
95
96   let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
97   options = wrapWithProxyOptions(options)
98
99   if (process.env.FFMPEG_PATH) {
100     options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
101   }
102
103   return new Promise<string>((res, rej) => {
104     safeGetYoutubeDL()
105       .then(youtubeDL => {
106         youtubeDL.exec(url, options, processOptions, err => {
107           clearTimeout(timer)
108
109           if (err) {
110             remove(path)
111               .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
112
113             return rej(err)
114           }
115
116           return res(path)
117         })
118
119         timer = setTimeout(() => {
120           const err = new Error('YoutubeDL download timeout.')
121
122           remove(path)
123             .finally(() => rej(err))
124             .catch(err => {
125               logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
126               return rej(err)
127             })
128         }, timeout)
129       })
130       .catch(err => rej(err))
131   })
132 }
133
134 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
135 // We rewrote it to avoid sync calls
136 async function updateYoutubeDLBinary () {
137   logger.info('Updating youtubeDL binary.')
138
139   const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
140   const bin = join(binDirectory, 'youtube-dl')
141   const detailsPath = join(binDirectory, 'details')
142   const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
143
144   await ensureDir(binDirectory)
145
146   return new Promise(res => {
147     request.get(url, { followRedirect: false }, (err, result) => {
148       if (err) {
149         logger.error('Cannot update youtube-dl.', { err })
150         return res()
151       }
152
153       if (result.statusCode !== 302) {
154         logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
155         return res()
156       }
157
158       const url = result.headers.location
159       const downloadFile = request.get(url)
160       const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
161
162       downloadFile.on('response', result => {
163         if (result.statusCode !== 200) {
164           logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
165           return res()
166         }
167
168         downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
169       })
170
171       downloadFile.on('error', err => {
172         logger.error('youtube-dl update error.', { err })
173         return res()
174       })
175
176       downloadFile.on('end', () => {
177         const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
178         writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
179           if (err) {
180             logger.error('youtube-dl update error: cannot write details.', { err })
181             return res()
182           }
183
184           logger.info('youtube-dl updated to version %s.', newVersion)
185           return res()
186         })
187       })
188     })
189   })
190 }
191
192 async function safeGetYoutubeDL () {
193   let youtubeDL
194
195   try {
196     youtubeDL = require('youtube-dl')
197   } catch (e) {
198     // Download binary
199     await updateYoutubeDLBinary()
200     youtubeDL = require('youtube-dl')
201   }
202
203   return youtubeDL
204 }
205
206 function buildOriginallyPublishedAt (obj: any) {
207   let originallyPublishedAt: Date = null
208
209   const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
210   if (uploadDateMatcher) {
211     originallyPublishedAt = new Date()
212     originallyPublishedAt.setHours(0, 0, 0, 0)
213
214     const year = parseInt(uploadDateMatcher[1], 10)
215     // Month starts from 0
216     const month = parseInt(uploadDateMatcher[2], 10) - 1
217     const day = parseInt(uploadDateMatcher[3], 10)
218
219     originallyPublishedAt.setFullYear(year, month, day)
220   }
221
222   return originallyPublishedAt
223 }
224
225 // ---------------------------------------------------------------------------
226
227 export {
228   updateYoutubeDLBinary,
229   downloadYoutubeDLVideo,
230   getYoutubeDLSubs,
231   getYoutubeDLInfo,
232   safeGetYoutubeDL,
233   buildOriginallyPublishedAt
234 }
235
236 // ---------------------------------------------------------------------------
237
238 function normalizeObject (obj: any) {
239   const newObj: any = {}
240
241   for (const key of Object.keys(obj)) {
242     // Deprecated key
243     if (key === 'resolution') continue
244
245     const value = obj[key]
246
247     if (typeof value === 'string') {
248       newObj[key] = value.normalize()
249     } else {
250       newObj[key] = value
251     }
252   }
253
254   return newObj
255 }
256
257 function buildVideoInfo (obj: any): YoutubeDLInfo {
258   return {
259     name: titleTruncation(obj.title),
260     description: descriptionTruncation(obj.description),
261     category: getCategory(obj.categories),
262     licence: getLicence(obj.license),
263     language: getLanguage(obj.language),
264     nsfw: isNSFW(obj),
265     tags: getTags(obj.tags),
266     thumbnailUrl: obj.thumbnail || undefined,
267     originallyPublishedAt: buildOriginallyPublishedAt(obj),
268     fileExt: obj.ext
269   }
270 }
271
272 function titleTruncation (title: string) {
273   return peertubeTruncate(title, {
274     length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
275     separator: /,? +/,
276     omission: ' […]'
277   })
278 }
279
280 function descriptionTruncation (description: string) {
281   if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
282
283   return peertubeTruncate(description, {
284     length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
285     separator: /,? +/,
286     omission: ' […]'
287   })
288 }
289
290 function isNSFW (info: any) {
291   return info.age_limit && info.age_limit >= 16
292 }
293
294 function getTags (tags: any) {
295   if (Array.isArray(tags) === false) return []
296
297   return tags
298     .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
299     .map(t => t.normalize())
300     .slice(0, 5)
301 }
302
303 function getLicence (licence: string) {
304   if (!licence) return undefined
305
306   if (licence.includes('Creative Commons Attribution')) return 1
307
308   for (const key of Object.keys(VIDEO_LICENCES)) {
309     const peertubeLicence = VIDEO_LICENCES[key]
310     if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
311   }
312
313   return undefined
314 }
315
316 function getCategory (categories: string[]) {
317   if (!categories) return undefined
318
319   const categoryString = categories[0]
320   if (!categoryString || typeof categoryString !== 'string') return undefined
321
322   if (categoryString === 'News & Politics') return 11
323
324   for (const key of Object.keys(VIDEO_CATEGORIES)) {
325     const category = VIDEO_CATEGORIES[key]
326     if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
327   }
328
329   return undefined
330 }
331
332 function getLanguage (language: string) {
333   return VIDEO_LANGUAGES[language] ? language : undefined
334 }
335
336 function wrapWithProxyOptions (options: string[]) {
337   if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
338     logger.debug('Using proxy for YoutubeDL')
339
340     return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)
341   }
342
343   return options
344 }