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