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, 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 const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...command.args ]
77 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
79 exitError(err.stderr + ' ' + err.message)
84 // Normalize utf8 fields
85 infoArray = [].concat(info)
86 if (program['first']) {
87 infoArray = infoArray.slice(0, program['first'])
88 } else if (program['last']) {
89 infoArray = infoArray.slice(-program['last'])
91 infoArray = infoArray.map(i => normalizeObject(i))
93 log.info('Will download and upload %d videos.\n', infoArray.length)
95 for (const info of infoArray) {
97 cwd: program['tmpdir'],
104 log.info('Video/s for user %s imported: %s', user.username, program['targetUrl'])
109 function processVideo (parameters: {
112 user: { username: string, password: string }
115 const { youtubeInfo, cwd, url, user } = parameters
117 return new Promise(async res => {
118 log.debug('Fetching object.', youtubeInfo)
120 const videoInfo = await fetchObject(youtubeInfo)
121 log.debug('Fetched object.', videoInfo)
123 if (program['since']) {
124 if (buildOriginallyPublishedAt(videoInfo).getTime() < program['since'].getTime()) {
125 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
126 videoInfo.title, formatDate(program['since']))
130 if (program['until']) {
131 if (buildOriginallyPublishedAt(videoInfo).getTime() > program['until'].getTime()) {
132 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
133 videoInfo.title, formatDate(program['until']))
138 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
140 log.info('############################################################\n')
142 if (result.body.data.find(v => v.name === videoInfo.title)) {
143 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
147 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
149 log.info('Downloading video "%s"...', videoInfo.title)
151 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', ...command.args, '-o', path ]
153 const youtubeDL = await safeGetYoutubeDL()
154 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
160 log.info(output.join('\n'))
161 await uploadVideoOnPeerTube({
165 videoInfo: normalizeObject(videoInfo),
171 log.error(err.message)
177 async function uploadVideoOnPeerTube (parameters: {
182 user: { username: string, password: string }
184 const { videoInfo, videoPath, cwd, url, user } = parameters
186 const category = await getCategory(videoInfo.categories, url)
187 const licence = getLicence(videoInfo.license)
189 if (Array.isArray(videoInfo.tags)) {
190 tags = videoInfo.tags
191 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
192 .map(t => t.normalize())
197 if (videoInfo.thumbnail) {
198 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
200 await doRequestAndSaveToFile({
202 uri: videoInfo.thumbnail
206 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
208 const defaultAttributes = {
209 name: truncate(videoInfo.title, {
210 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
216 nsfw: isNSFW(videoInfo),
217 description: videoInfo.description,
221 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
223 Object.assign(videoAttributes, {
224 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
226 previewfile: thumbnailfile,
230 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
232 let accessToken = await getAccessTokenOrDie(url, user)
235 await uploadVideo(url, accessToken, videoAttributes)
237 if (err.message.indexOf('401') !== -1) {
238 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
240 accessToken = await getAccessTokenOrDie(url, user)
242 await uploadVideo(url, accessToken, videoAttributes)
244 exitError(err.message)
248 await remove(videoPath)
249 if (thumbnailfile) await remove(thumbnailfile)
251 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
254 /* ---------------------------------------------------------- */
256 async function getCategory (categories: string[], url: string) {
257 if (!categories) return undefined
259 const categoryString = categories[0]
261 if (categoryString === 'News & Politics') return 11
263 const res = await getVideoCategories(url)
264 const categoriesServer = res.body
266 for (const key of Object.keys(categoriesServer)) {
267 const categoryServer = categoriesServer[key]
268 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
274 function getLicence (licence: string) {
275 if (!licence) return undefined
277 if (licence.includes('Creative Commons Attribution licence')) return 1
282 function normalizeObject (obj: any) {
283 const newObj: any = {}
285 for (const key of Object.keys(obj)) {
287 if (key === 'resolution') continue
289 const value = obj[key]
291 if (typeof value === 'string') {
292 newObj[key] = value.normalize()
301 function fetchObject (info: any) {
302 const url = buildUrl(info)
304 return new Promise<any>(async (res, rej) => {
305 const youtubeDL = await safeGetYoutubeDL()
306 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
307 if (err) return rej(err)
309 const videoInfoWithUrl = Object.assign(videoInfo, { url })
310 return res(normalizeObject(videoInfoWithUrl))
315 function buildUrl (info: any) {
316 const webpageUrl = info.webpage_url as string
317 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
319 const url = info.url as string
320 if (url?.match(/^https?:\/\//)) return url
322 // It seems youtube-dl does not return the video url
323 return 'https://www.youtube.com/watch?v=' + info.id
326 function isNSFW (info: any) {
327 return info.age_limit && info.age_limit >= 16
330 function normalizeTargetUrl (url: string) {
331 let normalizedUrl = url.replace(/\/+$/, '')
333 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
334 normalizedUrl = 'https://' + normalizedUrl
340 async function promptPassword () {
341 return new Promise<string>((res, rej) => {
351 prompt.get(schema, function (err, result) {
355 return res(result.password)
360 async function getAccessTokenOrDie (url: string, user: UserInfo) {
361 const resClient = await getClient(url)
363 id: resClient.body.client_id,
364 secret: resClient.body.client_secret
368 const res = await login(url, client, user)
369 return res.body.access_token
371 exitError('Cannot authenticate. Please check your username/password.')
375 function parseDate (dateAsStr: string): Date {
376 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
377 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
379 const date = new Date(dateAsStr)
380 date.setHours(0, 0, 0)
381 if (isNaN(date.getTime())) {
382 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
387 function formatDate (date: Date): string {
388 return date.toISOString().split('T')[0]
391 function exitError (message: string, ...meta: any[]) {
392 // use console.error instead of log.error here
393 console.error(message, ...meta)