1 import * as program from 'commander'
2 import { join } from 'path'
3 import * as youtubeDL from 'youtube-dl'
4 import { VideoPrivacy } from '../../shared/models/videos'
5 import { unlinkPromise } from '../helpers/core-utils'
6 import { doRequestAndSaveToFile } from '../helpers/requests'
7 import { CONSTRAINTS_FIELDS } from '../initializers'
8 import { getClient, getVideoCategories, login, searchVideo, uploadVideo } from '../tests/utils'
9 import { truncate } from 'lodash'
12 .option('-u, --url <url>', 'Server url')
13 .option('-U, --username <username>', 'Username')
14 .option('-p, --password <token>', 'Password')
15 .option('-t, --target-url <targetUrl>', 'Video target URL')
16 .option('-l, --language <languageCode>', 'Language code')
17 .option('-v, --verbose', 'Verbose mode')
22 !program['username'] ||
23 !program['password'] ||
26 console.error('All arguments are required.')
30 run().catch(err => console.error(err))
32 let accessToken: string
33 let client: { id: string, secret: string }
36 username: program['username'],
37 password: program['password']
40 const processOptions = {
45 async function run () {
46 const res = await getClient(program['url'])
48 id: res.body.client_id,
49 secret: res.body.client_secret
52 const res2 = await login(program['url'], client, user)
53 accessToken = res2.body.access_token
55 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
56 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
58 console.log(err.message)
64 // Normalize utf8 fields
65 if (Array.isArray(info) === true) {
66 infoArray = info.map(i => normalizeObject(i))
68 infoArray = [ normalizeObject(info) ]
70 console.log('Will download and upload %d videos.\n', infoArray.length)
72 for (const info of infoArray) {
73 await processVideo(info, program['language'])
76 // https://www.youtube.com/watch?v=2Upx39TBc1s
77 console.log('I\'m finished!')
82 function processVideo (info: any, languageCode: number) {
83 return new Promise(async res => {
84 if (program['verbose']) console.log('Fetching object.', info)
86 const videoInfo = await fetchObject(info)
87 if (program['verbose']) console.log('Fetched object.', videoInfo)
89 const result = await searchVideo(program['url'], videoInfo.title)
91 console.log('############################################################\n')
93 if (result.body.data.find(v => v.name === videoInfo.title)) {
94 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
98 const path = join(__dirname, new Date().getTime() + '.mp4')
100 console.log('Downloading video "%s"...', videoInfo.title)
102 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
103 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
104 if (err) return console.error(err)
106 console.log(output.join('\n'))
108 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
115 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: number) {
116 const category = await getCategory(videoInfo.categories)
117 const licence = getLicence(videoInfo.license)
119 if (Array.isArray(videoInfo.tags)) {
120 tags = videoInfo.tags
121 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
122 .map(t => t.normalize())
127 if (videoInfo.thumbnail) {
128 thumbnailfile = join(__dirname, 'thumbnail.jpg')
130 await doRequestAndSaveToFile({
132 uri: videoInfo.thumbnail
136 const videoAttributes = {
137 name: truncate(videoInfo.title, {
138 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
145 nsfw: isNSFW(videoInfo),
146 commentsEnabled: true,
147 description: videoInfo.description,
150 privacy: VideoPrivacy.PUBLIC,
153 previewfile: thumbnailfile
156 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
158 await uploadVideo(program['url'], accessToken, videoAttributes)
160 if (err.message.indexOf('401') !== -1) {
161 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
163 const res = await login(program['url'], client, user)
164 accessToken = res.body.access_token
166 await uploadVideo(program['url'], accessToken, videoAttributes)
168 console.log(err.message)
173 await unlinkPromise(videoPath)
175 await unlinkPromise(thumbnailfile)
178 console.log('Uploaded video "%s"!\n', videoAttributes.name)
181 async function getCategory (categories: string[]) {
182 if (!categories) return undefined
184 const categoryString = categories[0]
186 if (categoryString === 'News & Politics') return 11
188 const res = await getVideoCategories(program['url'])
189 const categoriesServer = res.body
191 for (const key of Object.keys(categoriesServer)) {
192 const categoryServer = categoriesServer[key]
193 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
199 function getLicence (licence: string) {
200 if (!licence) return undefined
202 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
207 function normalizeObject (obj: any) {
208 const newObj: any = {}
210 for (const key of Object.keys(obj)) {
212 if (key === 'resolution') continue
214 const value = obj[key]
216 if (typeof value === 'string') {
217 newObj[key] = value.normalize()
226 function fetchObject (info: any) {
227 const url = buildUrl(info)
229 return new Promise<any>(async (res, rej) => {
230 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
231 if (err) return rej(err)
233 const videoInfoWithUrl = Object.assign(videoInfo, { url })
234 return res(normalizeObject(videoInfoWithUrl))
239 function buildUrl (info: any) {
240 const webpageUrl = info.webpage_url as string
241 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
243 const url = info.url as string
244 if (url && url.match(/^https?:\/\//)) return url
246 // It seems youtube-dl does not return the video url
247 return 'https://www.youtube.com/watch?v=' + info.id
250 function isNSFW (info: any) {
251 if (info.age_limit && info.age_limit >= 16) return true