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