]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/youtube-dl.ts
default youtube-dl to use ipv4 (#3311)
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
CommitLineData
86ad0cde 1import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
fbad87b0 2import { logger } from './logger'
6040f87d 3import { generateVideoImportTmpPath } from './utils'
606c946e 4import { join } from 'path'
687c6180
C
5import { peertubeTruncate, root } from './core-utils'
6import { ensureDir, remove, writeFile } from 'fs-extra'
606c946e
C
7import * as request from 'request'
8import { createWriteStream } from 'fs'
be7ca0c6 9import { CONFIG } from '@server/initializers/config'
fbad87b0
C
10
11export type YoutubeDLInfo = {
ce33919c
C
12 name?: string
13 description?: string
14 category?: number
86ad0cde 15 language?: string
ce33919c
C
16 licence?: number
17 nsfw?: boolean
18 tags?: string[]
19 thumbnailUrl?: string
d57d1d83 20 fileExt?: string
c74c9be9 21 originallyPublishedAt?: Date
fbad87b0
C
22}
23
50ad0a1c 24export type YoutubeDLSubs = {
652c6416
C
25 language: string
26 filename: string
50ad0a1c 27 path: string
28}[]
29
cc680494
C
30const processOptions = {
31 maxBuffer: 1024 * 1024 * 10 // 10MB
32}
33
8704acf4 34function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
a1587156 35 return new Promise<YoutubeDLInfo>((res, rej) => {
93905586 36 let args = opts || [ '-j', '--flat-playlist' ]
677012b4 37 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCEIPV4) args.push('--force-ipv4')
93905586 38 args = wrapWithProxyOptions(args)
fbad87b0 39
a1587156
C
40 safeGetYoutubeDL()
41 .then(youtubeDL => {
42 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
43 if (err) return rej(err)
44 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
fbad87b0 45
a1587156
C
46 const obj = buildVideoInfo(normalizeObject(info))
47 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
fbad87b0 48
a1587156
C
49 return res(obj)
50 })
51 })
52 .catch(err => rej(err))
fbad87b0
C
53 })
54}
55
50ad0a1c 56function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
57 return new Promise<YoutubeDLSubs>((res, rej) => {
58 const cwd = CONFIG.STORAGE.TMP_DIR
59 const options = opts || { all: true, format: 'vtt', cwd }
60
61 safeGetYoutubeDL()
62 .then(youtubeDL => {
63 youtubeDL.getSubs(url, options, (err, files) => {
64 if (err) return rej(err)
c7763edd 65 if (!files) return []
50ad0a1c 66
652c6416
C
67 logger.debug('Get subtitles from youtube dl.', { url, files })
68
50ad0a1c 69 const subtitles = files.reduce((acc, filename) => {
70 const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
982f2fc9 71 if (!matched || !matched[1]) return acc
50ad0a1c 72
982f2fc9
C
73 return [
74 ...acc,
75 {
76 language: matched[1],
77 path: join(cwd, filename),
78 filename
79 }
80 ]
50ad0a1c 81 }, [])
82
83 return res(subtitles)
84 })
85 })
86 .catch(err => rej(err))
87 })
88}
89
d57d1d83
C
90function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) {
91 const path = generateVideoImportTmpPath(url, extension)
cf9166cf 92 let timer
fbad87b0 93
d57d1d83 94 logger.info('Importing youtubeDL video %s to %s', url, path)
fbad87b0 95
be7ca0c6 96 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
93905586 97 options = wrapWithProxyOptions(options)
fbad87b0 98
5322589d 99 if (process.env.FFMPEG_PATH) {
be7ca0c6 100 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
5322589d
C
101 }
102
a1587156
C
103 return new Promise<string>((res, rej) => {
104 safeGetYoutubeDL()
105 .then(youtubeDL => {
106 youtubeDL.exec(url, options, processOptions, err => {
107 clearTimeout(timer)
cf9166cf 108
a1587156
C
109 if (err) {
110 remove(path)
111 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
cf9166cf 112
a1587156
C
113 return rej(err)
114 }
fbad87b0 115
a1587156
C
116 return res(path)
117 })
cf9166cf 118
a1587156
C
119 timer = setTimeout(() => {
120 const err = new Error('YoutubeDL download timeout.')
cf9166cf 121
a1587156
C
122 remove(path)
123 .finally(() => rej(err))
124 .catch(err => {
125 logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
126 return rej(err)
127 })
128 }, timeout)
129 })
130 .catch(err => rej(err))
fbad87b0
C
131 })
132}
133
606c946e
C
134// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
135// We rewrote it to avoid sync calls
136async function updateYoutubeDLBinary () {
137 logger.info('Updating youtubeDL binary.')
138
139 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
140 const bin = join(binDirectory, 'youtube-dl')
141 const detailsPath = join(binDirectory, 'details')
44fb5297 142 const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl'
606c946e
C
143
144 await ensureDir(binDirectory)
145
146 return new Promise(res => {
147 request.get(url, { followRedirect: false }, (err, result) => {
148 if (err) {
149 logger.error('Cannot update youtube-dl.', { err })
150 return res()
151 }
152
153 if (result.statusCode !== 302) {
154 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
155 return res()
156 }
157
158 const url = result.headers.location
159 const downloadFile = request.get(url)
a1587156 160 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
606c946e
C
161
162 downloadFile.on('response', result => {
163 if (result.statusCode !== 200) {
164 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
165 return res()
166 }
167
168 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
169 })
170
171 downloadFile.on('error', err => {
172 logger.error('youtube-dl update error.', { err })
173 return res()
174 })
175
176 downloadFile.on('end', () => {
177 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
178 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
179 if (err) {
180 logger.error('youtube-dl update error: cannot write details.', { err })
181 return res()
182 }
183
184 logger.info('youtube-dl updated to version %s.', newVersion)
185 return res()
186 })
187 })
188 })
189 })
190}
191
4f1f6f03
C
192async function safeGetYoutubeDL () {
193 let youtubeDL
194
195 try {
196 youtubeDL = require('youtube-dl')
197 } catch (e) {
198 // Download binary
606c946e 199 await updateYoutubeDLBinary()
4f1f6f03
C
200 youtubeDL = require('youtube-dl')
201 }
202
203 return youtubeDL
204}
205
c74c9be9
C
206function buildOriginallyPublishedAt (obj: any) {
207 let originallyPublishedAt: Date = null
208
209 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
210 if (uploadDateMatcher) {
211 originallyPublishedAt = new Date()
212 originallyPublishedAt.setHours(0, 0, 0, 0)
213
214 const year = parseInt(uploadDateMatcher[1], 10)
215 // Month starts from 0
216 const month = parseInt(uploadDateMatcher[2], 10) - 1
217 const day = parseInt(uploadDateMatcher[3], 10)
218
219 originallyPublishedAt.setFullYear(year, month, day)
220 }
221
222 return originallyPublishedAt
223}
224
8704acf4
RK
225// ---------------------------------------------------------------------------
226
227export {
0491173a 228 updateYoutubeDLBinary,
8704acf4 229 downloadYoutubeDLVideo,
50ad0a1c 230 getYoutubeDLSubs,
8704acf4 231 getYoutubeDLInfo,
c74c9be9
C
232 safeGetYoutubeDL,
233 buildOriginallyPublishedAt
8704acf4
RK
234}
235
236// ---------------------------------------------------------------------------
237
fbad87b0
C
238function normalizeObject (obj: any) {
239 const newObj: any = {}
240
241 for (const key of Object.keys(obj)) {
242 // Deprecated key
243 if (key === 'resolution') continue
244
245 const value = obj[key]
246
247 if (typeof value === 'string') {
248 newObj[key] = value.normalize()
249 } else {
250 newObj[key] = value
251 }
252 }
253
254 return newObj
255}
256
86ad0cde 257function buildVideoInfo (obj: any): YoutubeDLInfo {
fbad87b0
C
258 return {
259 name: titleTruncation(obj.title),
260 description: descriptionTruncation(obj.description),
261 category: getCategory(obj.categories),
262 licence: getLicence(obj.license),
86ad0cde 263 language: getLanguage(obj.language),
fbad87b0
C
264 nsfw: isNSFW(obj),
265 tags: getTags(obj.tags),
4e553a41 266 thumbnailUrl: obj.thumbnail || undefined,
d57d1d83
C
267 originallyPublishedAt: buildOriginallyPublishedAt(obj),
268 fileExt: obj.ext
fbad87b0
C
269 }
270}
271
272function titleTruncation (title: string) {
687c6180
C
273 return peertubeTruncate(title, {
274 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
275 separator: /,? +/,
276 omission: ' […]'
fbad87b0
C
277 })
278}
279
280function descriptionTruncation (description: string) {
ed31c059 281 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
fbad87b0 282
687c6180
C
283 return peertubeTruncate(description, {
284 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
285 separator: /,? +/,
286 omission: ' […]'
fbad87b0
C
287 })
288}
289
290function isNSFW (info: any) {
291 return info.age_limit && info.age_limit >= 16
292}
293
294function getTags (tags: any) {
295 if (Array.isArray(tags) === false) return []
296
297 return tags
298 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
299 .map(t => t.normalize())
300 .slice(0, 5)
301}
302
303function getLicence (licence: string) {
304 if (!licence) return undefined
305
bdd428a6 306 if (licence.includes('Creative Commons Attribution')) return 1
fbad87b0 307
86ad0cde
C
308 for (const key of Object.keys(VIDEO_LICENCES)) {
309 const peertubeLicence = VIDEO_LICENCES[key]
310 if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10)
311 }
312
fbad87b0
C
313 return undefined
314}
315
316function getCategory (categories: string[]) {
317 if (!categories) return undefined
318
319 const categoryString = categories[0]
320 if (!categoryString || typeof categoryString !== 'string') return undefined
321
322 if (categoryString === 'News & Politics') return 11
323
324 for (const key of Object.keys(VIDEO_CATEGORIES)) {
325 const category = VIDEO_CATEGORIES[key]
326 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
327 }
328
329 return undefined
330}
93905586 331
86ad0cde
C
332function getLanguage (language: string) {
333 return VIDEO_LANGUAGES[language] ? language : undefined
334}
335
93905586
C
336function wrapWithProxyOptions (options: string[]) {
337 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
338 logger.debug('Using proxy for YoutubeDL')
339
340 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)
341 }
342
343 return options
344}