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((res, rej) => {
59 prompt.get(schema, function (err, result) {
63 return res(result.password)
68 async function run () {
70 user.password = await promptPassword()
73 const res = await getClient(program['url'])
75 id: res.body.client_id,
76 secret: res.body.client_secret
79 const res2 = await login(program['url'], client, user)
80 accessToken = res2.body.access_token
82 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
83 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
85 console.log(err.message)
91 // Normalize utf8 fields
92 if (Array.isArray(info) === true) {
93 infoArray = info.map(i => normalizeObject(i))
95 infoArray = [ normalizeObject(info) ]
97 console.log('Will download and upload %d videos.\n', infoArray.length)
99 for (const info of infoArray) {
100 await processVideo(info, program['language'])
103 // https://www.youtube.com/watch?v=2Upx39TBc1s
104 console.log('I\'m finished!')
109 function processVideo (info: any, languageCode: string) {
110 return new Promise(async res => {
111 if (program['verbose']) console.log('Fetching object.', info)
113 const videoInfo = await fetchObject(info)
114 if (program['verbose']) console.log('Fetched object.', videoInfo)
116 const result = await searchVideo(program['url'], videoInfo.title)
118 console.log('############################################################\n')
120 if (result.body.data.find(v => v.name === videoInfo.title)) {
121 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
125 const path = join(__dirname, new Date().getTime() + '.mp4')
127 console.log('Downloading video "%s"...', videoInfo.title)
129 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
131 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
137 console.log(output.join('\n'))
138 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
142 console.log(err.message)
148 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: string) {
149 const category = await getCategory(videoInfo.categories)
150 const licence = getLicence(videoInfo.license)
152 if (Array.isArray(videoInfo.tags)) {
153 tags = videoInfo.tags
154 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
155 .map(t => t.normalize())
160 if (videoInfo.thumbnail) {
161 thumbnailfile = join(__dirname, 'thumbnail.jpg')
163 await doRequestAndSaveToFile({
165 uri: videoInfo.thumbnail
169 const videoAttributes = {
170 name: truncate(videoInfo.title, {
171 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
178 nsfw: isNSFW(videoInfo),
179 waitTranscoding: true,
180 commentsEnabled: true,
181 description: videoInfo.description || undefined,
184 privacy: VideoPrivacy.PUBLIC,
187 previewfile: thumbnailfile
190 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
192 await uploadVideo(program['url'], accessToken, videoAttributes)
194 if (err.message.indexOf('401') !== -1) {
195 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
197 const res = await login(program['url'], client, user)
198 accessToken = res.body.access_token
200 await uploadVideo(program['url'], accessToken, videoAttributes)
202 console.log(err.message)
207 await unlinkPromise(videoPath)
209 await unlinkPromise(thumbnailfile)
212 console.log('Uploaded video "%s"!\n', videoAttributes.name)
215 async function getCategory (categories: string[]) {
216 if (!categories) return undefined
218 const categoryString = categories[0]
220 if (categoryString === 'News & Politics') return 11
222 const res = await getVideoCategories(program['url'])
223 const categoriesServer = res.body
225 for (const key of Object.keys(categoriesServer)) {
226 const categoryServer = categoriesServer[key]
227 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
233 function getLicence (licence: string) {
234 if (!licence) return undefined
236 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
241 function normalizeObject (obj: any) {
242 const newObj: any = {}
244 for (const key of Object.keys(obj)) {
246 if (key === 'resolution') continue
248 const value = obj[key]
250 if (typeof value === 'string') {
251 newObj[key] = value.normalize()
260 function fetchObject (info: any) {
261 const url = buildUrl(info)
263 return new Promise<any>(async (res, rej) => {
264 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
265 if (err) return rej(err)
267 const videoInfoWithUrl = Object.assign(videoInfo, { url })
268 return res(normalizeObject(videoInfoWithUrl))
273 function buildUrl (info: any) {
274 const webpageUrl = info.webpage_url as string
275 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
277 const url = info.url as string
278 if (url && url.match(/^https?:\/\//)) return url
280 // It seems youtube-dl does not return the video url
281 return 'https://www.youtube.com/watch?v=' + info.id
284 function isNSFW (info: any) {
285 if (info.age_limit && info.age_limit >= 16) return true