1 import { registerTSPaths } from '../helpers/register-ts-paths'
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 { accessSync, constants } from 'fs'
12 import { remove } from 'fs-extra'
13 import { sha256 } from '../helpers/core-utils'
14 import { buildOriginallyPublishedAt, getYoutubeDLVideoFormat, safeGetYoutubeDL } from '../helpers/youtube-dl'
15 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli'
22 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('--target-url <targetUrl>', 'Video target URL')
36 .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate)
37 .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate)
38 .option('--first <first>', 'Process first n elements of returned playlist')
39 .option('--last <last>', 'Process last n elements of returned playlist')
40 .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
41 .usage("[global options] [ -- youtube-dl options]")
44 const log = getLogger(program['verbose'])
46 getServerCredentials(command)
47 .then(({ url, username, password }) => {
48 if (!program['targetUrl']) {
49 exitError('--target-url field is required.')
53 accessSync(program['tmpdir'], constants.R_OK | constants.W_OK)
55 exitError('--tmpdir %s: directory does not exist or is not accessible', program['tmpdir'])
58 url = normalizeTargetUrl(url)
59 program['targetUrl'] = normalizeTargetUrl(program['targetUrl'])
61 const user = { username, password }
64 .catch(err => exitError(err))
66 .catch(err => console.error(err))
68 async function run (url: string, user: UserInfo) {
70 user.password = await promptPassword()
73 const youtubeDL = await safeGetYoutubeDL()
75 let info = await getYoutubeDLInfo(youtubeDL, program['targetUrl'], command.args)
77 if (!Array.isArray(info)) info = [ info ]
79 // Try to fix youtube channels upload
80 const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads')
83 console.log('Fixing URL to %s.', uploadsObject.url)
85 info = await getYoutubeDLInfo(youtubeDL, uploadsObject.url, command.args)
90 // Normalize utf8 fields
91 infoArray = [].concat(info)
92 if (program['first']) {
93 infoArray = infoArray.slice(0, program['first'])
94 } else if (program['last']) {
95 infoArray = infoArray.slice(-program['last'])
97 infoArray = infoArray.map(i => normalizeObject(i))
99 log.info('Will download and upload %d videos.\n', infoArray.length)
101 for (const info of infoArray) {
104 cwd: program['tmpdir'],
110 console.error('Cannot process video.', { info, url })
114 log.info('Video/s for user %s imported: %s', user.username, program['targetUrl'])
118 function processVideo (parameters: {
121 user: { username: string, password: string }
124 const { youtubeInfo, cwd, url, user } = parameters
126 return new Promise(async res => {
127 log.debug('Fetching object.', youtubeInfo)
129 const videoInfo = await fetchObject(youtubeInfo)
130 log.debug('Fetched object.', videoInfo)
132 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
134 if (program['since'] && originallyPublishedAt && originallyPublishedAt.getTime() < program['since'].getTime()) {
135 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
136 videoInfo.title, formatDate(program['since']))
140 if (program['until'] && originallyPublishedAt && originallyPublishedAt.getTime() > program['until'].getTime()) {
141 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
142 videoInfo.title, formatDate(program['until']))
146 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
148 log.info('############################################################\n')
150 if (result.body.data.find(v => v.name === videoInfo.title)) {
151 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
155 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
157 log.info('Downloading video "%s"...', videoInfo.title)
159 const options = [ '-f', getYoutubeDLVideoFormat(), ...command.args, '-o', path ]
161 const youtubeDL = await safeGetYoutubeDL()
162 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
168 log.info(output.join('\n'))
169 await uploadVideoOnPeerTube({
173 videoInfo: normalizeObject(videoInfo),
179 log.error(err.message)
185 async function uploadVideoOnPeerTube (parameters: {
190 user: { username: string, password: string }
192 const { videoInfo, videoPath, cwd, url, user } = parameters
194 const category = await getCategory(videoInfo.categories, url)
195 const licence = getLicence(videoInfo.license)
197 if (Array.isArray(videoInfo.tags)) {
198 tags = videoInfo.tags
199 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
200 .map(t => t.normalize())
205 if (videoInfo.thumbnail) {
206 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
208 await doRequestAndSaveToFile({
210 uri: videoInfo.thumbnail
214 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
216 const defaultAttributes = {
217 name: truncate(videoInfo.title, {
218 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
224 nsfw: isNSFW(videoInfo),
225 description: videoInfo.description,
229 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
231 Object.assign(videoAttributes, {
232 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
234 previewfile: thumbnailfile,
238 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
240 let accessToken = await getAccessTokenOrDie(url, user)
243 await uploadVideo(url, accessToken, videoAttributes)
245 if (err.message.indexOf('401') !== -1) {
246 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
248 accessToken = await getAccessTokenOrDie(url, user)
250 await uploadVideo(url, accessToken, videoAttributes)
252 exitError(err.message)
256 await remove(videoPath)
257 if (thumbnailfile) await remove(thumbnailfile)
259 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
262 /* ---------------------------------------------------------- */
264 async function getCategory (categories: string[], url: string) {
265 if (!categories) return undefined
267 const categoryString = categories[0]
269 if (categoryString === 'News & Politics') return 11
271 const res = await getVideoCategories(url)
272 const categoriesServer = res.body
274 for (const key of Object.keys(categoriesServer)) {
275 const categoryServer = categoriesServer[key]
276 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
282 function getLicence (licence: string) {
283 if (!licence) return undefined
285 if (licence.includes('Creative Commons Attribution licence')) return 1
290 function normalizeObject (obj: any) {
291 const newObj: any = {}
293 for (const key of Object.keys(obj)) {
295 if (key === 'resolution') continue
297 const value = obj[key]
299 if (typeof value === 'string') {
300 newObj[key] = value.normalize()
309 function fetchObject (info: any) {
310 const url = buildUrl(info)
312 return new Promise<any>(async (res, rej) => {
313 const youtubeDL = await safeGetYoutubeDL()
314 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
315 if (err) return rej(err)
317 const videoInfoWithUrl = Object.assign(videoInfo, { url })
318 return res(normalizeObject(videoInfoWithUrl))
323 function buildUrl (info: any) {
324 const webpageUrl = info.webpage_url as string
325 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
327 const url = info.url as string
328 if (url?.match(/^https?:\/\//)) return url
330 // It seems youtube-dl does not return the video url
331 return 'https://www.youtube.com/watch?v=' + info.id
334 function isNSFW (info: any) {
335 return info.age_limit && info.age_limit >= 16
338 function normalizeTargetUrl (url: string) {
339 let normalizedUrl = url.replace(/\/+$/, '')
341 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
342 normalizedUrl = 'https://' + normalizedUrl
348 async function promptPassword () {
349 return new Promise<string>((res, rej) => {
359 prompt.get(schema, function (err, result) {
363 return res(result.password)
368 async function getAccessTokenOrDie (url: string, user: UserInfo) {
369 const resClient = await getClient(url)
371 id: resClient.body.client_id,
372 secret: resClient.body.client_secret
376 const res = await login(url, client, user)
377 return res.body.access_token
379 exitError('Cannot authenticate. Please check your username/password.')
383 function parseDate (dateAsStr: string): Date {
384 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
385 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
387 const date = new Date(dateAsStr)
388 date.setHours(0, 0, 0)
389 if (isNaN(date.getTime())) {
390 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
395 function formatDate (date: Date): string {
396 return date.toISOString().split('T')[0]
399 function exitError (message: string, ...meta: any[]) {
400 // use console.error instead of log.error here
401 console.error(message, ...meta)
405 function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) {
406 return new Promise<any>((res, rej) => {
407 const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ]
409 youtubeDL.getInfo(url, options, processOptions, async (err, info) => {
410 if (err) return rej(err)