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'
9 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../tests/utils'
10 import { truncate } from 'lodash'
11 import * as prompt from 'prompt'
12 import { remove } from 'fs-extra'
13 import { safeGetYoutubeDL } from '../helpers/youtube-dl'
14 import { getSettings, netrc } from './cli'
16 let accessToken: string
17 let client: { id: string, secret: string }
19 const processOptions = {
25 .name('import-videos')
26 .option('-u, --url <url>', 'Server url')
27 .option('-U, --username <username>', 'Username')
28 .option('-p, --password <token>', 'Password')
29 .option('-t, --target-url <targetUrl>', 'Video target URL')
30 .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)')
31 .option('-v, --verbose', 'Verbose mode')
38 !program['username'] ||
39 !program['password']) &&
40 (settings.remotes.length === 0)
42 if (!program['url']) console.error('--url field is required.')
43 if (!program['username']) console.error('--username field is required.')
44 if (!program['password']) console.error('--password field is required.')
45 if (!program['targetUrl']) console.error('--targetUrl field is required.')
51 !program['username'] ||
52 !program['password']) &&
53 (settings.remotes.length > 0)
55 if (!program['url']) {
56 program['url'] = (settings.default !== -1) ?
57 settings.remotes[settings.default] :
60 if (!program['username']) program['username'] = netrc.machines[program['url']].login
61 if (!program['password']) program['password'] = netrc.machines[program['url']].password
67 if (!program['targetUrl']) console.error('--targetUrl field is required.')
72 username: program['username'],
73 password: program['password']
76 run(user, program['url']).catch(err => console.error(err))
79 async function promptPassword () {
80 return new Promise((res, rej) => {
90 prompt.get(schema, function (err, result) {
94 return res(result.password)
99 async function run (user, url: string) {
100 if (!user.password) {
101 user.password = await promptPassword()
104 const res = await getClient(url)
106 id: res.body.client_id,
107 secret: res.body.client_secret
110 const res2 = await login(url, client, user)
111 accessToken = res2.body.access_token
113 const youtubeDL = await safeGetYoutubeDL()
115 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
116 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
118 console.log(err.message)
124 // Normalize utf8 fields
125 if (Array.isArray(info) === true) {
126 infoArray = info.map(i => normalizeObject(i))
128 infoArray = [ normalizeObject(info) ]
130 console.log('Will download and upload %d videos.\n', infoArray.length)
132 for (const info of infoArray) {
133 await processVideo(info, program['language'], processOptions.cwd, url, user)
136 // https://www.youtube.com/watch?v=2Upx39TBc1s
137 console.log('I\'m finished!')
142 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
143 return new Promise(async res => {
144 if (program['verbose']) console.log('Fetching object.', info)
146 const videoInfo = await fetchObject(info)
147 if (program['verbose']) console.log('Fetched object.', videoInfo)
149 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
151 console.log('############################################################\n')
153 if (result.body.data.find(v => v.name === videoInfo.title)) {
154 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
158 const path = join(cwd, new Date().getTime() + '.mp4')
160 console.log('Downloading video "%s"...', videoInfo.title)
162 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
164 const youtubeDL = await safeGetYoutubeDL()
165 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
171 console.log(output.join('\n'))
172 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
176 console.log(err.message)
182 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
183 const category = await getCategory(videoInfo.categories, url)
184 const licence = getLicence(videoInfo.license)
186 if (Array.isArray(videoInfo.tags)) {
187 tags = videoInfo.tags
188 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
189 .map(t => t.normalize())
194 if (videoInfo.thumbnail) {
195 thumbnailfile = join(cwd, 'thumbnail.jpg')
197 await doRequestAndSaveToFile({
199 uri: videoInfo.thumbnail
203 const videoAttributes = {
204 name: truncate(videoInfo.title, {
205 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
212 nsfw: isNSFW(videoInfo),
213 waitTranscoding: true,
214 commentsEnabled: true,
215 downloadingEnabled: true,
216 description: videoInfo.description || undefined,
219 privacy: VideoPrivacy.PUBLIC,
222 previewfile: thumbnailfile
225 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
227 await uploadVideo(url, accessToken, videoAttributes)
229 if (err.message.indexOf('401') !== -1) {
230 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
232 const res = await login(url, client, user)
233 accessToken = res.body.access_token
235 await uploadVideo(url, accessToken, videoAttributes)
237 console.log(err.message)
242 await remove(videoPath)
243 if (thumbnailfile) await remove(thumbnailfile)
245 console.log('Uploaded video "%s"!\n', videoAttributes.name)
248 async function getCategory (categories: string[], url: string) {
249 if (!categories) return undefined
251 const categoryString = categories[0]
253 if (categoryString === 'News & Politics') return 11
255 const res = await getVideoCategories(url)
256 const categoriesServer = res.body
258 for (const key of Object.keys(categoriesServer)) {
259 const categoryServer = categoriesServer[key]
260 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
266 /* ---------------------------------------------------------- */
268 function getLicence (licence: string) {
269 if (!licence) return undefined
271 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
276 function normalizeObject (obj: any) {
277 const newObj: any = {}
279 for (const key of Object.keys(obj)) {
281 if (key === 'resolution') continue
283 const value = obj[key]
285 if (typeof value === 'string') {
286 newObj[key] = value.normalize()
295 function fetchObject (info: any) {
296 const url = buildUrl(info)
298 return new Promise<any>(async (res, rej) => {
299 const youtubeDL = await safeGetYoutubeDL()
300 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
301 if (err) return rej(err)
303 const videoInfoWithUrl = Object.assign(videoInfo, { url })
304 return res(normalizeObject(videoInfoWithUrl))
309 function buildUrl (info: any) {
310 const webpageUrl = info.webpage_url as string
311 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
313 const url = info.url as string
314 if (url && url.match(/^https?:\/\//)) return url
316 // It seems youtube-dl does not return the video url
317 return 'https://www.youtube.com/watch?v=' + info.id
320 function isNSFW (info: any) {
321 if (info.age_limit && info.age_limit >= 16) return true