1 import { registerTSPaths } from '../helpers/register-ts-paths'
4 import { program } from 'commander'
5 import { accessSync, constants } from 'fs'
6 import { remove } from 'fs-extra'
7 import { truncate } from 'lodash'
8 import { join } from 'path'
9 import * as prompt from 'prompt'
10 import { promisify } from 'util'
11 import { YoutubeDL } from '@server/helpers/youtube-dl'
12 import { getVideoCategories, uploadVideo } from '../../shared/extra-utils/index'
13 import { sha256 } from '../helpers/core-utils'
14 import { doRequestAndSaveToFile } from '../helpers/requests'
15 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
17 buildCommonVideoOptions,
19 buildVideoAttributesFromCommander,
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 run(url, username, password)
68 .catch(err => exitError(err))
70 .catch(err => console.error(err))
72 async function run (url: string, username: string, password: string) {
73 if (!password) password = await promptPassword()
75 const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL()
77 let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args)
79 if (!Array.isArray(info)) info = [ info ]
81 // Try to fix youtube channels upload
82 const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads')
85 console.log('Fixing URL to %s.', uploadsObject.url)
87 info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args)
92 infoArray = [].concat(info)
94 infoArray = infoArray.slice(0, options.first)
95 } else if (options.last) {
96 infoArray = infoArray.slice(-options.last)
98 // Normalize utf8 fields
99 infoArray = infoArray.map(i => normalizeObject(i))
101 log.info('Will download and upload %d videos.\n', infoArray.length)
103 for (const [ index, info ] of infoArray.entries()) {
105 if (index > 0 && options.waitInterval) {
106 log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000)
107 await new Promise(res => setTimeout(res, options.waitInterval))
117 console.error('Cannot process video.', { info, url, err })
121 log.info('Video/s for user %s imported: %s', username, options.targetUrl)
125 async function processVideo (parameters: {
132 const { youtubeInfo, cwd, url, username, password } = parameters
133 const youtubeDL = new YoutubeDL('', [])
135 log.debug('Fetching object.', youtubeInfo)
137 const videoInfo = await fetchObject(youtubeInfo)
138 log.debug('Fetched object.', videoInfo)
140 const originallyPublishedAt = youtubeDL.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', 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', videoInfo.title, formatDate(options.until))
152 const server = buildServer(url)
153 const { data } = await server.searchCommand.advancedVideoSearch({
155 search: videoInfo.title,
157 searchTarget: 'local'
161 log.info('############################################################\n')
163 if (data.find(v => v.name === videoInfo.title)) {
164 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
168 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
170 log.info('Downloading video "%s"...', videoInfo.title)
172 const youtubeDLOptions = [ '-f', youtubeDL.getYoutubeDLVideoFormat(), ...command.args, '-o', path ]
174 const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL()
175 const youtubeDLExec = promisify(youtubeDLBinary.exec).bind(youtubeDLBinary)
176 const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions)
177 log.info(output.join('\n'))
178 await uploadVideoOnPeerTube({
184 videoInfo: normalizeObject(videoInfo),
188 log.error(err.message)
192 async function uploadVideoOnPeerTube (parameters: {
201 const { youtubeDL, videoInfo, videoPath, cwd, url, username, password } = parameters
203 const category = await getCategory(videoInfo.categories, url)
204 const licence = getLicence(videoInfo.license)
206 if (Array.isArray(videoInfo.tags)) {
207 tags = videoInfo.tags
208 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
209 .map(t => t.normalize())
214 if (videoInfo.thumbnail) {
215 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
217 await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile)
220 const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo)
222 const defaultAttributes = {
223 name: truncate(videoInfo.title, {
224 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
230 nsfw: isNSFW(videoInfo),
231 description: videoInfo.description,
235 let accessToken = await getAccessTokenOrDie(url, username, password)
236 const server = buildServer(url, accessToken)
238 const videoAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes)
240 Object.assign(videoAttributes, {
241 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
243 previewfile: thumbnailfile,
247 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
250 await uploadVideo(url, accessToken, videoAttributes)
252 if (err.message.indexOf('401') !== -1) {
253 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
255 accessToken = await getAccessTokenOrDie(url, username, password)
257 await uploadVideo(url, accessToken, videoAttributes)
259 exitError(err.message)
263 await remove(videoPath)
264 if (thumbnailfile) await remove(thumbnailfile)
266 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
269 /* ---------------------------------------------------------- */
271 async function getCategory (categories: string[], url: string) {
272 if (!categories) return undefined
274 const categoryString = categories[0]
276 if (categoryString === 'News & Politics') return 11
278 const res = await getVideoCategories(url)
279 const categoriesServer = res.body
281 for (const key of Object.keys(categoriesServer)) {
282 const categoryServer = categoriesServer[key]
283 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
289 function getLicence (licence: string) {
290 if (!licence) return undefined
292 if (licence.includes('Creative Commons Attribution licence')) return 1
297 function normalizeObject (obj: any) {
298 const newObj: any = {}
300 for (const key of Object.keys(obj)) {
302 if (key === 'resolution') continue
304 const value = obj[key]
306 if (typeof value === 'string') {
307 newObj[key] = value.normalize()
316 function fetchObject (info: any) {
317 const url = buildUrl(info)
319 return new Promise<any>(async (res, rej) => {
320 const youtubeDL = await YoutubeDL.safeGetYoutubeDL()
321 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
322 if (err) return rej(err)
324 const videoInfoWithUrl = Object.assign(videoInfo, { url })
325 return res(normalizeObject(videoInfoWithUrl))
330 function buildUrl (info: any) {
331 const webpageUrl = info.webpage_url as string
332 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
334 const url = info.url as string
335 if (url?.match(/^https?:\/\//)) return url
337 // It seems youtube-dl does not return the video url
338 return 'https://www.youtube.com/watch?v=' + info.id
341 function isNSFW (info: any) {
342 return info.age_limit && info.age_limit >= 16
345 function normalizeTargetUrl (url: string) {
346 let normalizedUrl = url.replace(/\/+$/, '')
348 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
349 normalizedUrl = 'https://' + normalizedUrl
355 async function promptPassword () {
356 return new Promise<string>((res, rej) => {
366 prompt.get(schema, function (err, result) {
370 return res(result.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 convertIntoMs (secondsAsStr: string): number {
392 const seconds = parseInt(secondsAsStr, 10)
394 exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
396 return Math.round(seconds * 1000)
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)