1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
4 import * as program from 'commander'
5 import { join } from 'path'
6 import { doRequestAndSaveToFile } from '../helpers/requests'
7 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
8 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
9 import { truncate } from 'lodash'
10 import * as prompt from 'prompt'
11 import { remove } from 'fs-extra'
12 import { sha256 } from '../helpers/core-utils'
13 import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
14 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials } from './cli'
21 const processOptions = {
27 .name('import-videos')
29 command = buildCommonVideoOptions(command)
32 .option('-u, --url <url>', 'Server url')
33 .option('-U, --username <username>', 'Username')
34 .option('-p, --password <token>', 'Password')
35 .option('--target-url <targetUrl>', 'Video target URL')
36 .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate)
37 .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate)
38 .option('-v, --verbose', 'Verbose mode')
41 getServerCredentials(command)
42 .then(({ url, username, password }) => {
43 if (!program[ 'targetUrl' ]) {
44 console.error('--targetUrl field is required.')
50 removeEndSlashes(program[ 'targetUrl' ])
52 const user = { username, password }
61 async function run (url: string, user: UserInfo) {
63 user.password = await promptPassword()
66 const youtubeDL = await safeGetYoutubeDL()
68 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
69 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
71 console.log(err.message)
77 // Normalize utf8 fields
78 if (Array.isArray(info) === true) {
79 infoArray = info.map(i => normalizeObject(i))
81 infoArray = [ normalizeObject(info) ]
83 console.log('Will download and upload %d videos.\n', infoArray.length)
85 for (const info of infoArray) {
87 cwd: processOptions.cwd,
94 console.log('Video/s for user %s imported: %s', program[ 'username' ], program[ 'targetUrl' ])
99 function processVideo (parameters: {
102 user: { username: string, password: string },
105 const { youtubeInfo, cwd, url, user } = parameters
107 return new Promise(async res => {
108 if (program[ 'verbose' ]) console.log('Fetching object.', youtubeInfo)
110 const videoInfo = await fetchObject(youtubeInfo)
111 if (program[ 'verbose' ]) console.log('Fetched object.', videoInfo)
113 if (program[ 'since' ]) {
114 if (buildOriginallyPublishedAt(videoInfo).getTime() < program[ 'since' ].getTime()) {
115 console.log('Video "%s" has been published before "%s", don\'t upload it.\n',
116 videoInfo.title, formatDate(program[ 'since' ]));
120 if (program[ 'until' ]) {
121 if (buildOriginallyPublishedAt(videoInfo).getTime() > program[ 'until' ].getTime()) {
122 console.log('Video "%s" has been published after "%s", don\'t upload it.\n',
123 videoInfo.title, formatDate(program[ 'until' ]));
128 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
130 console.log('############################################################\n')
132 if (result.body.data.find(v => v.name === videoInfo.title)) {
133 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
137 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
139 console.log('Downloading video "%s"...', videoInfo.title)
141 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
143 const youtubeDL = await safeGetYoutubeDL()
144 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
150 console.log(output.join('\n'))
151 await uploadVideoOnPeerTube({
155 videoInfo: normalizeObject(videoInfo),
161 console.log(err.message)
167 async function uploadVideoOnPeerTube (parameters: {
172 user: { username: string; password: string }
174 const { videoInfo, videoPath, cwd, url, user } = parameters
176 const category = await getCategory(videoInfo.categories, url)
177 const licence = getLicence(videoInfo.license)
179 if (Array.isArray(videoInfo.tags)) {
180 tags = videoInfo.tags
181 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
182 .map(t => t.normalize())
187 if (videoInfo.thumbnail) {
188 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
190 await doRequestAndSaveToFile({
192 uri: videoInfo.thumbnail
196 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
198 const defaultAttributes = {
199 name: truncate(videoInfo.title, {
200 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
206 nsfw: isNSFW(videoInfo),
207 description: videoInfo.description,
211 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
213 Object.assign(videoAttributes, {
214 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
216 previewfile: thumbnailfile,
220 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
222 let accessToken = await getAccessTokenOrDie(url, user)
225 await uploadVideo(url, accessToken, videoAttributes)
227 if (err.message.indexOf('401') !== -1) {
228 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
230 accessToken = await getAccessTokenOrDie(url, user)
232 await uploadVideo(url, accessToken, videoAttributes)
234 console.log(err.message)
239 await remove(videoPath)
240 if (thumbnailfile) await remove(thumbnailfile)
242 console.log('Uploaded video "%s"!\n', videoAttributes.name)
245 /* ---------------------------------------------------------- */
247 async function getCategory (categories: string[], url: string) {
248 if (!categories) return undefined
250 const categoryString = categories[ 0 ]
252 if (categoryString === 'News & Politics') return 11
254 const res = await getVideoCategories(url)
255 const categoriesServer = res.body
257 for (const key of Object.keys(categoriesServer)) {
258 const categoryServer = categoriesServer[ key ]
259 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
265 function getLicence (licence: string) {
266 if (!licence) return undefined
268 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
273 function normalizeObject (obj: any) {
274 const newObj: any = {}
276 for (const key of Object.keys(obj)) {
278 if (key === 'resolution') continue
280 const value = obj[ key ]
282 if (typeof value === 'string') {
283 newObj[ key ] = value.normalize()
285 newObj[ key ] = value
292 function fetchObject (info: any) {
293 const url = buildUrl(info)
295 return new Promise<any>(async (res, rej) => {
296 const youtubeDL = await safeGetYoutubeDL()
297 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
298 if (err) return rej(err)
300 const videoInfoWithUrl = Object.assign(videoInfo, { url })
301 return res(normalizeObject(videoInfoWithUrl))
306 function buildUrl (info: any) {
307 const webpageUrl = info.webpage_url as string
308 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
310 const url = info.url as string
311 if (url && url.match(/^https?:\/\//)) return url
313 // It seems youtube-dl does not return the video url
314 return 'https://www.youtube.com/watch?v=' + info.id
317 function isNSFW (info: any) {
318 return info.age_limit && info.age_limit >= 16
321 function removeEndSlashes (url: string) {
322 while (url.endsWith('/')) {
327 async function promptPassword () {
328 return new Promise<string>((res, rej) => {
338 prompt.get(schema, function (err, result) {
342 return res(result.password)
347 async function getAccessTokenOrDie (url: string, user: UserInfo) {
348 const resClient = await getClient(url)
350 id: resClient.body.client_id,
351 secret: resClient.body.client_secret
355 const res = await login(url, client, user)
356 return res.body.access_token
358 console.error('Cannot authenticate. Please check your username/password.')
363 function parseDate (dateAsStr: string): Date {
364 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
365 console.error(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`);
368 const date = new Date(dateAsStr);
369 if (isNaN(date.getTime())) {
370 console.error(`Invalid date passed: ${dateAsStr}. See help for usage.`);
376 function formatDate (date: Date): string {
377 return date.toISOString().split('T')[0];