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