]>
Commit | Line | Data |
---|---|---|
74dc3bca | 1 | import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } 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 | |
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 | 23 | export type YoutubeDLSubs = { |
652c6416 C |
24 | language: string |
25 | filename: string | |
50ad0a1c | 26 | path: string |
27 | }[] | |
28 | ||
cc680494 C |
29 | const processOptions = { |
30 | maxBuffer: 1024 * 1024 * 10 // 10MB | |
31 | } | |
32 | ||
8704acf4 | 33 | function 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 | 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 | ||
652c6416 C |
64 | logger.debug('Get subtitles from youtube dl.', { url, files }) |
65 | ||
50ad0a1c | 66 | const subtitles = files.reduce((acc, filename) => { |
67 | const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i) | |
68 | ||
69 | if (matched[1]) { | |
652c6416 C |
70 | return [ |
71 | ...acc, | |
72 | { | |
73 | language: matched[1], | |
74 | path: join(cwd, filename), | |
75 | filename | |
76 | } | |
77 | ] | |
50ad0a1c | 78 | } |
79 | }, []) | |
80 | ||
81 | return res(subtitles) | |
82 | }) | |
83 | }) | |
84 | .catch(err => rej(err)) | |
85 | }) | |
86 | } | |
87 | ||
d57d1d83 C |
88 | function downloadYoutubeDLVideo (url: string, extension: string, timeout: number) { |
89 | const path = generateVideoImportTmpPath(url, extension) | |
cf9166cf | 90 | let timer |
fbad87b0 | 91 | |
d57d1d83 | 92 | logger.info('Importing youtubeDL video %s to %s', url, path) |
fbad87b0 | 93 | |
be7ca0c6 | 94 | let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ] |
93905586 | 95 | options = wrapWithProxyOptions(options) |
fbad87b0 | 96 | |
5322589d | 97 | if (process.env.FFMPEG_PATH) { |
be7ca0c6 | 98 | options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ]) |
5322589d C |
99 | } |
100 | ||
a1587156 C |
101 | return new Promise<string>((res, rej) => { |
102 | safeGetYoutubeDL() | |
103 | .then(youtubeDL => { | |
104 | youtubeDL.exec(url, options, processOptions, err => { | |
105 | clearTimeout(timer) | |
cf9166cf | 106 | |
a1587156 C |
107 | if (err) { |
108 | remove(path) | |
109 | .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err })) | |
cf9166cf | 110 | |
a1587156 C |
111 | return rej(err) |
112 | } | |
fbad87b0 | 113 | |
a1587156 C |
114 | return res(path) |
115 | }) | |
cf9166cf | 116 | |
a1587156 C |
117 | timer = setTimeout(() => { |
118 | const err = new Error('YoutubeDL download timeout.') | |
cf9166cf | 119 | |
a1587156 C |
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)) | |
fbad87b0 C |
129 | }) |
130 | } | |
131 | ||
606c946e C |
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) | |
a1587156 | 158 | const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1] |
606c946e C |
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 | ||
4f1f6f03 C |
190 | async function safeGetYoutubeDL () { |
191 | let youtubeDL | |
192 | ||
193 | try { | |
194 | youtubeDL = require('youtube-dl') | |
195 | } catch (e) { | |
196 | // Download binary | |
606c946e | 197 | await updateYoutubeDLBinary() |
4f1f6f03 C |
198 | youtubeDL = require('youtube-dl') |
199 | } | |
200 | ||
201 | return youtubeDL | |
202 | } | |
203 | ||
c74c9be9 C |
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 | ||
8704acf4 RK |
223 | // --------------------------------------------------------------------------- |
224 | ||
225 | export { | |
0491173a | 226 | updateYoutubeDLBinary, |
8704acf4 | 227 | downloadYoutubeDLVideo, |
50ad0a1c | 228 | getYoutubeDLSubs, |
8704acf4 | 229 | getYoutubeDLInfo, |
c74c9be9 C |
230 | safeGetYoutubeDL, |
231 | buildOriginallyPublishedAt | |
8704acf4 RK |
232 | } |
233 | ||
234 | // --------------------------------------------------------------------------- | |
235 | ||
fbad87b0 C |
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), | |
4e553a41 | 263 | thumbnailUrl: obj.thumbnail || undefined, |
d57d1d83 C |
264 | originallyPublishedAt: buildOriginallyPublishedAt(obj), |
265 | fileExt: obj.ext | |
fbad87b0 C |
266 | } |
267 | } | |
268 | ||
269 | function titleTruncation (title: string) { | |
687c6180 C |
270 | return peertubeTruncate(title, { |
271 | length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, | |
272 | separator: /,? +/, | |
273 | omission: ' […]' | |
fbad87b0 C |
274 | }) |
275 | } | |
276 | ||
277 | function descriptionTruncation (description: string) { | |
ed31c059 | 278 | if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined |
fbad87b0 | 279 | |
687c6180 C |
280 | return peertubeTruncate(description, { |
281 | length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max, | |
282 | separator: /,? +/, | |
283 | omission: ' […]' | |
fbad87b0 C |
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 | ||
bdd428a6 | 303 | if (licence.includes('Creative Commons Attribution')) return 1 |
fbad87b0 C |
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 | } | |
93905586 C |
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 | } |