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 { sha256 } from '../helpers/core-utils'
13 import { doRequestAndSaveToFile } from '../helpers/requests'
14 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
17 buildCommonVideoOptions,
19 buildVideoAttributesFromCommander,
23 import { PeerTubeServer } from '@shared/extra-utils'
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.search.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 server = buildServer(url)
204 await assignToken(server, username, password)
206 const category = await getCategory(server, videoInfo.categories)
207 const licence = getLicence(videoInfo.license)
209 if (Array.isArray(videoInfo.tags)) {
210 tags = videoInfo.tags
211 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
212 .map(t => t.normalize())
217 if (videoInfo.thumbnail) {
218 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
220 await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile)
223 const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo)
225 const defaultAttributes = {
226 name: truncate(videoInfo.title, {
227 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
233 nsfw: isNSFW(videoInfo),
234 description: videoInfo.description,
238 const baseAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes)
243 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
245 previewfile: thumbnailfile,
249 log.info('\nUploading on PeerTube video "%s".', attributes.name)
252 await server.videos.upload({ attributes })
254 if (err.message.indexOf('401') !== -1) {
255 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
257 server.accessToken = await server.login.getAccessToken(username, password)
259 await server.videos.upload({ attributes })
261 exitError(err.message)
265 await remove(videoPath)
266 if (thumbnailfile) await remove(thumbnailfile)
268 log.warn('Uploaded video "%s"!\n', attributes.name)
271 /* ---------------------------------------------------------- */
273 async function getCategory (server: PeerTubeServer, categories: string[]) {
274 if (!categories) return undefined
276 const categoryString = categories[0]
278 if (categoryString === 'News & Politics') return 11
280 const categoriesServer = await server.videos.getCategories()
282 for (const key of Object.keys(categoriesServer)) {
283 const categoryServer = categoriesServer[key]
284 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
290 function getLicence (licence: string) {
291 if (!licence) return undefined
293 if (licence.includes('Creative Commons Attribution licence')) return 1
298 function normalizeObject (obj: any) {
299 const newObj: any = {}
301 for (const key of Object.keys(obj)) {
303 if (key === 'resolution') continue
305 const value = obj[key]
307 if (typeof value === 'string') {
308 newObj[key] = value.normalize()
317 function fetchObject (info: any) {
318 const url = buildUrl(info)
320 return new Promise<any>(async (res, rej) => {
321 const youtubeDL = await YoutubeDL.safeGetYoutubeDL()
322 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
323 if (err) return rej(err)
325 const videoInfoWithUrl = Object.assign(videoInfo, { url })
326 return res(normalizeObject(videoInfoWithUrl))
331 function buildUrl (info: any) {
332 const webpageUrl = info.webpage_url as string
333 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
335 const url = info.url as string
336 if (url?.match(/^https?:\/\//)) return url
338 // It seems youtube-dl does not return the video url
339 return 'https://www.youtube.com/watch?v=' + info.id
342 function isNSFW (info: any) {
343 return info.age_limit && info.age_limit >= 16
346 function normalizeTargetUrl (url: string) {
347 let normalizedUrl = url.replace(/\/+$/, '')
349 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
350 normalizedUrl = 'https://' + normalizedUrl
356 async function promptPassword () {
357 return new Promise<string>((res, rej) => {
367 prompt.get(schema, function (err, result) {
371 return res(result.password)
376 function parseDate (dateAsStr: string): Date {
377 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
378 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
380 const date = new Date(dateAsStr)
381 date.setHours(0, 0, 0)
382 if (isNaN(date.getTime())) {
383 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
388 function formatDate (date: Date): string {
389 return date.toISOString().split('T')[0]
392 function convertIntoMs (secondsAsStr: string): number {
393 const seconds = parseInt(secondsAsStr, 10)
395 exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
397 return Math.round(seconds * 1000)
400 function exitError (message: string, ...meta: any[]) {
401 // use console.error instead of log.error here
402 console.error(message, ...meta)
406 function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) {
407 return new Promise<any>((res, rej) => {
408 const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ]
410 youtubeDL.getInfo(url, options, processOptions, (err, info) => {
411 if (err) return rej(err)