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