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