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