]>
Commit | Line | Data |
---|---|---|
86ad0cde | 1 | import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants' |
fbad87b0 | 2 | import { logger } from './logger' |
6040f87d | 3 | import { generateVideoImportTmpPath } from './utils' |
454c20fa | 4 | import { getEnabledResolutions } from '../lib/video-transcoding' |
606c946e | 5 | import { join } from 'path' |
687c6180 C |
6 | import { peertubeTruncate, root } from './core-utils' |
7 | import { ensureDir, remove, writeFile } from 'fs-extra' | |
606c946e C |
8 | import * as request from 'request' |
9 | import { createWriteStream } from 'fs' | |
be7ca0c6 | 10 | import { CONFIG } from '@server/initializers/config' |
f2eb23cd | 11 | import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' |
454c20fa | 12 | import { VideoResolution } from '../../shared/models/videos' |
fbad87b0 C |
13 | |
14 | export type YoutubeDLInfo = { | |
ce33919c C |
15 | name?: string |
16 | description?: string | |
17 | category?: number | |
86ad0cde | 18 | language?: string |
ce33919c C |
19 | licence?: number |
20 | nsfw?: boolean | |
21 | tags?: string[] | |
22 | thumbnailUrl?: string | |
454c20fa RK |
23 | ext?: string |
24 | mergeExt?: string | |
c74c9be9 | 25 | originallyPublishedAt?: Date |
fbad87b0 C |
26 | } |
27 | ||
50ad0a1c | 28 | export type YoutubeDLSubs = { |
652c6416 C |
29 | language: string |
30 | filename: string | |
50ad0a1c | 31 | path: string |
32 | }[] | |
33 | ||
cc680494 C |
34 | const processOptions = { |
35 | maxBuffer: 1024 * 1024 * 10 // 10MB | |
36 | } | |
37 | ||
8704acf4 | 38 | function 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.')) | |
454c20fa RK |
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' | |
969e59d1 C |
58 | } else if (info.ext === 'webm') { |
59 | info.mergeExt = 'webm' | |
454c20fa RK |
60 | } else { |
61 | info.mergeExt = 'mkv' | |
62 | } | |
63 | } | |
fbad87b0 | 64 | |
a1587156 C |
65 | const obj = buildVideoInfo(normalizeObject(info)) |
66 | if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video' | |
fbad87b0 | 67 | |
a1587156 C |
68 | return res(obj) |
69 | }) | |
70 | }) | |
71 | .catch(err => rej(err)) | |
fbad87b0 C |
72 | }) |
73 | } | |
74 | ||
50ad0a1c | 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) | |
c7763edd | 84 | if (!files) return [] |
50ad0a1c | 85 | |
652c6416 C |
86 | logger.debug('Get subtitles from youtube dl.', { url, files }) |
87 | ||
50ad0a1c | 88 | const subtitles = files.reduce((acc, filename) => { |
89 | const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i) | |
982f2fc9 | 90 | if (!matched || !matched[1]) return acc |
50ad0a1c | 91 | |
982f2fc9 C |
92 | return [ |
93 | ...acc, | |
94 | { | |
95 | language: matched[1], | |
96 | path: join(cwd, filename), | |
97 | filename | |
98 | } | |
99 | ] | |
50ad0a1c | 100 | }, []) |
101 | ||
102 | return res(subtitles) | |
103 | }) | |
104 | }) | |
105 | .catch(err => rej(err)) | |
106 | }) | |
107 | } | |
108 | ||
454c20fa RK |
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`, | |
a8a63b1f C |
131 | 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats |
132 | 'best' // Ultimate fallback | |
454c20fa RK |
133 | ].join('/') |
134 | } | |
135 | ||
136 | function downloadYoutubeDLVideo (url: string, extension: string, timeout: number, mergeExtension?: string) { | |
969e59d1 C |
137 | let path = generateVideoImportTmpPath(url, extension) |
138 | ||
139 | path = mergeExtension | |
140 | ? path.replace(new RegExp(`${extension}$`), mergeExtension) | |
141 | : path | |
142 | ||
cf9166cf | 143 | let timer |
fbad87b0 | 144 | |
969e59d1 | 145 | logger.info('Importing youtubeDL video %s to %s', url, path) |
fbad87b0 | 146 | |
454c20fa | 147 | let options = [ '-f', getYoutubeDLVideoFormat(), '-o', path ] |
93905586 | 148 | options = wrapWithProxyOptions(options) |
fbad87b0 | 149 | |
5322589d | 150 | if (process.env.FFMPEG_PATH) { |
be7ca0c6 | 151 | options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ]) |
5322589d C |
152 | } |
153 | ||
969e59d1 C |
154 | logger.debug('YoutubeDL options for %s.', url, { options }) |
155 | ||
a1587156 C |
156 | return new Promise<string>((res, rej) => { |
157 | safeGetYoutubeDL() | |
158 | .then(youtubeDL => { | |
159 | youtubeDL.exec(url, options, processOptions, err => { | |
160 | clearTimeout(timer) | |
cf9166cf | 161 | |
a1587156 C |
162 | if (err) { |
163 | remove(path) | |
164 | .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err })) | |
cf9166cf | 165 | |
a1587156 C |
166 | return rej(err) |
167 | } | |
fbad87b0 | 168 | |
969e59d1 | 169 | return res(path) |
a1587156 | 170 | }) |
cf9166cf | 171 | |
a1587156 C |
172 | timer = setTimeout(() => { |
173 | const err = new Error('YoutubeDL download timeout.') | |
cf9166cf | 174 | |
a1587156 C |
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)) | |
fbad87b0 C |
184 | }) |
185 | } | |
186 | ||
606c946e C |
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') | |
44fb5297 | 195 | const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl' |
606c946e C |
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 | ||
f2eb23cd | 206 | if (result.statusCode !== HttpStatusCode.FOUND_302) { |
606c946e C |
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) | |
a1587156 | 213 | const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1] |
606c946e C |
214 | |
215 | downloadFile.on('response', result => { | |
f2eb23cd | 216 | if (result.statusCode !== HttpStatusCode.OK_200) { |
606c946e C |
217 | logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode) |
218 | return res() | |
219 | } | |
220 | ||
027e3080 C |
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) | |
606c946e C |
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 | ||
4f1f6f03 C |
250 | async function safeGetYoutubeDL () { |
251 | let youtubeDL | |
252 | ||
253 | try { | |
254 | youtubeDL = require('youtube-dl') | |
255 | } catch (e) { | |
256 | // Download binary | |
606c946e | 257 | await updateYoutubeDLBinary() |
4f1f6f03 C |
258 | youtubeDL = require('youtube-dl') |
259 | } | |
260 | ||
261 | return youtubeDL | |
262 | } | |
263 | ||
c74c9be9 C |
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 | ||
8704acf4 RK |
283 | // --------------------------------------------------------------------------- |
284 | ||
285 | export { | |
0491173a | 286 | updateYoutubeDLBinary, |
454c20fa | 287 | getYoutubeDLVideoFormat, |
8704acf4 | 288 | downloadYoutubeDLVideo, |
50ad0a1c | 289 | getYoutubeDLSubs, |
8704acf4 | 290 | getYoutubeDLInfo, |
c74c9be9 C |
291 | safeGetYoutubeDL, |
292 | buildOriginallyPublishedAt | |
8704acf4 RK |
293 | } |
294 | ||
295 | // --------------------------------------------------------------------------- | |
296 | ||
fbad87b0 C |
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 | ||
86ad0cde | 316 | function buildVideoInfo (obj: any): YoutubeDLInfo { |
fbad87b0 C |
317 | return { |
318 | name: titleTruncation(obj.title), | |
319 | description: descriptionTruncation(obj.description), | |
320 | category: getCategory(obj.categories), | |
321 | licence: getLicence(obj.license), | |
86ad0cde | 322 | language: getLanguage(obj.language), |
fbad87b0 C |
323 | nsfw: isNSFW(obj), |
324 | tags: getTags(obj.tags), | |
4e553a41 | 325 | thumbnailUrl: obj.thumbnail || undefined, |
d57d1d83 | 326 | originallyPublishedAt: buildOriginallyPublishedAt(obj), |
454c20fa RK |
327 | ext: obj.ext, |
328 | mergeExt: obj.mergeExt | |
fbad87b0 C |
329 | } |
330 | } | |
331 | ||
332 | function titleTruncation (title: string) { | |
687c6180 C |
333 | return peertubeTruncate(title, { |
334 | length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, | |
335 | separator: /,? +/, | |
336 | omission: ' […]' | |
fbad87b0 C |
337 | }) |
338 | } | |
339 | ||
340 | function descriptionTruncation (description: string) { | |
ed31c059 | 341 | if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined |
fbad87b0 | 342 | |
687c6180 C |
343 | return peertubeTruncate(description, { |
344 | length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max, | |
345 | separator: /,? +/, | |
346 | omission: ' […]' | |
fbad87b0 C |
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 | ||
bdd428a6 | 366 | if (licence.includes('Creative Commons Attribution')) return 1 |
fbad87b0 | 367 | |
86ad0cde C |
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 | ||
fbad87b0 C |
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 | } | |
93905586 | 391 | |
86ad0cde C |
392 | function getLanguage (language: string) { |
393 | return VIDEO_LANGUAGES[language] ? language : undefined | |
394 | } | |
395 | ||
93905586 C |
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 | } |