]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/youtube-dl.ts
move from trending routes to alg param
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
CommitLineData
805b8619 1import { createWriteStream } from 'fs'
86f553fb 2import { ensureDir, move, pathExists, remove, writeFile } from 'fs-extra'
606c946e 3import { join } from 'path'
606c946e 4import * as request from 'request'
be7ca0c6 5import { CONFIG } from '@server/initializers/config'
f2eb23cd 6import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
454c20fa 7import { VideoResolution } from '../../shared/models/videos'
805b8619
C
8import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
9import { getEnabledResolutions } from '../lib/video-transcoding'
10import { peertubeTruncate, root } from './core-utils'
11import { isVideoFileExtnameValid } from './custom-validators/videos'
12import { logger } from './logger'
13import { generateVideoImportTmpPath } from './utils'
fbad87b0
C
14
15export type YoutubeDLInfo = {
ce33919c
C
16 name?: string
17 description?: string
18 category?: number
86ad0cde 19 language?: string
ce33919c
C
20 licence?: number
21 nsfw?: boolean
22 tags?: string[]
23 thumbnailUrl?: string
454c20fa 24 ext?: string
c74c9be9 25 originallyPublishedAt?: Date
fbad87b0
C
26}
27
50ad0a1c 28export type YoutubeDLSubs = {
652c6416
C
29 language: string
30 filename: string
50ad0a1c 31 path: string
32}[]
33
cc680494
C
34const processOptions = {
35 maxBuffer: 1024 * 1024 * 10 // 10MB
36}
37
8704acf4 38function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
a1587156 39 return new Promise<YoutubeDLInfo>((res, rej) => {
93905586 40 let args = opts || [ '-j', '--flat-playlist' ]
e0409585
C
41
42 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) {
43 args.push('--force-ipv4')
44 }
45
93905586 46 args = wrapWithProxyOptions(args)
454c20fa 47 args = [ '-f', getYoutubeDLVideoFormat() ].concat(args)
fbad87b0 48
a1587156
C
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.'))
fbad87b0 54
a1587156
C
55 const obj = buildVideoInfo(normalizeObject(info))
56 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
fbad87b0 57
a1587156
C
58 return res(obj)
59 })
60 })
61 .catch(err => rej(err))
fbad87b0
C
62 })
63}
64
50ad0a1c 65function 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)
c7763edd 74 if (!files) return []
50ad0a1c 75
652c6416
C
76 logger.debug('Get subtitles from youtube dl.', { url, files })
77
50ad0a1c 78 const subtitles = files.reduce((acc, filename) => {
79 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
982f2fc9 80 if (!matched || !matched[1]) return acc
50ad0a1c 81
982f2fc9
C
82 return [
83 ...acc,
84 {
85 language: matched[1],
86 path: join(cwd, filename),
87 filename
88 }
89 ]
50ad0a1c 90 }, [])
91
92 return res(subtitles)
93 })
94 })
95 .catch(err => rej(err))
96 })
97}
98
454c20fa
RK
99function 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`,
a8a63b1f
C
121 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats
122 'best' // Ultimate fallback
454c20fa
RK
123 ].join('/')
124}
125
805b8619
C
126function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number) {
127 // Leave empty the extension, youtube-dl will add it
128 const pathWithoutExtension = generateVideoImportTmpPath(url, '')
969e59d1 129
cf9166cf 130 let timer
fbad87b0 131
805b8619 132 logger.info('Importing youtubeDL video %s to %s', url, pathWithoutExtension)
fbad87b0 133
805b8619 134 let options = [ '-f', getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ]
93905586 135 options = wrapWithProxyOptions(options)
fbad87b0 136
5322589d 137 if (process.env.FFMPEG_PATH) {
be7ca0c6 138 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
5322589d
C
139 }
140
969e59d1
C
141 logger.debug('YoutubeDL options for %s.', url, { options })
142
a1587156
C
143 return new Promise<string>((res, rej) => {
144 safeGetYoutubeDL()
145 .then(youtubeDL => {
805b8619 146 youtubeDL.exec(url, options, processOptions, async err => {
a1587156 147 clearTimeout(timer)
cf9166cf 148
805b8619 149 try {
86f553fb
C
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
805b8619
C
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 }))
cf9166cf 160
805b8619
C
161 return rej(err)
162 }
163
164 return res(path)
165 } catch (err) {
a1587156
C
166 return rej(err)
167 }
a1587156 168 })
cf9166cf 169
a1587156
C
170 timer = setTimeout(() => {
171 const err = new Error('YoutubeDL download timeout.')
cf9166cf 172
805b8619
C
173 guessVideoPathWithExtension(pathWithoutExtension, fileExt)
174 .then(path => remove(path))
a1587156
C
175 .finally(() => rej(err))
176 .catch(err => {
805b8619 177 logger.error('Cannot remove file in youtubeDL timeout.', { err })
a1587156
C
178 return rej(err)
179 })
180 }, timeout)
181 })
182 .catch(err => rej(err))
fbad87b0
C
183 })
184}
185
606c946e
C
186// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
187// We rewrote it to avoid sync calls
188async 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')
44fb5297 194 const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl'
606c946e
C
195
196 await ensureDir(binDirectory)
197
198 return new Promise(res => {
199 request.get(url, { followRedirect: false }, (err, result) => {
200 if (err) {
201 logger.error('Cannot update youtube-dl.', { err })
202 return res()
203 }
204
f2eb23cd 205 if (result.statusCode !== HttpStatusCode.FOUND_302) {
606c946e
C
206 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
207 return res()
208 }
209
210 const url = result.headers.location
211 const downloadFile = request.get(url)
a1587156 212 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
606c946e
C
213
214 downloadFile.on('response', result => {
f2eb23cd 215 if (result.statusCode !== HttpStatusCode.OK_200) {
606c946e
C
216 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
217 return res()
218 }
219
027e3080
C
220 const writeStream = createWriteStream(bin, { mode: 493 }).on('error', err => {
221 logger.error('youtube-dl update error in write stream', { err })
222 return res()
223 })
224
225 downloadFile.pipe(writeStream)
606c946e
C
226 })
227
228 downloadFile.on('error', err => {
229 logger.error('youtube-dl update error.', { err })
230 return res()
231 })
232
233 downloadFile.on('end', () => {
234 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
235 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
236 if (err) {
237 logger.error('youtube-dl update error: cannot write details.', { err })
238 return res()
239 }
240
241 logger.info('youtube-dl updated to version %s.', newVersion)
242 return res()
243 })
244 })
245 })
246 })
247}
248
4f1f6f03
C
249async function safeGetYoutubeDL () {
250 let youtubeDL
251
252 try {
253 youtubeDL = require('youtube-dl')
254 } catch (e) {
255 // Download binary
606c946e 256 await updateYoutubeDLBinary()
4f1f6f03
C
257 youtubeDL = require('youtube-dl')
258 }
259
260 return youtubeDL
261}
262
c74c9be9
C
263function buildOriginallyPublishedAt (obj: any) {
264 let originallyPublishedAt: Date = null
265
266 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
267 if (uploadDateMatcher) {
268 originallyPublishedAt = new Date()
269 originallyPublishedAt.setHours(0, 0, 0, 0)
270
271 const year = parseInt(uploadDateMatcher[1], 10)
272 // Month starts from 0
273 const month = parseInt(uploadDateMatcher[2], 10) - 1
274 const day = parseInt(uploadDateMatcher[3], 10)
275
276 originallyPublishedAt.setFullYear(year, month, day)
277 }
278
279 return originallyPublishedAt
280}
281
8704acf4
RK
282// ---------------------------------------------------------------------------
283
284export {
0491173a 285 updateYoutubeDLBinary,
454c20fa 286 getYoutubeDLVideoFormat,
8704acf4 287 downloadYoutubeDLVideo,
50ad0a1c 288 getYoutubeDLSubs,
8704acf4 289 getYoutubeDLInfo,
c74c9be9
C
290 safeGetYoutubeDL,
291 buildOriginallyPublishedAt
8704acf4
RK
292}
293
294// ---------------------------------------------------------------------------
295
805b8619
C
296async function guessVideoPathWithExtension (tmpPath: string, sourceExt: string) {
297 if (!isVideoFileExtnameValid(sourceExt)) {
298 throw new Error('Invalid video extension ' + sourceExt)
299 }
300
301 const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ]
302
303 for (const extension of extensions) {
304 const path = tmpPath + extension
305
306 if (await pathExists(path)) return path
307 }
308
309 throw new Error('Cannot guess path of ' + tmpPath)
310}
311
fbad87b0
C
312function normalizeObject (obj: any) {
313 const newObj: any = {}
314
315 for (const key of Object.keys(obj)) {
316 // Deprecated key
317 if (key === 'resolution') continue
318
319 const value = obj[key]
320
321 if (typeof value === 'string') {
322 newObj[key] = value.normalize()
323 } else {
324 newObj[key] = value
325 }
326 }
327
328 return newObj
329}
330
86ad0cde 331function buildVideoInfo (obj: any): YoutubeDLInfo {
fbad87b0
C
332 return {
333 name: titleTruncation(obj.title),
334 description: descriptionTruncation(obj.description),
335 category: getCategory(obj.categories),
336 licence: getLicence(obj.license),
86ad0cde 337 language: getLanguage(obj.language),
fbad87b0
C
338 nsfw: isNSFW(obj),
339 tags: getTags(obj.tags),
4e553a41 340 thumbnailUrl: obj.thumbnail || undefined,
d57d1d83 341 originallyPublishedAt: buildOriginallyPublishedAt(obj),
805b8619 342 ext: obj.ext
fbad87b0
C
343 }
344}
345
346function titleTruncation (title: string) {
687c6180
C
347 return peertubeTruncate(title, {
348 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
349 separator: /,? +/,
350 omission: ' […]'
fbad87b0
C
351 })
352}
353
354function descriptionTruncation (description: string) {
ed31c059 355 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
fbad87b0 356
687c6180
C
357 return peertubeTruncate(description, {
358 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
359 separator: /,? +/,
360 omission: ' […]'
fbad87b0
C
361 })
362}
363
364function isNSFW (info: any) {
365 return info.age_limit && info.age_limit >= 16
366}
367
368function getTags (tags: any) {
369 if (Array.isArray(tags) === false) return []
370
371 return tags
372 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
373 .map(t => t.normalize())
374 .slice(0, 5)
375}
376
377function getLicence (licence: string) {
378 if (!licence) return undefined
379
bdd428a6 380 if (licence.includes('Creative Commons Attribution')) return 1
fbad87b0 381
86ad0cde
C
382 for (const key of Object.keys(VIDEO_LICENCES)) {
383 const peertubeLicence = VIDEO_LICENCES[key]
384 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
385 }
386
fbad87b0
C
387 return undefined
388}
389
390function getCategory (categories: string[]) {
391 if (!categories) return undefined
392
393 const categoryString = categories[0]
394 if (!categoryString || typeof categoryString !== 'string') return undefined
395
396 if (categoryString === 'News & Politics') return 11
397
398 for (const key of Object.keys(VIDEO_CATEGORIES)) {
399 const category = VIDEO_CATEGORIES[key]
400 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
401 }
402
403 return undefined
404}
93905586 405
86ad0cde
C
406function getLanguage (language: string) {
407 return VIDEO_LANGUAGES[language] ? language : undefined
408}
409
93905586
C
410function wrapWithProxyOptions (options: string[]) {
411 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
412 logger.debug('Using proxy for YoutubeDL')
413
414 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)
415 }
416
417 return options
418}