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 * as youtubeDL from 'youtube-dl'
7 import { VideoPrivacy } from '../../shared/models/videos'
8 import { unlinkPromise } from '../helpers/core-utils'
9 import { doRequestAndSaveToFile } from '../helpers/requests'
10 import { CONSTRAINTS_FIELDS } from '../initializers'
11 import { getClient, getVideoCategories, login, searchVideo, uploadVideo } from '../tests/utils'
12 import { truncate } from 'lodash'
13 import * as prompt from 'prompt'
16 .option('-u, --url <url>', 'Server url')
17 .option('-U, --username <username>', 'Username')
18 .option('-p, --password <token>', 'Password')
19 .option('-t, --target-url <targetUrl>', 'Video target URL')
20 .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)')
21 .option('-v, --verbose', 'Verbose mode')
26 !program['username'] ||
29 console.error('All arguments are required.')
34 username: program['username'],
35 password: program['password']
38 run().catch(err => console.error(err))
40 let accessToken: string
41 let client: { id: string, secret: string }
43 const processOptions = {
48 async function promptPassword () {
49 return new Promise ( resolve => {
59 prompt.get(schema, function(err, result) {
61 console.log(err.message)
63 resolve(result.password)
68 async function run () {
72 user.password = await promptPassword();
75 const res = await getClient(program['url'])
77 id: res.body.client_id,
78 secret: res.body.client_secret
81 const res2 = await login(program['url'], client, user)
82 accessToken = res2.body.access_token
84 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
85 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
87 console.log(err.message)
93 // Normalize utf8 fields
94 if (Array.isArray(info) === true) {
95 infoArray = info.map(i => normalizeObject(i))
97 infoArray = [ normalizeObject(info) ]
99 console.log('Will download and upload %d videos.\n', infoArray.length)
101 for (const info of infoArray) {
102 await processVideo(info, program['language'])
105 // https://www.youtube.com/watch?v=2Upx39TBc1s
106 console.log('I\'m finished!')
111 function processVideo (info: any, languageCode: string) {
112 return new Promise(async res => {
113 if (program['verbose']) console.log('Fetching object.', info)
115 const videoInfo = await fetchObject(info)
116 if (program['verbose']) console.log('Fetched object.', videoInfo)
118 const result = await searchVideo(program['url'], videoInfo.title)
120 console.log('############################################################\n')
122 if (result.body.data.find(v => v.name === videoInfo.title)) {
123 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
127 const path = join(__dirname, new Date().getTime() + '.mp4')
129 console.log('Downloading video "%s"...', videoInfo.title)
131 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
133 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
139 console.log(output.join('\n'))
140 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
144 console.log(err.message)
150 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: string) {
151 const category = await getCategory(videoInfo.categories)
152 const licence = getLicence(videoInfo.license)
154 if (Array.isArray(videoInfo.tags)) {
155 tags = videoInfo.tags
156 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
157 .map(t => t.normalize())
162 if (videoInfo.thumbnail) {
163 thumbnailfile = join(__dirname, 'thumbnail.jpg')
165 await doRequestAndSaveToFile({
167 uri: videoInfo.thumbnail
171 const videoAttributes = {
172 name: truncate(videoInfo.title, {
173 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
180 nsfw: isNSFW(videoInfo),
181 commentsEnabled: true,
182 description: videoInfo.description || undefined,
185 privacy: VideoPrivacy.PUBLIC,
188 previewfile: thumbnailfile
191 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
193 await uploadVideo(program['url'], accessToken, videoAttributes)
195 if (err.message.indexOf('401') !== -1) {
196 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
198 const res = await login(program['url'], client, user)
199 accessToken = res.body.access_token
201 await uploadVideo(program['url'], accessToken, videoAttributes)
203 console.log(err.message)
208 await unlinkPromise(videoPath)
210 await unlinkPromise(thumbnailfile)
213 console.log('Uploaded video "%s"!\n', videoAttributes.name)
216 async function getCategory (categories: string[]) {
217 if (!categories) return undefined
219 const categoryString = categories[0]
221 if (categoryString === 'News & Politics') return 11
223 const res = await getVideoCategories(program['url'])
224 const categoriesServer = res.body
226 for (const key of Object.keys(categoriesServer)) {
227 const categoryServer = categoriesServer[key]
228 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
234 function getLicence (licence: string) {
235 if (!licence) return undefined
237 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
242 function normalizeObject (obj: any) {
243 const newObj: any = {}
245 for (const key of Object.keys(obj)) {
247 if (key === 'resolution') continue
249 const value = obj[key]
251 if (typeof value === 'string') {
252 newObj[key] = value.normalize()
261 function fetchObject (info: any) {
262 const url = buildUrl(info)
264 return new Promise<any>(async (res, rej) => {
265 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
266 if (err) return rej(err)
268 const videoInfoWithUrl = Object.assign(videoInfo, { url })
269 return res(normalizeObject(videoInfoWithUrl))
274 function buildUrl (info: any) {
275 const webpageUrl = info.webpage_url as string
276 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
278 const url = info.url as string
279 if (url && url.match(/^https?:\/\//)) return url
281 // It seems youtube-dl does not return the video url
282 return 'https://www.youtube.com/watch?v=' + info.id
285 function isNSFW (info: any) {
286 if (info.age_limit && info.age_limit >= 16) return true