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