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