]>
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 | 11 | import { YoutubeDL } from '@server/helpers/youtube-dl' |
fa27f076 | 12 | import { sha256 } from '../helpers/core-utils' |
d7764e2e | 13 | import { doRequestAndSaveToFile } from '../helpers/requests' |
d7764e2e | 14 | import { CONSTRAINTS_FIELDS } from '../initializers/constants' |
078f17e6 | 15 | import { |
d0a0fa42 | 16 | assignToken, |
078f17e6 C |
17 | buildCommonVideoOptions, |
18 | buildServer, | |
19 | buildVideoAttributesFromCommander, | |
078f17e6 C |
20 | getLogger, |
21 | getServerCredentials | |
22 | } from './cli' | |
254d3579 | 23 | import { PeerTubeServer } from '@shared/extra-utils' |
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 | 152 | const server = buildServer(url) |
89d241a7 | 153 | const { data } = await server.search.advancedVideoSearch({ |
078f17e6 C |
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 | |
d23dd9fb C |
203 | const server = buildServer(url) |
204 | await assignToken(server, username, password) | |
205 | ||
206 | const category = await getCategory(server, videoInfo.categories) | |
a7fea183 | 207 | const licence = getLicence(videoInfo.license) |
34cbef8c C |
208 | let tags = [] |
209 | if (Array.isArray(videoInfo.tags)) { | |
02988fdc | 210 | tags = videoInfo.tags |
2b4dd7e2 C |
211 | .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min) |
212 | .map(t => t.normalize()) | |
213 | .slice(0, 5) | |
34cbef8c | 214 | } |
a7fea183 | 215 | |
1d791a26 C |
216 | let thumbnailfile |
217 | if (videoInfo.thumbnail) { | |
fa27f076 | 218 | thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg') |
1d791a26 | 219 | |
b5c36108 | 220 | await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile) |
1d791a26 C |
221 | } |
222 | ||
1bcb03a1 | 223 | const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) |
84929846 | 224 | |
1205823f | 225 | const defaultAttributes = { |
45b8a42c | 226 | name: truncate(videoInfo.title, { |
a1587156 C |
227 | length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, |
228 | separator: /,? +/, | |
229 | omission: ' […]' | |
45b8a42c | 230 | }), |
a7fea183 C |
231 | category, |
232 | licence, | |
a41e183c | 233 | nsfw: isNSFW(videoInfo), |
1205823f C |
234 | description: videoInfo.description, |
235 | tags | |
a7fea183 C |
236 | } |
237 | ||
d23dd9fb | 238 | const baseAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) |
078f17e6 | 239 | |
d23dd9fb C |
240 | const attributes = { |
241 | ...baseAttributes, | |
1205823f | 242 | |
1205823f C |
243 | originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null, |
244 | thumbnailfile, | |
245 | previewfile: thumbnailfile, | |
246 | fixture: videoPath | |
d23dd9fb | 247 | } |
1a12f66d | 248 | |
d23dd9fb | 249 | log.info('\nUploading on PeerTube video "%s".', attributes.name) |
1a12f66d | 250 | |
71578f31 | 251 | try { |
89d241a7 | 252 | await server.videos.upload({ attributes }) |
61b3e146 | 253 | } catch (err) { |
b6fe1f98 | 254 | if (err.message.indexOf('401') !== -1) { |
bda3b705 | 255 | log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') |
61b3e146 | 256 | |
89d241a7 | 257 | server.accessToken = await server.login.getAccessToken(username, password) |
61b3e146 | 258 | |
89d241a7 | 259 | await server.videos.upload({ attributes }) |
61b3e146 | 260 | } else { |
bda3b705 | 261 | exitError(err.message) |
71578f31 L |
262 | } |
263 | } | |
1d791a26 | 264 | |
62689b94 C |
265 | await remove(videoPath) |
266 | if (thumbnailfile) await remove(thumbnailfile) | |
1d791a26 | 267 | |
d23dd9fb | 268 | log.warn('Uploaded video "%s"!\n', attributes.name) |
a7fea183 C |
269 | } |
270 | ||
1a12f66d C |
271 | /* ---------------------------------------------------------- */ |
272 | ||
254d3579 | 273 | async function getCategory (server: PeerTubeServer, categories: string[]) { |
61b3e146 C |
274 | if (!categories) return undefined |
275 | ||
a1587156 | 276 | const categoryString = categories[0] |
a7fea183 C |
277 | |
278 | if (categoryString === 'News & Politics') return 11 | |
279 | ||
89d241a7 | 280 | const categoriesServer = await server.videos.getCategories() |
a7fea183 C |
281 | |
282 | for (const key of Object.keys(categoriesServer)) { | |
a1587156 | 283 | const categoryServer = categoriesServer[key] |
a7fea183 C |
284 | if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10) |
285 | } | |
286 | ||
287 | return undefined | |
288 | } | |
289 | ||
290 | function getLicence (licence: string) { | |
61b3e146 C |
291 | if (!licence) return undefined |
292 | ||
bdd428a6 | 293 | if (licence.includes('Creative Commons Attribution licence')) return 1 |
a7fea183 C |
294 | |
295 | return undefined | |
296 | } | |
e7872038 C |
297 | |
298 | function normalizeObject (obj: any) { | |
299 | const newObj: any = {} | |
300 | ||
301 | for (const key of Object.keys(obj)) { | |
302 | // Deprecated key | |
303 | if (key === 'resolution') continue | |
304 | ||
a1587156 | 305 | const value = obj[key] |
e7872038 C |
306 | |
307 | if (typeof value === 'string') { | |
a1587156 | 308 | newObj[key] = value.normalize() |
e7872038 | 309 | } else { |
a1587156 | 310 | newObj[key] = value |
e7872038 C |
311 | } |
312 | } | |
313 | ||
314 | return newObj | |
315 | } | |
61b3e146 C |
316 | |
317 | function fetchObject (info: any) { | |
318 | const url = buildUrl(info) | |
319 | ||
320 | return new Promise<any>(async (res, rej) => { | |
1bcb03a1 | 321 | const youtubeDL = await YoutubeDL.safeGetYoutubeDL() |
a1587156 | 322 | youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => { |
61b3e146 C |
323 | if (err) return rej(err) |
324 | ||
325 | const videoInfoWithUrl = Object.assign(videoInfo, { url }) | |
326 | return res(normalizeObject(videoInfoWithUrl)) | |
327 | }) | |
328 | }) | |
329 | } | |
330 | ||
331 | function buildUrl (info: any) { | |
a41e183c | 332 | const webpageUrl = info.webpage_url as string |
a1587156 | 333 | if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl |
a41e183c | 334 | |
61b3e146 | 335 | const url = info.url as string |
a1587156 | 336 | if (url?.match(/^https?:\/\//)) return url |
61b3e146 C |
337 | |
338 | // It seems youtube-dl does not return the video url | |
339 | return 'https://www.youtube.com/watch?v=' + info.id | |
340 | } | |
a41e183c C |
341 | |
342 | function isNSFW (info: any) { | |
1a12f66d | 343 | return info.age_limit && info.age_limit >= 16 |
a41e183c | 344 | } |
ab4dbe36 | 345 | |
da69b886 C |
346 | function normalizeTargetUrl (url: string) { |
347 | let normalizedUrl = url.replace(/\/+$/, '') | |
348 | ||
4449d269 | 349 | if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) { |
da69b886 C |
350 | normalizedUrl = 'https://' + normalizedUrl |
351 | } | |
352 | ||
353 | return normalizedUrl | |
ab4dbe36 | 354 | } |
1a12f66d C |
355 | |
356 | async function promptPassword () { | |
357 | return new Promise<string>((res, rej) => { | |
358 | prompt.start() | |
359 | const schema = { | |
360 | properties: { | |
361 | password: { | |
362 | hidden: true, | |
363 | required: true | |
364 | } | |
365 | } | |
366 | } | |
367 | prompt.get(schema, function (err, result) { | |
368 | if (err) { | |
369 | return rej(err) | |
370 | } | |
371 | return res(result.password) | |
372 | }) | |
373 | }) | |
374 | } | |
375 | ||
d0198ff9 F |
376 | function parseDate (dateAsStr: string): Date { |
377 | if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) { | |
da69b886 | 378 | exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`) |
d0198ff9 | 379 | } |
da69b886 C |
380 | const date = new Date(dateAsStr) |
381 | date.setHours(0, 0, 0) | |
d0198ff9 | 382 | if (isNaN(date.getTime())) { |
da69b886 | 383 | exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`) |
d0198ff9 | 384 | } |
da69b886 | 385 | return date |
d0198ff9 F |
386 | } |
387 | ||
388 | function formatDate (date: Date): string { | |
a1587156 | 389 | return date.toISOString().split('T')[0] |
d0198ff9 | 390 | } |
bda3b705 | 391 | |
82f5527f F |
392 | function convertIntoMs (secondsAsStr: string): number { |
393 | const seconds = parseInt(secondsAsStr, 10) | |
394 | if (seconds <= 0) { | |
395 | exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`) | |
396 | } | |
397 | return Math.round(seconds * 1000) | |
398 | } | |
399 | ||
da69b886 | 400 | function exitError (message: string, ...meta: any[]) { |
bda3b705 FL |
401 | // use console.error instead of log.error here |
402 | console.error(message, ...meta) | |
403 | process.exit(-1) | |
404 | } | |
de29e90c C |
405 | |
406 | function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) { | |
407 | return new Promise<any>((res, rej) => { | |
408 | const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ] | |
409 | ||
410 | youtubeDL.getInfo(url, options, processOptions, async (err, info) => { | |
411 | if (err) return rej(err) | |
412 | ||
413 | return res(info) | |
414 | }) | |
415 | }) | |
416 | } |