1 import { registerTSPaths } from '../helpers/register-ts-paths'
4 // FIXME: https://github.com/nodejs/node/pull/16853
5 require('tls').DEFAULT_ECDH_CURVE = 'auto'
7 import * as program from 'commander'
8 import { join } from 'path'
9 import { doRequestAndSaveToFile } from '../helpers/requests'
10 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
11 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
12 import { truncate } from 'lodash'
13 import * as prompt from 'prompt'
14 import { accessSync, constants } from 'fs'
15 import { remove } from 'fs-extra'
16 import { sha256 } from '../helpers/core-utils'
17 import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
18 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials, getLogger } from './cli'
25 const processOptions = {
30 .name('import-videos')
32 command = buildCommonVideoOptions(command)
35 .option('-u, --url <url>', 'Server url')
36 .option('-U, --username <username>', 'Username')
37 .option('-p, --password <token>', 'Password')
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)
41 .option('--first <first>', 'Process first n elements of returned playlist')
42 .option('--last <last>', 'Process last n elements of returned playlist')
43 .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
46 let log = getLogger(program[ 'verbose' ])
48 getServerCredentials(command)
49 .then(({ url, username, password }) => {
50 if (!program[ 'targetUrl' ]) {
51 exitError('--target-url field is required.')
55 accessSync(program[ 'tmpdir' ], constants.R_OK | constants.W_OK)
57 exitError('--tmpdir %s: directory does not exist or is not accessible', program[ 'tmpdir' ])
60 url = removeEndSlashes(url)
61 program[ 'targetUrl' ] = removeEndSlashes(program[ 'targetUrl' ])
63 const user = { username, password }
71 async function run (url: string, user: UserInfo) {
73 user.password = await promptPassword()
76 const youtubeDL = await safeGetYoutubeDL()
78 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
79 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
81 exitError(err.message)
86 // Normalize utf8 fields
87 infoArray = [].concat(info);
88 if (program[ 'first' ]) {
89 infoArray = infoArray.slice(0, program[ 'first' ])
90 } else if (program[ 'last' ]) {
91 infoArray = infoArray.slice(- program[ 'last' ])
93 infoArray = infoArray.map(i => normalizeObject(i))
95 log.info('Will download and upload %d videos.\n', infoArray.length)
97 for (const info of infoArray) {
99 cwd: program[ 'tmpdir' ],
106 log.info('Video/s for user %s imported: %s', user.username, program[ 'targetUrl' ])
111 function processVideo (parameters: {
114 user: { username: string, password: string },
117 const { youtubeInfo, cwd, url, user } = parameters
119 return new Promise(async res => {
120 log.debug('Fetching object.', youtubeInfo)
122 const videoInfo = await fetchObject(youtubeInfo)
123 log.debug('Fetched object.', videoInfo)
125 if (program[ 'since' ]) {
126 if (buildOriginallyPublishedAt(videoInfo).getTime() < program[ 'since' ].getTime()) {
127 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
128 videoInfo.title, formatDate(program[ 'since' ]));
132 if (program[ 'until' ]) {
133 if (buildOriginallyPublishedAt(videoInfo).getTime() > program[ 'until' ].getTime()) {
134 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
135 videoInfo.title, formatDate(program[ 'until' ]));
140 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
142 log.info('############################################################\n')
144 if (result.body.data.find(v => v.name === videoInfo.title)) {
145 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
149 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
151 log.info('Downloading video "%s"...', videoInfo.title)
153 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
155 const youtubeDL = await safeGetYoutubeDL()
156 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
162 log.info(output.join('\n'))
163 await uploadVideoOnPeerTube({
167 videoInfo: normalizeObject(videoInfo),
173 log.error(err.message)
179 async function uploadVideoOnPeerTube (parameters: {
184 user: { username: string; password: string }
186 const { videoInfo, videoPath, cwd, url, user } = parameters
188 const category = await getCategory(videoInfo.categories, url)
189 const licence = getLicence(videoInfo.license)
191 if (Array.isArray(videoInfo.tags)) {
192 tags = videoInfo.tags
193 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
194 .map(t => t.normalize())
199 if (videoInfo.thumbnail) {
200 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
202 await doRequestAndSaveToFile({
204 uri: videoInfo.thumbnail
208 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
210 const defaultAttributes = {
211 name: truncate(videoInfo.title, {
212 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
218 nsfw: isNSFW(videoInfo),
219 description: videoInfo.description,
223 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
225 Object.assign(videoAttributes, {
226 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
228 previewfile: thumbnailfile,
232 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
234 let accessToken = await getAccessTokenOrDie(url, user)
237 await uploadVideo(url, accessToken, videoAttributes)
239 if (err.message.indexOf('401') !== -1) {
240 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
242 accessToken = await getAccessTokenOrDie(url, user)
244 await uploadVideo(url, accessToken, videoAttributes)
246 exitError(err.message)
250 await remove(videoPath)
251 if (thumbnailfile) await remove(thumbnailfile)
253 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
256 /* ---------------------------------------------------------- */
258 async function getCategory (categories: string[], url: string) {
259 if (!categories) return undefined
261 const categoryString = categories[ 0 ]
263 if (categoryString === 'News & Politics') return 11
265 const res = await getVideoCategories(url)
266 const categoriesServer = res.body
268 for (const key of Object.keys(categoriesServer)) {
269 const categoryServer = categoriesServer[ key ]
270 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
276 function getLicence (licence: string) {
277 if (!licence) return undefined
279 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
284 function normalizeObject (obj: any) {
285 const newObj: any = {}
287 for (const key of Object.keys(obj)) {
289 if (key === 'resolution') continue
291 const value = obj[ key ]
293 if (typeof value === 'string') {
294 newObj[ key ] = value.normalize()
296 newObj[ key ] = value
303 function fetchObject (info: any) {
304 const url = buildUrl(info)
306 return new Promise<any>(async (res, rej) => {
307 const youtubeDL = await safeGetYoutubeDL()
308 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
309 if (err) return rej(err)
311 const videoInfoWithUrl = Object.assign(videoInfo, { url })
312 return res(normalizeObject(videoInfoWithUrl))
317 function buildUrl (info: any) {
318 const webpageUrl = info.webpage_url as string
319 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
321 const url = info.url as string
322 if (url && url.match(/^https?:\/\//)) return url
324 // It seems youtube-dl does not return the video url
325 return 'https://www.youtube.com/watch?v=' + info.id
328 function isNSFW (info: any) {
329 return info.age_limit && info.age_limit >= 16
332 function removeEndSlashes (url: string) {
333 return url.replace(/\/+$/, '')
336 async function promptPassword () {
337 return new Promise<string>((res, rej) => {
347 prompt.get(schema, function (err, result) {
351 return res(result.password)
356 async function getAccessTokenOrDie (url: string, user: UserInfo) {
357 const resClient = await getClient(url)
359 id: resClient.body.client_id,
360 secret: resClient.body.client_secret
364 const res = await login(url, client, user)
365 return res.body.access_token
367 exitError('Cannot authenticate. Please check your username/password.')
371 function parseDate (dateAsStr: string): Date {
372 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
373 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`);
375 const date = new Date(dateAsStr);
376 date.setHours(0, 0, 0);
377 if (isNaN(date.getTime())) {
378 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`);
383 function formatDate (date: Date): string {
384 return date.toISOString().split('T')[0];
387 function exitError (message:string, ...meta: any[]) {
388 // use console.error instead of log.error here
389 console.error(message, ...meta)