1 import { registerTSPaths } from '../helpers/register-ts-paths'
4 import { accessSync, constants } from 'fs'
5 import { join } from 'path'
6 import { promisify } from 'util'
8 import * as program from 'commander'
9 import { remove } from 'fs-extra'
10 import { truncate } from 'lodash'
11 import * as prompt from 'prompt'
13 import { doRequestAndSaveToFile } from '../helpers/requests'
14 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
15 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
16 import { sha256 } from '../helpers/core-utils'
17 import { buildOriginallyPublishedAt, getYoutubeDLVideoFormat, safeGetYoutubeDL } from '../helpers/youtube-dl'
18 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli'
25 const processOptions = {
30 .name('import-videos')
32 command = buildCommonVideoOptions(command)
35 .option('-u, --url <url>', 'Server url')
36 .option('-U, --username <username>', 'Username')
37 .option('-p, --password <token>', 'Password')
38 .option('--target-url <targetUrl>', 'Video target URL')
39 .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate)
40 .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate)
41 .option('--first <first>', 'Process first n elements of returned playlist')
42 .option('--last <last>', 'Process last n elements of returned playlist')
43 .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs)
44 .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
45 .usage("[global options] [ -- youtube-dl options]")
48 const options = command.opts()
50 const log = getLogger(options.verbose)
52 getServerCredentials(command)
53 .then(({ url, username, password }) => {
54 if (!options.targetUrl) {
55 exitError('--target-url field is required.')
59 accessSync(options.tmpdir, constants.R_OK | constants.W_OK)
61 exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir)
64 url = normalizeTargetUrl(url)
65 options.targetUrl = normalizeTargetUrl(options.targetUrl)
67 const user = { username, password }
70 .catch(err => exitError(err))
72 .catch(err => console.error(err))
74 async function run (url: string, user: UserInfo) {
76 user.password = await promptPassword()
79 const youtubeDL = await safeGetYoutubeDL()
81 let info = await getYoutubeDLInfo(youtubeDL, options.targetUrl, command.args)
83 if (!Array.isArray(info)) info = [ info ]
85 // Try to fix youtube channels upload
86 const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads')
89 console.log('Fixing URL to %s.', uploadsObject.url)
91 info = await getYoutubeDLInfo(youtubeDL, uploadsObject.url, command.args)
96 infoArray = [].concat(info)
98 infoArray = infoArray.slice(0, options.first)
99 } else if (options.last) {
100 infoArray = infoArray.slice(-options.last)
102 // Normalize utf8 fields
103 infoArray = infoArray.map(i => normalizeObject(i))
105 log.info('Will download and upload %d videos.\n', infoArray.length)
107 for (const [ index, info ] of infoArray.entries()) {
109 if (index > 0 && options.waitInterval) {
110 log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000)
111 await new Promise(res => setTimeout(res, options.waitInterval))
120 console.error('Cannot process video.', { info, url, err })
124 log.info('Video/s for user %s imported: %s', user.username, options.targetUrl)
128 async function processVideo (parameters: {
131 user: { username: string, password: string }
134 const { youtubeInfo, cwd, url, user } = parameters
136 log.debug('Fetching object.', youtubeInfo)
138 const videoInfo = await fetchObject(youtubeInfo)
139 log.debug('Fetched object.', videoInfo)
141 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
142 if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) {
143 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
144 videoInfo.title, formatDate(options.since))
147 if (options.until && originallyPublishedAt && originallyPublishedAt.getTime() > options.until.getTime()) {
148 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
149 videoInfo.title, formatDate(options.until))
153 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
155 log.info('############################################################\n')
157 if (result.body.data.find(v => v.name === videoInfo.title)) {
158 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
162 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
164 log.info('Downloading video "%s"...', videoInfo.title)
166 const youtubeDLOptions = [ '-f', getYoutubeDLVideoFormat(), ...command.args, '-o', path ]
168 const youtubeDL = await safeGetYoutubeDL()
169 const youtubeDLExec = promisify(youtubeDL.exec).bind(youtubeDL)
170 const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions)
171 log.info(output.join('\n'))
172 await uploadVideoOnPeerTube({
176 videoInfo: normalizeObject(videoInfo),
180 log.error(err.message)
184 async function uploadVideoOnPeerTube (parameters: {
189 user: { username: string, password: string }
191 const { videoInfo, videoPath, cwd, url, user } = parameters
193 const category = await getCategory(videoInfo.categories, url)
194 const licence = getLicence(videoInfo.license)
196 if (Array.isArray(videoInfo.tags)) {
197 tags = videoInfo.tags
198 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
199 .map(t => t.normalize())
204 if (videoInfo.thumbnail) {
205 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
207 await doRequestAndSaveToFile({
209 uri: videoInfo.thumbnail
213 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
215 const defaultAttributes = {
216 name: truncate(videoInfo.title, {
217 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
223 nsfw: isNSFW(videoInfo),
224 description: videoInfo.description,
228 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
230 Object.assign(videoAttributes, {
231 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
233 previewfile: thumbnailfile,
237 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
239 let accessToken = await getAccessTokenOrDie(url, user)
242 await uploadVideo(url, accessToken, videoAttributes)
244 if (err.message.indexOf('401') !== -1) {
245 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
247 accessToken = await getAccessTokenOrDie(url, user)
249 await uploadVideo(url, accessToken, videoAttributes)
251 exitError(err.message)
255 await remove(videoPath)
256 if (thumbnailfile) await remove(thumbnailfile)
258 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
261 /* ---------------------------------------------------------- */
263 async function getCategory (categories: string[], url: string) {
264 if (!categories) return undefined
266 const categoryString = categories[0]
268 if (categoryString === 'News & Politics') return 11
270 const res = await getVideoCategories(url)
271 const categoriesServer = res.body
273 for (const key of Object.keys(categoriesServer)) {
274 const categoryServer = categoriesServer[key]
275 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
281 function getLicence (licence: string) {
282 if (!licence) return undefined
284 if (licence.includes('Creative Commons Attribution licence')) return 1
289 function normalizeObject (obj: any) {
290 const newObj: any = {}
292 for (const key of Object.keys(obj)) {
294 if (key === 'resolution') continue
296 const value = obj[key]
298 if (typeof value === 'string') {
299 newObj[key] = value.normalize()
308 function fetchObject (info: any) {
309 const url = buildUrl(info)
311 return new Promise<any>(async (res, rej) => {
312 const youtubeDL = await safeGetYoutubeDL()
313 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
314 if (err) return rej(err)
316 const videoInfoWithUrl = Object.assign(videoInfo, { url })
317 return res(normalizeObject(videoInfoWithUrl))
322 function buildUrl (info: any) {
323 const webpageUrl = info.webpage_url as string
324 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
326 const url = info.url as string
327 if (url?.match(/^https?:\/\//)) return url
329 // It seems youtube-dl does not return the video url
330 return 'https://www.youtube.com/watch?v=' + info.id
333 function isNSFW (info: any) {
334 return info.age_limit && info.age_limit >= 16
337 function normalizeTargetUrl (url: string) {
338 let normalizedUrl = url.replace(/\/+$/, '')
340 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
341 normalizedUrl = 'https://' + normalizedUrl
347 async function promptPassword () {
348 return new Promise<string>((res, rej) => {
358 prompt.get(schema, function (err, result) {
362 return res(result.password)
367 async function getAccessTokenOrDie (url: string, user: UserInfo) {
368 const resClient = await getClient(url)
370 id: resClient.body.client_id,
371 secret: resClient.body.client_secret
375 const res = await login(url, client, user)
376 return res.body.access_token
378 exitError('Cannot authenticate. Please check your username/password.')
382 function parseDate (dateAsStr: string): Date {
383 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
384 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
386 const date = new Date(dateAsStr)
387 date.setHours(0, 0, 0)
388 if (isNaN(date.getTime())) {
389 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
394 function formatDate (date: Date): string {
395 return date.toISOString().split('T')[0]
398 function convertIntoMs (secondsAsStr: string): number {
399 const seconds = parseInt(secondsAsStr, 10)
401 exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
403 return Math.round(seconds * 1000)
406 function exitError (message: string, ...meta: any[]) {
407 // use console.error instead of log.error here
408 console.error(message, ...meta)
412 function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) {
413 return new Promise<any>((res, rej) => {
414 const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ]
416 youtubeDL.getInfo(url, options, processOptions, async (err, info) => {
417 if (err) return rej(err)