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