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