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 { getNetrc, getRemoteObjectOrDie, getSettings } 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')
35 Promise.all([ getSettings(), getNetrc() ])
36 .then(([ settings, netrc ]) => {
37 const { url, username, password } = getRemoteObjectOrDie(program, settings)
39 if (!program[ 'targetUrl' ]) {
40 console.error('--targetUrl field is required.')
46 removeEndSlashes(program[ 'targetUrl' ])
60 async function promptPassword () {
61 return new Promise((res, rej) => {
71 prompt.get(schema, function (err, result) {
75 return res(result.password)
80 async function run (user, url: string) {
82 user.password = await promptPassword()
85 const res = await getClient(url)
87 id: res.body.client_id,
88 secret: res.body.client_secret
92 const res = await login(program[ 'url' ], client, user)
93 accessToken = res.body.access_token
95 throw new Error('Cannot authenticate. Please check your username/password.')
98 const youtubeDL = await safeGetYoutubeDL()
100 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
101 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
103 console.log(err.message)
109 // Normalize utf8 fields
110 if (Array.isArray(info) === true) {
111 infoArray = info.map(i => normalizeObject(i))
113 infoArray = [ normalizeObject(info) ]
115 console.log('Will download and upload %d videos.\n', infoArray.length)
117 for (const info of infoArray) {
118 await processVideo(info, program[ 'language' ], processOptions.cwd, url, user)
121 console.log('Video/s for user %s imported: %s', program[ 'username' ], program[ 'targetUrl' ])
126 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
127 return new Promise(async res => {
128 if (program[ 'verbose' ]) console.log('Fetching object.', info)
130 const videoInfo = await fetchObject(info)
131 if (program[ 'verbose' ]) console.log('Fetched object.', videoInfo)
133 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
135 console.log('############################################################\n')
137 if (result.body.data.find(v => v.name === videoInfo.title)) {
138 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
142 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
144 console.log('Downloading video "%s"...', videoInfo.title)
146 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
148 const youtubeDL = await safeGetYoutubeDL()
149 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
155 console.log(output.join('\n'))
156 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
160 console.log(err.message)
166 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
167 const category = await getCategory(videoInfo.categories, url)
168 const licence = getLicence(videoInfo.license)
170 if (Array.isArray(videoInfo.tags)) {
171 tags = videoInfo.tags
172 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
173 .map(t => t.normalize())
178 if (videoInfo.thumbnail) {
179 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
181 await doRequestAndSaveToFile({
183 uri: videoInfo.thumbnail
187 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
189 const videoAttributes = {
190 name: truncate(videoInfo.title, {
191 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
198 nsfw: isNSFW(videoInfo),
199 waitTranscoding: true,
200 commentsEnabled: true,
201 downloadEnabled: true,
202 description: videoInfo.description || undefined,
205 privacy: VideoPrivacy.PUBLIC,
208 previewfile: thumbnailfile,
209 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null
212 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
214 await uploadVideo(url, accessToken, videoAttributes)
216 if (err.message.indexOf('401') !== -1) {
217 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
219 const res = await login(url, client, user)
220 accessToken = res.body.access_token
222 await uploadVideo(url, accessToken, videoAttributes)
224 console.log(err.message)
229 await remove(videoPath)
230 if (thumbnailfile) await remove(thumbnailfile)
232 console.log('Uploaded video "%s"!\n', videoAttributes.name)
235 async function getCategory (categories: string[], url: string) {
236 if (!categories) return undefined
238 const categoryString = categories[ 0 ]
240 if (categoryString === 'News & Politics') return 11
242 const res = await getVideoCategories(url)
243 const categoriesServer = res.body
245 for (const key of Object.keys(categoriesServer)) {
246 const categoryServer = categoriesServer[ key ]
247 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
253 /* ---------------------------------------------------------- */
255 function getLicence (licence: string) {
256 if (!licence) return undefined
258 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
263 function normalizeObject (obj: any) {
264 const newObj: any = {}
266 for (const key of Object.keys(obj)) {
268 if (key === 'resolution') continue
270 const value = obj[ key ]
272 if (typeof value === 'string') {
273 newObj[ key ] = value.normalize()
275 newObj[ key ] = value
282 function fetchObject (info: any) {
283 const url = buildUrl(info)
285 return new Promise<any>(async (res, rej) => {
286 const youtubeDL = await safeGetYoutubeDL()
287 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
288 if (err) return rej(err)
290 const videoInfoWithUrl = Object.assign(videoInfo, { url })
291 return res(normalizeObject(videoInfoWithUrl))
296 function buildUrl (info: any) {
297 const webpageUrl = info.webpage_url as string
298 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
300 const url = info.url as string
301 if (url && url.match(/^https?:\/\//)) return url
303 // It seems youtube-dl does not return the video url
304 return 'https://www.youtube.com/watch?v=' + info.id
307 function isNSFW (info: any) {
308 if (info.age_limit && info.age_limit >= 16) return true
313 function removeEndSlashes (url: string) {
314 while (url.endsWith('/')) {