1 import { program } from 'commander'
2 import { accessSync, constants } from 'fs'
3 import { remove } from 'fs-extra'
4 import { join } from 'path'
5 import { YoutubeDLCLI, YoutubeDLInfo, YoutubeDLInfoBuilder } from '@server/helpers/youtube-dl'
6 import { wait } from '@shared/core-utils'
7 import { sha256 } from '@shared/extra-utils'
8 import { doRequestAndSaveToFile } from '../helpers/requests'
11 buildCommonVideoOptions,
13 buildVideoAttributesFromCommander,
18 import prompt = require('prompt')
20 const processOptions = {
25 .name('import-videos')
27 command = buildCommonVideoOptions(command)
30 .option('-u, --url <url>', 'Server url')
31 .option('-U, --username <username>', 'Username')
32 .option('-p, --password <token>', 'Password')
33 .option('--target-url <targetUrl>', 'Video target URL')
34 .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate)
35 .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate)
36 .option('--first <first>', 'Process first n elements of returned playlist')
37 .option('--last <last>', 'Process last n elements of returned playlist')
38 .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs)
39 .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
40 .usage("[global options] [ -- youtube-dl options]")
43 const options = command.opts()
45 const log = getLogger(options.verbose)
47 getServerCredentials(command)
48 .then(({ url, username, password }) => {
49 if (!options.targetUrl) {
50 exitError('--target-url field is required.')
54 accessSync(options.tmpdir, constants.R_OK | constants.W_OK)
56 exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir)
59 url = normalizeTargetUrl(url)
60 options.targetUrl = normalizeTargetUrl(options.targetUrl)
62 run(url, username, password)
63 .catch(err => exitError(err))
65 .catch(err => console.error(err))
67 async function run (url: string, username: string, password: string) {
68 if (!password) password = await promptPassword()
70 const youtubeDLBinary = await YoutubeDLCLI.safeGet()
72 let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args)
74 if (!Array.isArray(info)) info = [ info ]
76 // Try to fix youtube channels upload
77 const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads')
80 console.log('Fixing URL to %s.', uploadsObject.url)
82 info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args)
87 infoArray = [].concat(info)
89 infoArray = infoArray.slice(0, options.first)
90 } else if (options.last) {
91 infoArray = infoArray.slice(-options.last)
94 log.info('Will download and upload %d videos.\n', infoArray.length)
96 let skipInterval = true
97 for (const [ index, info ] of infoArray.entries()) {
99 if (index > 0 && options.waitInterval && !skipInterval) {
100 log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000)
101 await wait(options.waitInterval)
104 skipInterval = await processVideo({
112 console.error('Cannot process video.', { info, url, err })
116 log.info('Video/s for user %s imported: %s', username, options.targetUrl)
120 async function processVideo (parameters: {
127 const { youtubeInfo, cwd, url, username, password } = parameters
129 log.debug('Fetching object.', youtubeInfo)
131 const videoInfo = await fetchObject(youtubeInfo)
132 log.debug('Fetched object.', videoInfo)
134 if (options.since && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() < options.since.getTime()) {
135 log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.since))
139 if (options.until && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() > options.until.getTime()) {
140 log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.until))
144 const server = buildServer(url)
145 const { data } = await server.search.advancedVideoSearch({
147 search: videoInfo.name,
149 searchTarget: 'local'
153 log.info('############################################################\n')
155 if (data.find(v => v.name === videoInfo.name)) {
156 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.name)
160 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
162 log.info('Downloading video "%s"...', videoInfo.name)
165 const youtubeDLBinary = await YoutubeDLCLI.safeGet()
166 const output = await youtubeDLBinary.download({
168 format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
170 additionalYoutubeDLArgs: command.args,
174 log.info(output.join('\n'))
175 await uploadVideoOnPeerTube({
184 log.error(err.message)
190 async function uploadVideoOnPeerTube (parameters: {
191 videoInfo: YoutubeDLInfo
198 const { videoInfo, videoPath, cwd, url, username, password } = parameters
200 const server = buildServer(url)
201 await assignToken(server, username, password)
203 let thumbnailfile: string
204 if (videoInfo.thumbnailUrl) {
205 thumbnailfile = join(cwd, sha256(videoInfo.thumbnailUrl) + '.jpg')
207 await doRequestAndSaveToFile(videoInfo.thumbnailUrl, thumbnailfile)
210 const baseAttributes = await buildVideoAttributesFromCommander(server, program, videoInfo)
215 originallyPublishedAt: videoInfo.originallyPublishedAt
216 ? videoInfo.originallyPublishedAt.toISOString()
220 previewfile: thumbnailfile,
224 log.info('\nUploading on PeerTube video "%s".', attributes.name)
227 await server.videos.upload({ attributes })
229 if (err.message.indexOf('401') !== -1) {
230 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
232 server.accessToken = await server.login.getAccessToken(username, password)
234 await server.videos.upload({ attributes })
236 exitError(err.message)
240 await remove(videoPath)
241 if (thumbnailfile) await remove(thumbnailfile)
243 log.info('Uploaded video "%s"!\n', attributes.name)
246 /* ---------------------------------------------------------- */
248 async function fetchObject (info: any) {
249 const url = buildUrl(info)
251 const youtubeDLCLI = await YoutubeDLCLI.safeGet()
252 const result = await youtubeDLCLI.getInfo({
254 format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
258 const builder = new YoutubeDLInfoBuilder(result)
260 const videoInfo = builder.getInfo()
262 return { ...videoInfo, url }
265 function buildUrl (info: any) {
266 const webpageUrl = info.webpage_url as string
267 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
269 const url = info.url as string
270 if (url?.match(/^https?:\/\//)) return url
272 // It seems youtube-dl does not return the video url
273 return 'https://www.youtube.com/watch?v=' + info.id
276 function normalizeTargetUrl (url: string) {
277 let normalizedUrl = url.replace(/\/+$/, '')
279 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
280 normalizedUrl = 'https://' + normalizedUrl
286 async function promptPassword () {
287 return new Promise<string>((res, rej) => {
297 prompt.get(schema, function (err, result) {
301 return res(result.password)
306 function parseDate (dateAsStr: string): Date {
307 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
308 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
310 const date = new Date(dateAsStr)
311 date.setHours(0, 0, 0)
312 if (isNaN(date.getTime())) {
313 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
318 function formatDate (date: Date): string {
319 return date.toISOString().split('T')[0]
322 function convertIntoMs (secondsAsStr: string): number {
323 const seconds = parseInt(secondsAsStr, 10)
325 exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
327 return Math.round(seconds * 1000)
330 function exitError (message: string, ...meta: any[]) {
331 // use console.error instead of log.error here
332 console.error(message, ...meta)
336 function getYoutubeDLInfo (youtubeDLCLI: YoutubeDLCLI, url: string, args: string[]) {
337 return youtubeDLCLI.getInfo({
339 format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
340 additionalYoutubeDLArgs: [ '-j', '--flat-playlist', '--playlist-reverse', ...args ],