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/constants'
9 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
10 import { truncate } from 'lodash'
11 import * as prompt from 'prompt'
12 import { remove } from 'fs-extra'
13 import { sha256 } from '../helpers/core-utils'
14 import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
15 import { getNetrc, getRemoteObjectOrDie, getSettings } from './cli'
22 const processOptions = {
28 .name('import-videos')
29 .option('-u, --url <url>', 'Server url')
30 .option('-U, --username <username>', 'Username')
31 .option('-p, --password <token>', 'Password')
32 .option('-t, --target-url <targetUrl>', 'Video target URL')
33 .option('-C, --channel-id <channel_id>', 'Channel ID')
34 .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)')
35 .option('-v, --verbose', 'Verbose mode')
38 Promise.all([ getSettings(), getNetrc() ])
39 .then(([ settings, netrc ]) => {
40 const { url, username, password } = getRemoteObjectOrDie(program, settings, netrc)
42 if (!program[ 'targetUrl' ]) {
43 console.error('--targetUrl field is required.')
49 removeEndSlashes(program[ 'targetUrl' ])
51 const user = { username, password }
60 async function run (url: string, user: UserInfo) {
62 user.password = await promptPassword()
65 const youtubeDL = await safeGetYoutubeDL()
67 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
68 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
70 console.log(err.message)
76 // Normalize utf8 fields
77 if (Array.isArray(info) === true) {
78 infoArray = info.map(i => normalizeObject(i))
80 infoArray = [ normalizeObject(info) ]
82 console.log('Will download and upload %d videos.\n', infoArray.length)
84 for (const info of infoArray) {
86 cwd: processOptions.cwd,
93 console.log('Video/s for user %s imported: %s', program[ 'username' ], program[ 'targetUrl' ])
98 function processVideo (parameters: {
101 user: { username: string, password: string },
104 const { youtubeInfo, cwd, url, user } = parameters
106 return new Promise(async res => {
107 if (program[ 'verbose' ]) console.log('Fetching object.', youtubeInfo)
109 const videoInfo = await fetchObject(youtubeInfo)
110 if (program[ 'verbose' ]) console.log('Fetched object.', videoInfo)
112 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
114 console.log('############################################################\n')
116 if (result.body.data.find(v => v.name === videoInfo.title)) {
117 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
121 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
123 console.log('Downloading video "%s"...', videoInfo.title)
125 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
127 const youtubeDL = await safeGetYoutubeDL()
128 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
134 console.log(output.join('\n'))
135 await uploadVideoOnPeerTube({
139 videoInfo: normalizeObject(videoInfo),
145 console.log(err.message)
151 async function uploadVideoOnPeerTube (parameters: {
156 user: { username: string; password: string }
158 const { videoInfo, videoPath, cwd, url, user } = parameters
160 const category = await getCategory(videoInfo.categories, url)
161 const licence = getLicence(videoInfo.license)
163 if (Array.isArray(videoInfo.tags)) {
164 tags = videoInfo.tags
165 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
166 .map(t => t.normalize())
171 if (videoInfo.thumbnail) {
172 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
174 await doRequestAndSaveToFile({
176 uri: videoInfo.thumbnail
180 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
182 const videoAttributes = {
183 name: truncate(videoInfo.title, {
184 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
190 language: program[ 'language' ],
191 nsfw: isNSFW(videoInfo),
192 waitTranscoding: true,
193 commentsEnabled: true,
194 downloadEnabled: true,
195 description: videoInfo.description || undefined,
198 privacy: VideoPrivacy.PUBLIC,
201 previewfile: thumbnailfile,
202 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null
205 if (program[ 'channelId' ]) {
206 Object.assign(videoAttributes, { channelId: program['channelId'] })
209 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
211 let accessToken = await getAccessTokenOrDie(url, user)
214 await uploadVideo(url, accessToken, videoAttributes)
216 if (err.message.indexOf('401') !== -1) {
217 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
219 accessToken = await getAccessTokenOrDie(url, user)
221 await uploadVideo(url, accessToken, videoAttributes)
223 console.log(err.message)
228 await remove(videoPath)
229 if (thumbnailfile) await remove(thumbnailfile)
231 console.log('Uploaded video "%s"!\n', videoAttributes.name)
234 /* ---------------------------------------------------------- */
236 async function getCategory (categories: string[], url: string) {
237 if (!categories) return undefined
239 const categoryString = categories[ 0 ]
241 if (categoryString === 'News & Politics') return 11
243 const res = await getVideoCategories(url)
244 const categoriesServer = res.body
246 for (const key of Object.keys(categoriesServer)) {
247 const categoryServer = categoriesServer[ key ]
248 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
254 function getLicence (licence: string) {
255 if (!licence) return undefined
257 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
262 function normalizeObject (obj: any) {
263 const newObj: any = {}
265 for (const key of Object.keys(obj)) {
267 if (key === 'resolution') continue
269 const value = obj[ key ]
271 if (typeof value === 'string') {
272 newObj[ key ] = value.normalize()
274 newObj[ key ] = value
281 function fetchObject (info: any) {
282 const url = buildUrl(info)
284 return new Promise<any>(async (res, rej) => {
285 const youtubeDL = await safeGetYoutubeDL()
286 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
287 if (err) return rej(err)
289 const videoInfoWithUrl = Object.assign(videoInfo, { url })
290 return res(normalizeObject(videoInfoWithUrl))
295 function buildUrl (info: any) {
296 const webpageUrl = info.webpage_url as string
297 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
299 const url = info.url as string
300 if (url && url.match(/^https?:\/\//)) return url
302 // It seems youtube-dl does not return the video url
303 return 'https://www.youtube.com/watch?v=' + info.id
306 function isNSFW (info: any) {
307 return info.age_limit && info.age_limit >= 16
310 function removeEndSlashes (url: string) {
311 while (url.endsWith('/')) {
316 async function promptPassword () {
317 return new Promise<string>((res, rej) => {
327 prompt.get(schema, function (err, result) {
331 return res(result.password)
336 async function getAccessTokenOrDie (url: string, user: UserInfo) {
337 const resClient = await getClient(url)
339 id: resClient.body.client_id,
340 secret: resClient.body.client_secret
344 const res = await login(url, client, user)
345 return res.body.access_token
347 console.error('Cannot authenticate. Please check your username/password.')