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