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 { VideoPrivacy } from '../../shared/models/videos'
7 import { doRequestAndSaveToFile } from '../helpers/requests'
8 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
9 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
10 import { truncate } from 'lodash'
11 import * as prompt from 'prompt'
12 import { remove } from 'fs-extra'
13 import { sha256 } from '../helpers/core-utils'
14 import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
15 import { getSettings, netrc } from './cli'
17 let accessToken: string
18 let client: { id: string, secret: string }
20 const processOptions = {
26 .name('import-videos')
27 .option('-u, --url <url>', 'Server url')
28 .option('-U, --username <username>', 'Username')
29 .option('-p, --password <token>', 'Password')
30 .option('-t, --target-url <targetUrl>', 'Video target URL')
31 .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)')
32 .option('-v, --verbose', 'Verbose mode')
37 if ((!program['url'] || !program['username'] || !program['targetUrl']) && settings.remotes.length === 0) {
38 if (!program['url']) console.error('--url field is required.')
39 if (!program['username']) console.error('--username field is required.')
40 if (!program['targetUrl']) console.error('--targetUrl field is required.')
45 if ((!program[ 'url' ] || !program[ 'username' ]) && settings.remotes.length > 0) {
46 if (!program[ 'url' ]) {
47 program[ 'url' ] = settings.default !== -1
48 ? settings.remotes[ settings.default ]
49 : settings.remotes[ 0 ]
52 if (!program['username']) program['username'] = netrc.machines[program['url']].login
53 if (!program['password']) program['password'] = netrc.machines[program['url']].password
59 if (!program['targetUrl']) console.error('--targetUrl field is required.')
63 removeEndSlashes(program['url'])
64 removeEndSlashes(program['targetUrl'])
67 username: program['username'],
68 password: program['password']
71 run(user, program['url'])
78 async function promptPassword () {
79 return new Promise((res, rej) => {
89 prompt.get(schema, function (err, result) {
93 return res(result.password)
98 async function run (user, url: string) {
100 user.password = await promptPassword()
103 const res = await getClient(url)
105 id: res.body.client_id,
106 secret: res.body.client_secret
110 const res = await login(program[ 'url' ], client, user)
111 accessToken = res.body.access_token
113 throw new Error('Cannot authenticate. Please check your username/password.')
116 const youtubeDL = await safeGetYoutubeDL()
118 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
119 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
121 console.log(err.message)
127 // Normalize utf8 fields
128 if (Array.isArray(info) === true) {
129 infoArray = info.map(i => normalizeObject(i))
131 infoArray = [ normalizeObject(info) ]
133 console.log('Will download and upload %d videos.\n', infoArray.length)
135 for (const info of infoArray) {
136 await processVideo(info, program['language'], processOptions.cwd, url, user)
139 console.log('Video/s for user %s imported: %s', program['username'], program['targetUrl'])
144 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
145 return new Promise(async res => {
146 if (program['verbose']) console.log('Fetching object.', info)
148 const videoInfo = await fetchObject(info)
149 if (program['verbose']) console.log('Fetched object.', videoInfo)
151 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
153 console.log('############################################################\n')
155 if (result.body.data.find(v => v.name === videoInfo.title)) {
156 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
160 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
162 console.log('Downloading video "%s"...', videoInfo.title)
164 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
166 const youtubeDL = await safeGetYoutubeDL()
167 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
173 console.log(output.join('\n'))
174 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
178 console.log(err.message)
184 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
185 const category = await getCategory(videoInfo.categories, url)
186 const licence = getLicence(videoInfo.license)
188 if (Array.isArray(videoInfo.tags)) {
189 tags = videoInfo.tags
190 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
191 .map(t => t.normalize())
196 if (videoInfo.thumbnail) {
197 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
199 await doRequestAndSaveToFile({
201 uri: videoInfo.thumbnail
205 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
207 const videoAttributes = {
208 name: truncate(videoInfo.title, {
209 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
216 nsfw: isNSFW(videoInfo),
217 waitTranscoding: true,
218 commentsEnabled: true,
219 downloadEnabled: true,
220 description: videoInfo.description || undefined,
223 privacy: VideoPrivacy.PUBLIC,
226 previewfile: thumbnailfile,
227 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null
230 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
232 await uploadVideo(url, accessToken, videoAttributes)
234 if (err.message.indexOf('401') !== -1) {
235 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
237 const res = await login(url, client, user)
238 accessToken = res.body.access_token
240 await uploadVideo(url, accessToken, videoAttributes)
242 console.log(err.message)
247 await remove(videoPath)
248 if (thumbnailfile) await remove(thumbnailfile)
250 console.log('Uploaded video "%s"!\n', videoAttributes.name)
253 async function getCategory (categories: string[], url: string) {
254 if (!categories) return undefined
256 const categoryString = categories[0]
258 if (categoryString === 'News & Politics') return 11
260 const res = await getVideoCategories(url)
261 const categoriesServer = res.body
263 for (const key of Object.keys(categoriesServer)) {
264 const categoryServer = categoriesServer[key]
265 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
271 /* ---------------------------------------------------------- */
273 function getLicence (licence: string) {
274 if (!licence) return undefined
276 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
281 function normalizeObject (obj: any) {
282 const newObj: any = {}
284 for (const key of Object.keys(obj)) {
286 if (key === 'resolution') continue
288 const value = obj[key]
290 if (typeof value === 'string') {
291 newObj[key] = value.normalize()
300 function fetchObject (info: any) {
301 const url = buildUrl(info)
303 return new Promise<any>(async (res, rej) => {
304 const youtubeDL = await safeGetYoutubeDL()
305 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
306 if (err) return rej(err)
308 const videoInfoWithUrl = Object.assign(videoInfo, { url })
309 return res(normalizeObject(videoInfoWithUrl))
314 function buildUrl (info: any) {
315 const webpageUrl = info.webpage_url as string
316 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
318 const url = info.url as string
319 if (url && url.match(/^https?:\/\//)) return url
321 // It seems youtube-dl does not return the video url
322 return 'https://www.youtube.com/watch?v=' + info.id
325 function isNSFW (info: any) {
326 if (info.age_limit && info.age_limit >= 16) return true
331 function removeEndSlashes (url: string) {
332 while (url.endsWith('/')) {