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 { doRequestAndSaveToFile } from '../helpers/requests'
7 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
8 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
9 import { truncate } from 'lodash'
10 import * as prompt from 'prompt'
11 import { remove } from 'fs-extra'
12 import { sha256 } from '../helpers/core-utils'
13 import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
14 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials } from './cli'
21 const processOptions = {
27 .name('import-videos')
29 command = buildCommonVideoOptions(command)
32 .option('-u, --url <url>', 'Server url')
33 .option('-U, --username <username>', 'Username')
34 .option('-p, --password <token>', 'Password')
35 .option('-t, --target-url <targetUrl>', 'Video target URL')
36 .option('-v, --verbose', 'Verbose mode')
39 getServerCredentials(command)
40 .then(({ url, username, password }) => {
41 if (!program[ 'targetUrl' ]) {
42 console.error('--targetUrl field is required.')
48 removeEndSlashes(program[ 'targetUrl' ])
50 const user = { username, password }
59 async function run (url: string, user: UserInfo) {
61 user.password = await promptPassword()
64 const youtubeDL = await safeGetYoutubeDL()
66 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
67 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
69 console.log(err.message)
75 // Normalize utf8 fields
76 if (Array.isArray(info) === true) {
77 infoArray = info.map(i => normalizeObject(i))
79 infoArray = [ normalizeObject(info) ]
81 console.log('Will download and upload %d videos.\n', infoArray.length)
83 for (const info of infoArray) {
85 cwd: processOptions.cwd,
92 console.log('Video/s for user %s imported: %s', program[ 'username' ], program[ 'targetUrl' ])
97 function processVideo (parameters: {
100 user: { username: string, password: string },
103 const { youtubeInfo, cwd, url, user } = parameters
105 return new Promise(async res => {
106 if (program[ 'verbose' ]) console.log('Fetching object.', youtubeInfo)
108 const videoInfo = await fetchObject(youtubeInfo)
109 if (program[ 'verbose' ]) console.log('Fetched object.', videoInfo)
111 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
113 console.log('############################################################\n')
115 if (result.body.data.find(v => v.name === videoInfo.title)) {
116 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
120 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
122 console.log('Downloading video "%s"...', videoInfo.title)
124 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
126 const youtubeDL = await safeGetYoutubeDL()
127 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
133 console.log(output.join('\n'))
134 await uploadVideoOnPeerTube({
138 videoInfo: normalizeObject(videoInfo),
144 console.log(err.message)
150 async function uploadVideoOnPeerTube (parameters: {
155 user: { username: string; password: string }
157 const { videoInfo, videoPath, cwd, url, user } = parameters
159 const category = await getCategory(videoInfo.categories, url)
160 const licence = getLicence(videoInfo.license)
162 if (Array.isArray(videoInfo.tags)) {
163 tags = videoInfo.tags
164 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
165 .map(t => t.normalize())
170 if (videoInfo.thumbnail) {
171 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
173 await doRequestAndSaveToFile({
175 uri: videoInfo.thumbnail
179 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
181 const defaultAttributes = {
182 name: truncate(videoInfo.title, {
183 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
189 nsfw: isNSFW(videoInfo),
190 description: videoInfo.description,
194 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
196 Object.assign(videoAttributes, {
197 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
199 previewfile: thumbnailfile,
203 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
205 let accessToken = await getAccessTokenOrDie(url, user)
208 await uploadVideo(url, accessToken, videoAttributes)
210 if (err.message.indexOf('401') !== -1) {
211 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
213 accessToken = await getAccessTokenOrDie(url, user)
215 await uploadVideo(url, accessToken, videoAttributes)
217 console.log(err.message)
222 await remove(videoPath)
223 if (thumbnailfile) await remove(thumbnailfile)
225 console.log('Uploaded video "%s"!\n', videoAttributes.name)
228 /* ---------------------------------------------------------- */
230 async function getCategory (categories: string[], url: string) {
231 if (!categories) return undefined
233 const categoryString = categories[ 0 ]
235 if (categoryString === 'News & Politics') return 11
237 const res = await getVideoCategories(url)
238 const categoriesServer = res.body
240 for (const key of Object.keys(categoriesServer)) {
241 const categoryServer = categoriesServer[ key ]
242 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
248 function getLicence (licence: string) {
249 if (!licence) return undefined
251 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
256 function normalizeObject (obj: any) {
257 const newObj: any = {}
259 for (const key of Object.keys(obj)) {
261 if (key === 'resolution') continue
263 const value = obj[ key ]
265 if (typeof value === 'string') {
266 newObj[ key ] = value.normalize()
268 newObj[ key ] = value
275 function fetchObject (info: any) {
276 const url = buildUrl(info)
278 return new Promise<any>(async (res, rej) => {
279 const youtubeDL = await safeGetYoutubeDL()
280 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
281 if (err) return rej(err)
283 const videoInfoWithUrl = Object.assign(videoInfo, { url })
284 return res(normalizeObject(videoInfoWithUrl))
289 function buildUrl (info: any) {
290 const webpageUrl = info.webpage_url as string
291 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
293 const url = info.url as string
294 if (url && url.match(/^https?:\/\//)) return url
296 // It seems youtube-dl does not return the video url
297 return 'https://www.youtube.com/watch?v=' + info.id
300 function isNSFW (info: any) {
301 return info.age_limit && info.age_limit >= 16
304 function removeEndSlashes (url: string) {
305 while (url.endsWith('/')) {
310 async function promptPassword () {
311 return new Promise<string>((res, rej) => {
321 prompt.get(schema, function (err, result) {
325 return res(result.password)
330 async function getAccessTokenOrDie (url: string, user: UserInfo) {
331 const resClient = await getClient(url)
333 id: resClient.body.client_id,
334 secret: resClient.body.client_secret
338 const res = await login(url, client, user)
339 return res.body.access_token
341 console.error('Cannot authenticate. Please check your username/password.')