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 let info = await getYoutubeDLInfo(youtubeDL, program['targetUrl'], command.args)
77 if (info?.title === 'Uploads') {
78 console.log('Fixing URL to %s.', info.url)
80 info = await getYoutubeDLInfo(youtubeDL, info.url, command.args)
85 // Normalize utf8 fields
86 infoArray = [].concat(info)
87 if (program['first']) {
88 infoArray = infoArray.slice(0, program['first'])
89 } else if (program['last']) {
90 infoArray = infoArray.slice(-program['last'])
92 infoArray = infoArray.map(i => normalizeObject(i))
94 log.info('Will download and upload %d videos.\n', infoArray.length)
96 for (const info of infoArray) {
99 cwd: program['tmpdir'],
105 console.error('Cannot process video.', { info, url })
109 log.info('Video/s for user %s imported: %s', user.username, program['targetUrl'])
113 function processVideo (parameters: {
116 user: { username: string, password: string }
119 const { youtubeInfo, cwd, url, user } = parameters
121 return new Promise(async res => {
122 log.debug('Fetching object.', youtubeInfo)
124 const videoInfo = await fetchObject(youtubeInfo)
125 log.debug('Fetched object.', videoInfo)
127 if (program['since']) {
128 if (buildOriginallyPublishedAt(videoInfo).getTime() < program['since'].getTime()) {
129 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
130 videoInfo.title, formatDate(program['since']))
134 if (program['until']) {
135 if (buildOriginallyPublishedAt(videoInfo).getTime() > program['until'].getTime()) {
136 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
137 videoInfo.title, formatDate(program['until']))
142 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
144 log.info('############################################################\n')
146 if (result.body.data.find(v => v.name === videoInfo.title)) {
147 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
151 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
153 log.info('Downloading video "%s"...', videoInfo.title)
155 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', ...command.args, '-o', path ]
157 const youtubeDL = await safeGetYoutubeDL()
158 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
164 log.info(output.join('\n'))
165 await uploadVideoOnPeerTube({
169 videoInfo: normalizeObject(videoInfo),
175 log.error(err.message)
181 async function uploadVideoOnPeerTube (parameters: {
186 user: { username: string, password: string }
188 const { videoInfo, videoPath, cwd, url, user } = parameters
190 const category = await getCategory(videoInfo.categories, url)
191 const licence = getLicence(videoInfo.license)
193 if (Array.isArray(videoInfo.tags)) {
194 tags = videoInfo.tags
195 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
196 .map(t => t.normalize())
201 if (videoInfo.thumbnail) {
202 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
204 await doRequestAndSaveToFile({
206 uri: videoInfo.thumbnail
210 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
212 const defaultAttributes = {
213 name: truncate(videoInfo.title, {
214 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
220 nsfw: isNSFW(videoInfo),
221 description: videoInfo.description,
225 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
227 Object.assign(videoAttributes, {
228 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
230 previewfile: thumbnailfile,
234 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
236 let accessToken = await getAccessTokenOrDie(url, user)
239 await uploadVideo(url, accessToken, videoAttributes)
241 if (err.message.indexOf('401') !== -1) {
242 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
244 accessToken = await getAccessTokenOrDie(url, user)
246 await uploadVideo(url, accessToken, videoAttributes)
248 exitError(err.message)
252 await remove(videoPath)
253 if (thumbnailfile) await remove(thumbnailfile)
255 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
258 /* ---------------------------------------------------------- */
260 async function getCategory (categories: string[], url: string) {
261 if (!categories) return undefined
263 const categoryString = categories[0]
265 if (categoryString === 'News & Politics') return 11
267 const res = await getVideoCategories(url)
268 const categoriesServer = res.body
270 for (const key of Object.keys(categoriesServer)) {
271 const categoryServer = categoriesServer[key]
272 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
278 function getLicence (licence: string) {
279 if (!licence) return undefined
281 if (licence.includes('Creative Commons Attribution licence')) return 1
286 function normalizeObject (obj: any) {
287 const newObj: any = {}
289 for (const key of Object.keys(obj)) {
291 if (key === 'resolution') continue
293 const value = obj[key]
295 if (typeof value === 'string') {
296 newObj[key] = value.normalize()
305 function fetchObject (info: any) {
306 const url = buildUrl(info)
308 return new Promise<any>(async (res, rej) => {
309 const youtubeDL = await safeGetYoutubeDL()
310 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
311 if (err) return rej(err)
313 const videoInfoWithUrl = Object.assign(videoInfo, { url })
314 return res(normalizeObject(videoInfoWithUrl))
319 function buildUrl (info: any) {
320 const webpageUrl = info.webpage_url as string
321 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
323 const url = info.url as string
324 if (url?.match(/^https?:\/\//)) return url
326 // It seems youtube-dl does not return the video url
327 return 'https://www.youtube.com/watch?v=' + info.id
330 function isNSFW (info: any) {
331 return info.age_limit && info.age_limit >= 16
334 function normalizeTargetUrl (url: string) {
335 let normalizedUrl = url.replace(/\/+$/, '')
337 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
338 normalizedUrl = 'https://' + normalizedUrl
344 async function promptPassword () {
345 return new Promise<string>((res, rej) => {
355 prompt.get(schema, function (err, result) {
359 return res(result.password)
364 async function getAccessTokenOrDie (url: string, user: UserInfo) {
365 const resClient = await getClient(url)
367 id: resClient.body.client_id,
368 secret: resClient.body.client_secret
372 const res = await login(url, client, user)
373 return res.body.access_token
375 exitError('Cannot authenticate. Please check your username/password.')
379 function parseDate (dateAsStr: string): Date {
380 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
381 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
383 const date = new Date(dateAsStr)
384 date.setHours(0, 0, 0)
385 if (isNaN(date.getTime())) {
386 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
391 function formatDate (date: Date): string {
392 return date.toISOString().split('T')[0]
395 function exitError (message: string, ...meta: any[]) {
396 // use console.error instead of log.error here
397 console.error(message, ...meta)
401 function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) {
402 return new Promise<any>((res, rej) => {
403 const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ]
405 youtubeDL.getInfo(url, options, processOptions, async (err, info) => {
406 if (err) return rej(err)