]>
Commit | Line | Data |
---|---|---|
2aaa1a3f C |
1 | import { registerTSPaths } from '../helpers/register-ts-paths' |
2 | registerTSPaths() | |
3 | ||
12152aa0 | 4 | import { program } from 'commander' |
d7764e2e | 5 | import { accessSync, constants } from 'fs' |
82f5527f F |
6 | import { remove } from 'fs-extra' |
7 | import { truncate } from 'lodash' | |
d7764e2e | 8 | import { join } from 'path' |
82f5527f | 9 | import * as prompt from 'prompt' |
d7764e2e | 10 | import { promisify } from 'util' |
078f17e6 C |
11 | import { YoutubeDL } from '@server/helpers/youtube-dl' |
12 | import { getVideoCategories, uploadVideo } from '../../shared/extra-utils/index' | |
fa27f076 | 13 | import { sha256 } from '../helpers/core-utils' |
d7764e2e | 14 | import { doRequestAndSaveToFile } from '../helpers/requests' |
d7764e2e | 15 | import { CONSTRAINTS_FIELDS } from '../initializers/constants' |
078f17e6 C |
16 | import { |
17 | buildCommonVideoOptions, | |
18 | buildServer, | |
19 | buildVideoAttributesFromCommander, | |
20 | getAccessTokenOrDie, | |
21 | getLogger, | |
22 | getServerCredentials | |
23 | } from './cli' | |
8704acf4 RK |
24 | |
25 | const processOptions = { | |
8704acf4 RK |
26 | maxBuffer: Infinity |
27 | } | |
a7fea183 | 28 | |
1205823f | 29 | let command = program |
8704acf4 | 30 | .name('import-videos') |
1205823f C |
31 | |
32 | command = buildCommonVideoOptions(command) | |
33 | ||
34 | command | |
a7fea183 C |
35 | .option('-u, --url <url>', 'Server url') |
36 | .option('-U, --username <username>', 'Username') | |
37 | .option('-p, --password <token>', 'Password') | |
d0198ff9 F |
38 | .option('--target-url <targetUrl>', 'Video target URL') |
39 | .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate) | |
40 | .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate) | |
bda3b705 FL |
41 | .option('--first <first>', 'Process first n elements of returned playlist') |
42 | .option('--last <last>', 'Process last n elements of returned playlist') | |
82f5527f | 43 | .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs) |
bda3b705 | 44 | .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname) |
79ee77ea | 45 | .usage("[global options] [ -- youtube-dl options]") |
a7fea183 C |
46 | .parse(process.argv) |
47 | ||
ba5a8d89 C |
48 | const options = command.opts() |
49 | ||
50 | const log = getLogger(options.verbose) | |
bda3b705 | 51 | |
8d2be0ed C |
52 | getServerCredentials(command) |
53 | .then(({ url, username, password }) => { | |
ba5a8d89 | 54 | if (!options.targetUrl) { |
bda3b705 FL |
55 | exitError('--target-url field is required.') |
56 | } | |
e8a739e8 | 57 | |
bda3b705 | 58 | try { |
ba5a8d89 | 59 | accessSync(options.tmpdir, constants.R_OK | constants.W_OK) |
bda3b705 | 60 | } catch (e) { |
ba5a8d89 | 61 | exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir) |
8d2be0ed | 62 | } |
066fc8ba | 63 | |
da69b886 | 64 | url = normalizeTargetUrl(url) |
ba5a8d89 | 65 | options.targetUrl = normalizeTargetUrl(options.targetUrl) |
ab4dbe36 | 66 | |
078f17e6 | 67 | run(url, username, password) |
a1587156 | 68 | .catch(err => exitError(err)) |
8d2be0ed | 69 | }) |
a1587156 | 70 | .catch(err => console.error(err)) |
a7fea183 | 71 | |
078f17e6 C |
72 | async function run (url: string, username: string, password: string) { |
73 | if (!password) password = await promptPassword() | |
8a2db2e8 | 74 | |
1bcb03a1 | 75 | const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() |
8704acf4 | 76 | |
1bcb03a1 | 77 | let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args) |
79ee77ea | 78 | |
5721fd83 | 79 | if (!Array.isArray(info)) info = [ info ] |
a7fea183 | 80 | |
5721fd83 C |
81 | // Try to fix youtube channels upload |
82 | const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads') | |
83 | ||
84 | if (uploadsObject) { | |
85 | console.log('Fixing URL to %s.', uploadsObject.url) | |
86 | ||
1bcb03a1 | 87 | info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args) |
de29e90c | 88 | } |
a7fea183 | 89 | |
de29e90c | 90 | let infoArray: any[] |
bda3b705 | 91 | |
de29e90c | 92 | infoArray = [].concat(info) |
ba5a8d89 C |
93 | if (options.first) { |
94 | infoArray = infoArray.slice(0, options.first) | |
95 | } else if (options.last) { | |
96 | infoArray = infoArray.slice(-options.last) | |
de29e90c | 97 | } |
82f5527f | 98 | // Normalize utf8 fields |
de29e90c | 99 | infoArray = infoArray.map(i => normalizeObject(i)) |
a7fea183 | 100 | |
de29e90c C |
101 | log.info('Will download and upload %d videos.\n', infoArray.length) |
102 | ||
82f5527f | 103 | for (const [ index, info ] of infoArray.entries()) { |
de29e90c | 104 | try { |
ba5a8d89 C |
105 | if (index > 0 && options.waitInterval) { |
106 | log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000) | |
107 | await new Promise(res => setTimeout(res, options.waitInterval)) | |
82f5527f | 108 | } |
de29e90c | 109 | await processVideo({ |
ba5a8d89 | 110 | cwd: options.tmpdir, |
de29e90c | 111 | url, |
078f17e6 C |
112 | username, |
113 | password, | |
de29e90c C |
114 | youtubeInfo: info |
115 | }) | |
116 | } catch (err) { | |
82f5527f | 117 | console.error('Cannot process video.', { info, url, err }) |
a7fea183 | 118 | } |
de29e90c | 119 | } |
a7fea183 | 120 | |
078f17e6 | 121 | log.info('Video/s for user %s imported: %s', username, options.targetUrl) |
de29e90c | 122 | process.exit(0) |
a7fea183 C |
123 | } |
124 | ||
82f5527f | 125 | async function processVideo (parameters: { |
a1587156 C |
126 | cwd: string |
127 | url: string | |
078f17e6 C |
128 | username: string |
129 | password: string | |
1a12f66d C |
130 | youtubeInfo: any |
131 | }) { | |
078f17e6 | 132 | const { youtubeInfo, cwd, url, username, password } = parameters |
1bcb03a1 | 133 | const youtubeDL = new YoutubeDL('', []) |
1a12f66d | 134 | |
82f5527f | 135 | log.debug('Fetching object.', youtubeInfo) |
61b3e146 | 136 | |
82f5527f F |
137 | const videoInfo = await fetchObject(youtubeInfo) |
138 | log.debug('Fetched object.', videoInfo) | |
d0198ff9 | 139 | |
1bcb03a1 | 140 | const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) |
078f17e6 | 141 | |
ba5a8d89 | 142 | if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) { |
078f17e6 | 143 | log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.since)) |
82f5527f F |
144 | return |
145 | } | |
078f17e6 | 146 | |
ba5a8d89 | 147 | if (options.until && originallyPublishedAt && originallyPublishedAt.getTime() > options.until.getTime()) { |
078f17e6 | 148 | log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.until)) |
82f5527f F |
149 | return |
150 | } | |
e7872038 | 151 | |
078f17e6 C |
152 | const server = buildServer(url) |
153 | const { data } = await server.searchCommand.advancedVideoSearch({ | |
154 | search: { | |
155 | search: videoInfo.title, | |
156 | sort: '-match', | |
157 | searchTarget: 'local' | |
158 | } | |
159 | }) | |
e7872038 | 160 | |
82f5527f | 161 | log.info('############################################################\n') |
a7fea183 | 162 | |
078f17e6 | 163 | if (data.find(v => v.name === videoInfo.title)) { |
82f5527f F |
164 | log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title) |
165 | return | |
166 | } | |
a7fea183 | 167 | |
82f5527f | 168 | const path = join(cwd, sha256(videoInfo.url) + '.mp4') |
a7fea183 | 169 | |
82f5527f | 170 | log.info('Downloading video "%s"...', videoInfo.title) |
f97d2992 | 171 | |
1bcb03a1 | 172 | const youtubeDLOptions = [ '-f', youtubeDL.getYoutubeDLVideoFormat(), ...command.args, '-o', path ] |
82f5527f | 173 | try { |
1bcb03a1 C |
174 | const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() |
175 | const youtubeDLExec = promisify(youtubeDLBinary.exec).bind(youtubeDLBinary) | |
ba5a8d89 | 176 | const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions) |
82f5527f F |
177 | log.info(output.join('\n')) |
178 | await uploadVideoOnPeerTube({ | |
1bcb03a1 | 179 | youtubeDL, |
82f5527f F |
180 | cwd, |
181 | url, | |
078f17e6 C |
182 | username, |
183 | password, | |
82f5527f F |
184 | videoInfo: normalizeObject(videoInfo), |
185 | videoPath: path | |
186 | }) | |
187 | } catch (err) { | |
188 | log.error(err.message) | |
189 | } | |
a7fea183 C |
190 | } |
191 | ||
1a12f66d | 192 | async function uploadVideoOnPeerTube (parameters: { |
1bcb03a1 | 193 | youtubeDL: YoutubeDL |
a1587156 C |
194 | videoInfo: any |
195 | videoPath: string | |
196 | cwd: string | |
197 | url: string | |
078f17e6 C |
198 | username: string |
199 | password: string | |
1a12f66d | 200 | }) { |
078f17e6 | 201 | const { youtubeDL, videoInfo, videoPath, cwd, url, username, password } = parameters |
1a12f66d | 202 | |
8704acf4 | 203 | const category = await getCategory(videoInfo.categories, url) |
a7fea183 | 204 | const licence = getLicence(videoInfo.license) |
34cbef8c C |
205 | let tags = [] |
206 | if (Array.isArray(videoInfo.tags)) { | |
02988fdc | 207 | tags = videoInfo.tags |
2b4dd7e2 C |
208 | .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min) |
209 | .map(t => t.normalize()) | |
210 | .slice(0, 5) | |
34cbef8c | 211 | } |
a7fea183 | 212 | |
1d791a26 C |
213 | let thumbnailfile |
214 | if (videoInfo.thumbnail) { | |
fa27f076 | 215 | thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg') |
1d791a26 | 216 | |
b5c36108 | 217 | await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile) |
1d791a26 C |
218 | } |
219 | ||
1bcb03a1 | 220 | const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) |
84929846 | 221 | |
1205823f | 222 | const defaultAttributes = { |
45b8a42c | 223 | name: truncate(videoInfo.title, { |
a1587156 C |
224 | length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, |
225 | separator: /,? +/, | |
226 | omission: ' […]' | |
45b8a42c | 227 | }), |
a7fea183 C |
228 | category, |
229 | licence, | |
a41e183c | 230 | nsfw: isNSFW(videoInfo), |
1205823f C |
231 | description: videoInfo.description, |
232 | tags | |
a7fea183 C |
233 | } |
234 | ||
078f17e6 C |
235 | let accessToken = await getAccessTokenOrDie(url, username, password) |
236 | const server = buildServer(url, accessToken) | |
237 | ||
238 | const videoAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) | |
1205823f C |
239 | |
240 | Object.assign(videoAttributes, { | |
241 | originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null, | |
242 | thumbnailfile, | |
243 | previewfile: thumbnailfile, | |
244 | fixture: videoPath | |
245 | }) | |
1a12f66d | 246 | |
bda3b705 | 247 | log.info('\nUploading on PeerTube video "%s".', videoAttributes.name) |
1a12f66d | 248 | |
71578f31 | 249 | try { |
8704acf4 | 250 | await uploadVideo(url, accessToken, videoAttributes) |
61b3e146 | 251 | } catch (err) { |
b6fe1f98 | 252 | if (err.message.indexOf('401') !== -1) { |
bda3b705 | 253 | log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') |
61b3e146 | 254 | |
078f17e6 | 255 | accessToken = await getAccessTokenOrDie(url, username, password) |
61b3e146 | 256 | |
8704acf4 | 257 | await uploadVideo(url, accessToken, videoAttributes) |
61b3e146 | 258 | } else { |
bda3b705 | 259 | exitError(err.message) |
71578f31 L |
260 | } |
261 | } | |
1d791a26 | 262 | |
62689b94 C |
263 | await remove(videoPath) |
264 | if (thumbnailfile) await remove(thumbnailfile) | |
1d791a26 | 265 | |
bda3b705 | 266 | log.warn('Uploaded video "%s"!\n', videoAttributes.name) |
a7fea183 C |
267 | } |
268 | ||
1a12f66d C |
269 | /* ---------------------------------------------------------- */ |
270 | ||
8704acf4 | 271 | async function getCategory (categories: string[], url: string) { |
61b3e146 C |
272 | if (!categories) return undefined |
273 | ||
a1587156 | 274 | const categoryString = categories[0] |
a7fea183 C |
275 | |
276 | if (categoryString === 'News & Politics') return 11 | |
277 | ||
8704acf4 | 278 | const res = await getVideoCategories(url) |
a7fea183 C |
279 | const categoriesServer = res.body |
280 | ||
281 | for (const key of Object.keys(categoriesServer)) { | |
a1587156 | 282 | const categoryServer = categoriesServer[key] |
a7fea183 C |
283 | if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10) |
284 | } | |
285 | ||
286 | return undefined | |
287 | } | |
288 | ||
289 | function getLicence (licence: string) { | |
61b3e146 C |
290 | if (!licence) return undefined |
291 | ||
bdd428a6 | 292 | if (licence.includes('Creative Commons Attribution licence')) return 1 |
a7fea183 C |
293 | |
294 | return undefined | |
295 | } | |
e7872038 C |
296 | |
297 | function normalizeObject (obj: any) { | |
298 | const newObj: any = {} | |
299 | ||
300 | for (const key of Object.keys(obj)) { | |
301 | // Deprecated key | |
302 | if (key === 'resolution') continue | |
303 | ||
a1587156 | 304 | const value = obj[key] |
e7872038 C |
305 | |
306 | if (typeof value === 'string') { | |
a1587156 | 307 | newObj[key] = value.normalize() |
e7872038 | 308 | } else { |
a1587156 | 309 | newObj[key] = value |
e7872038 C |
310 | } |
311 | } | |
312 | ||
313 | return newObj | |
314 | } | |
61b3e146 C |
315 | |
316 | function fetchObject (info: any) { | |
317 | const url = buildUrl(info) | |
318 | ||
319 | return new Promise<any>(async (res, rej) => { | |
1bcb03a1 | 320 | const youtubeDL = await YoutubeDL.safeGetYoutubeDL() |
a1587156 | 321 | youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => { |
61b3e146 C |
322 | if (err) return rej(err) |
323 | ||
324 | const videoInfoWithUrl = Object.assign(videoInfo, { url }) | |
325 | return res(normalizeObject(videoInfoWithUrl)) | |
326 | }) | |
327 | }) | |
328 | } | |
329 | ||
330 | function buildUrl (info: any) { | |
a41e183c | 331 | const webpageUrl = info.webpage_url as string |
a1587156 | 332 | if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl |
a41e183c | 333 | |
61b3e146 | 334 | const url = info.url as string |
a1587156 | 335 | if (url?.match(/^https?:\/\//)) return url |
61b3e146 C |
336 | |
337 | // It seems youtube-dl does not return the video url | |
338 | return 'https://www.youtube.com/watch?v=' + info.id | |
339 | } | |
a41e183c C |
340 | |
341 | function isNSFW (info: any) { | |
1a12f66d | 342 | return info.age_limit && info.age_limit >= 16 |
a41e183c | 343 | } |
ab4dbe36 | 344 | |
da69b886 C |
345 | function normalizeTargetUrl (url: string) { |
346 | let normalizedUrl = url.replace(/\/+$/, '') | |
347 | ||
4449d269 | 348 | if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) { |
da69b886 C |
349 | normalizedUrl = 'https://' + normalizedUrl |
350 | } | |
351 | ||
352 | return normalizedUrl | |
ab4dbe36 | 353 | } |
1a12f66d C |
354 | |
355 | async function promptPassword () { | |
356 | return new Promise<string>((res, rej) => { | |
357 | prompt.start() | |
358 | const schema = { | |
359 | properties: { | |
360 | password: { | |
361 | hidden: true, | |
362 | required: true | |
363 | } | |
364 | } | |
365 | } | |
366 | prompt.get(schema, function (err, result) { | |
367 | if (err) { | |
368 | return rej(err) | |
369 | } | |
370 | return res(result.password) | |
371 | }) | |
372 | }) | |
373 | } | |
374 | ||
d0198ff9 F |
375 | function parseDate (dateAsStr: string): Date { |
376 | if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) { | |
da69b886 | 377 | exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`) |
d0198ff9 | 378 | } |
da69b886 C |
379 | const date = new Date(dateAsStr) |
380 | date.setHours(0, 0, 0) | |
d0198ff9 | 381 | if (isNaN(date.getTime())) { |
da69b886 | 382 | exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`) |
d0198ff9 | 383 | } |
da69b886 | 384 | return date |
d0198ff9 F |
385 | } |
386 | ||
387 | function formatDate (date: Date): string { | |
a1587156 | 388 | return date.toISOString().split('T')[0] |
d0198ff9 | 389 | } |
bda3b705 | 390 | |
82f5527f F |
391 | function convertIntoMs (secondsAsStr: string): number { |
392 | const seconds = parseInt(secondsAsStr, 10) | |
393 | if (seconds <= 0) { | |
394 | exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`) | |
395 | } | |
396 | return Math.round(seconds * 1000) | |
397 | } | |
398 | ||
da69b886 | 399 | function exitError (message: string, ...meta: any[]) { |
bda3b705 FL |
400 | // use console.error instead of log.error here |
401 | console.error(message, ...meta) | |
402 | process.exit(-1) | |
403 | } | |
de29e90c C |
404 | |
405 | function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) { | |
406 | return new Promise<any>((res, rej) => { | |
407 | const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ] | |
408 | ||
409 | youtubeDL.getInfo(url, options, processOptions, async (err, info) => { | |
410 | if (err) return rej(err) | |
411 | ||
412 | return res(info) | |
413 | }) | |
414 | }) | |
415 | } |