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