]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/youtube-dl.ts
Merge branch 'release/3.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
1 import { createWriteStream } from 'fs'
2 import { ensureDir, move, pathExists, remove, writeFile } from 'fs-extra'
3 import got from 'got'
4 import { join } from 'path'
5 import { CONFIG } from '@server/initializers/config'
6 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
7 import { VideoResolution } from '../../shared/models/videos'
8 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
9 import { getEnabledResolutions } from '../lib/video-transcoding'
10 import { peertubeTruncate, pipelinePromise, root } from './core-utils'
11 import { isVideoFileExtnameValid } from './custom-validators/videos'
12 import { logger } from './logger'
13 import { generateVideoImportTmpPath } from './utils'
14
15 export type YoutubeDLInfo = {
16 name?: string
17 description?: string
18 category?: number
19 language?: string
20 licence?: number
21 nsfw?: boolean
22 tags?: string[]
23 thumbnailUrl?: string
24 ext?: string
25 originallyPublishedAt?: Date
26 }
27
28 export type YoutubeDLSubs = {
29 language: string
30 filename: string
31 path: string
32 }[]
33
34 const processOptions = {
35 maxBuffer: 1024 * 1024 * 10 // 10MB
36 }
37
38 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
39 return new Promise<YoutubeDLInfo>((res, rej) => {
40 let args = opts || [ '-j', '--flat-playlist' ]
41
42 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) {
43 args.push('--force-ipv4')
44 }
45
46 args = wrapWithProxyOptions(args)
47 args = [ '-f', getYoutubeDLVideoFormat() ].concat(args)
48
49 safeGetYoutubeDL()
50 .then(youtubeDL => {
51 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
52 if (err) return rej(err)
53 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
54
55 const obj = buildVideoInfo(normalizeObject(info))
56 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
57
58 return res(obj)
59 })
60 })
61 .catch(err => rej(err))
62 })
63 }
64
65 function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
66 return new Promise<YoutubeDLSubs>((res, rej) => {
67 const cwd = CONFIG.STORAGE.TMP_DIR
68 const options = opts || { all: true, format: 'vtt', cwd }
69
70 safeGetYoutubeDL()
71 .then(youtubeDL => {
72 youtubeDL.getSubs(url, options, (err, files) => {
73 if (err) return rej(err)
74 if (!files) return []
75
76 logger.debug('Get subtitles from youtube dl.', { url, files })
77
78 const subtitles = files.reduce((acc, filename) => {
79 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
80 if (!matched || !matched[1]) return acc
81
82 return [
83 ...acc,
84 {
85 language: matched[1],
86 path: join(cwd, filename),
87 filename
88 }
89 ]
90 }, [])
91
92 return res(subtitles)
93 })
94 })
95 .catch(err => rej(err))
96 })
97 }
98
99 function getYoutubeDLVideoFormat () {
100 /**
101 * list of format selectors in order or preference
102 * see https://github.com/ytdl-org/youtube-dl#format-selection
103 *
104 * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope
105 * of being able to do a "quick-transcode"
106 * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9)
107 * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback
108 *
109 * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499
110 **/
111 const enabledResolutions = getEnabledResolutions('vod')
112 const resolution = enabledResolutions.length === 0
113 ? VideoResolution.H_720P
114 : Math.max(...enabledResolutions)
115
116 return [
117 `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1
118 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2
119 `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]`, // case #3
120 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio`,
121 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats
122 'best' // Ultimate fallback
123 ].join('/')
124 }
125
126 function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number) {
127 // Leave empty the extension, youtube-dl will add it
128 const pathWithoutExtension = generateVideoImportTmpPath(url, '')
129
130 let timer
131
132 logger.info('Importing youtubeDL video %s to %s', url, pathWithoutExtension)
133
134 let options = [ '-f', getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ]
135 options = wrapWithProxyOptions(options)
136
137 if (process.env.FFMPEG_PATH) {
138 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
139 }
140
141 logger.debug('YoutubeDL options for %s.', url, { options })
142
143 return new Promise<string>((res, rej) => {
144 safeGetYoutubeDL()
145 .then(youtubeDL => {
146 youtubeDL.exec(url, options, processOptions, async err => {
147 clearTimeout(timer)
148
149 try {
150 // If youtube-dl did not guess an extension for our file, just use .mp4 as default
151 if (await pathExists(pathWithoutExtension)) {
152 await move(pathWithoutExtension, pathWithoutExtension + '.mp4')
153 }
154
155 const path = await guessVideoPathWithExtension(pathWithoutExtension, fileExt)
156
157 if (err) {
158 remove(path)
159 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
160
161 return rej(err)
162 }
163
164 return res(path)
165 } catch (err) {
166 return rej(err)
167 }
168 })
169
170 timer = setTimeout(() => {
171 const err = new Error('YoutubeDL download timeout.')
172
173 guessVideoPathWithExtension(pathWithoutExtension, fileExt)
174 .then(path => remove(path))
175 .finally(() => rej(err))
176 .catch(err => {
177 logger.error('Cannot remove file in youtubeDL timeout.', { err })
178 return rej(err)
179 })
180 }, timeout)
181 })
182 .catch(err => rej(err))
183 })
184 }
185
186 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
187 // We rewrote it to avoid sync calls
188 async function updateYoutubeDLBinary () {
189 logger.info('Updating youtubeDL binary.')
190
191 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
192 const bin = join(binDirectory, 'youtube-dl')
193 const detailsPath = join(binDirectory, 'details')
194 const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl'
195
196 await ensureDir(binDirectory)
197
198 try {
199 const result = await got(url, { followRedirect: false })
200
201 if (result.statusCode !== HttpStatusCode.FOUND_302) {
202 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
203 return
204 }
205
206 const newUrl = result.headers.location
207 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(newUrl)[1]
208
209 const downloadFileStream = got.stream(newUrl)
210 const writeStream = createWriteStream(bin, { mode: 493 })
211
212 await pipelinePromise(
213 downloadFileStream,
214 writeStream
215 )
216
217 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
218 await writeFile(detailsPath, details, { encoding: 'utf8' })
219
220 logger.info('youtube-dl updated to version %s.', newVersion)
221 } catch (err) {
222 logger.error('Cannot update youtube-dl.', { err })
223 }
224 }
225
226 async function safeGetYoutubeDL () {
227 let youtubeDL
228
229 try {
230 youtubeDL = require('youtube-dl')
231 } catch (e) {
232 // Download binary
233 await updateYoutubeDLBinary()
234 youtubeDL = require('youtube-dl')
235 }
236
237 return youtubeDL
238 }
239
240 function buildOriginallyPublishedAt (obj: any) {
241 let originallyPublishedAt: Date = null
242
243 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
244 if (uploadDateMatcher) {
245 originallyPublishedAt = new Date()
246 originallyPublishedAt.setHours(0, 0, 0, 0)
247
248 const year = parseInt(uploadDateMatcher[1], 10)
249 // Month starts from 0
250 const month = parseInt(uploadDateMatcher[2], 10) - 1
251 const day = parseInt(uploadDateMatcher[3], 10)
252
253 originallyPublishedAt.setFullYear(year, month, day)
254 }
255
256 return originallyPublishedAt
257 }
258
259 // ---------------------------------------------------------------------------
260
261 export {
262 updateYoutubeDLBinary,
263 getYoutubeDLVideoFormat,
264 downloadYoutubeDLVideo,
265 getYoutubeDLSubs,
266 getYoutubeDLInfo,
267 safeGetYoutubeDL,
268 buildOriginallyPublishedAt
269 }
270
271 // ---------------------------------------------------------------------------
272
273 async function guessVideoPathWithExtension (tmpPath: string, sourceExt: string) {
274 if (!isVideoFileExtnameValid(sourceExt)) {
275 throw new Error('Invalid video extension ' + sourceExt)
276 }
277
278 const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ]
279
280 for (const extension of extensions) {
281 const path = tmpPath + extension
282
283 if (await pathExists(path)) return path
284 }
285
286 throw new Error('Cannot guess path of ' + tmpPath)
287 }
288
289 function normalizeObject (obj: any) {
290 const newObj: any = {}
291
292 for (const key of Object.keys(obj)) {
293 // Deprecated key
294 if (key === 'resolution') continue
295
296 const value = obj[key]
297
298 if (typeof value === 'string') {
299 newObj[key] = value.normalize()
300 } else {
301 newObj[key] = value
302 }
303 }
304
305 return newObj
306 }
307
308 function buildVideoInfo (obj: any): YoutubeDLInfo {
309 return {
310 name: titleTruncation(obj.title),
311 description: descriptionTruncation(obj.description),
312 category: getCategory(obj.categories),
313 licence: getLicence(obj.license),
314 language: getLanguage(obj.language),
315 nsfw: isNSFW(obj),
316 tags: getTags(obj.tags),
317 thumbnailUrl: obj.thumbnail || undefined,
318 originallyPublishedAt: buildOriginallyPublishedAt(obj),
319 ext: obj.ext
320 }
321 }
322
323 function titleTruncation (title: string) {
324 return peertubeTruncate(title, {
325 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
326 separator: /,? +/,
327 omission: ' […]'
328 })
329 }
330
331 function descriptionTruncation (description: string) {
332 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
333
334 return peertubeTruncate(description, {
335 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
336 separator: /,? +/,
337 omission: ' […]'
338 })
339 }
340
341 function isNSFW (info: any) {
342 return info.age_limit && info.age_limit >= 16
343 }
344
345 function getTags (tags: any) {
346 if (Array.isArray(tags) === false) return []
347
348 return tags
349 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
350 .map(t => t.normalize())
351 .slice(0, 5)
352 }
353
354 function getLicence (licence: string) {
355 if (!licence) return undefined
356
357 if (licence.includes('Creative Commons Attribution')) return 1
358
359 for (const key of Object.keys(VIDEO_LICENCES)) {
360 const peertubeLicence = VIDEO_LICENCES[key]
361 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
362 }
363
364 return undefined
365 }
366
367 function getCategory (categories: string[]) {
368 if (!categories) return undefined
369
370 const categoryString = categories[0]
371 if (!categoryString || typeof categoryString !== 'string') return undefined
372
373 if (categoryString === 'News & Politics') return 11
374
375 for (const key of Object.keys(VIDEO_CATEGORIES)) {
376 const category = VIDEO_CATEGORIES[key]
377 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
378 }
379
380 return undefined
381 }
382
383 function getLanguage (language: string) {
384 return VIDEO_LANGUAGES[language] ? language : undefined
385 }
386
387 function wrapWithProxyOptions (options: string[]) {
388 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
389 logger.debug('Using proxy for YoutubeDL')
390
391 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)
392 }
393
394 return options
395 }