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