]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/tools/peertube-import-videos.ts
Upgrade server dependencies
[github/Chocobozzz/PeerTube.git] / server / tools / peertube-import-videos.ts
CommitLineData
2aaa1a3f
C
1import { registerTSPaths } from '../helpers/register-ts-paths'
2registerTSPaths()
3
82f5527f 4import * as program from 'commander'
d7764e2e 5import { accessSync, constants } from 'fs'
82f5527f
F
6import { remove } from 'fs-extra'
7import { truncate } from 'lodash'
d7764e2e 8import { join } from 'path'
82f5527f 9import * as prompt from 'prompt'
d7764e2e
C
10import { promisify } from 'util'
11import { advancedVideosSearch, getClient, getVideoCategories, login, uploadVideo } from '../../shared/extra-utils/index'
fa27f076 12import { sha256 } from '../helpers/core-utils'
d7764e2e 13import { doRequestAndSaveToFile } from '../helpers/requests'
d7764e2e 14import { CONSTRAINTS_FIELDS } from '../initializers/constants'
a1587156 15import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli'
1bcb03a1 16import { YoutubeDL } from '@server/helpers/youtube-dl'
8704acf4 17
1a12f66d
C
18type UserInfo = {
19 username: string
20 password: string
21}
8704acf4
RK
22
23const processOptions = {
8704acf4
RK
24 maxBuffer: Infinity
25}
a7fea183 26
1205823f 27let command = program
8704acf4 28 .name('import-videos')
1205823f
C
29
30command = buildCommonVideoOptions(command)
31
32command
a7fea183
C
33 .option('-u, --url <url>', 'Server url')
34 .option('-U, --username <username>', 'Username')
35 .option('-p, --password <token>', 'Password')
d0198ff9
F
36 .option('--target-url <targetUrl>', 'Video target URL')
37 .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate)
38 .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate)
bda3b705
FL
39 .option('--first <first>', 'Process first n elements of returned playlist')
40 .option('--last <last>', 'Process last n elements of returned playlist')
82f5527f 41 .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs)
bda3b705 42 .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
79ee77ea 43 .usage("[global options] [ -- youtube-dl options]")
a7fea183
C
44 .parse(process.argv)
45
ba5a8d89
C
46const options = command.opts()
47
48const log = getLogger(options.verbose)
bda3b705 49
8d2be0ed
C
50getServerCredentials(command)
51 .then(({ url, username, password }) => {
ba5a8d89 52 if (!options.targetUrl) {
bda3b705
FL
53 exitError('--target-url field is required.')
54 }
e8a739e8 55
bda3b705 56 try {
ba5a8d89 57 accessSync(options.tmpdir, constants.R_OK | constants.W_OK)
bda3b705 58 } catch (e) {
ba5a8d89 59 exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir)
8d2be0ed 60 }
066fc8ba 61
da69b886 62 url = normalizeTargetUrl(url)
ba5a8d89 63 options.targetUrl = normalizeTargetUrl(options.targetUrl)
ab4dbe36 64
8d2be0ed 65 const user = { username, password }
8a2db2e8 66
8d2be0ed 67 run(url, user)
a1587156 68 .catch(err => exitError(err))
8d2be0ed 69 })
a1587156 70 .catch(err => console.error(err))
a7fea183 71
1a12f66d 72async function run (url: string, user: UserInfo) {
e2b9d0ca
JL
73 if (!user.password) {
74 user.password = await promptPassword()
066fc8ba 75 }
8a2db2e8 76
1bcb03a1 77 const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL()
8704acf4 78
1bcb03a1 79 let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args)
79ee77ea 80
5721fd83 81 if (!Array.isArray(info)) info = [ info ]
a7fea183 82
5721fd83
C
83 // Try to fix youtube channels upload
84 const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads')
85
86 if (uploadsObject) {
87 console.log('Fixing URL to %s.', uploadsObject.url)
88
1bcb03a1 89 info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args)
de29e90c 90 }
a7fea183 91
de29e90c 92 let infoArray: any[]
bda3b705 93
de29e90c 94 infoArray = [].concat(info)
ba5a8d89
C
95 if (options.first) {
96 infoArray = infoArray.slice(0, options.first)
97 } else if (options.last) {
98 infoArray = infoArray.slice(-options.last)
de29e90c 99 }
82f5527f 100 // Normalize utf8 fields
de29e90c 101 infoArray = infoArray.map(i => normalizeObject(i))
a7fea183 102
de29e90c
C
103 log.info('Will download and upload %d videos.\n', infoArray.length)
104
82f5527f 105 for (const [ index, info ] of infoArray.entries()) {
de29e90c 106 try {
ba5a8d89
C
107 if (index > 0 && options.waitInterval) {
108 log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000)
109 await new Promise(res => setTimeout(res, options.waitInterval))
82f5527f 110 }
de29e90c 111 await processVideo({
ba5a8d89 112 cwd: options.tmpdir,
de29e90c
C
113 url,
114 user,
115 youtubeInfo: info
116 })
117 } catch (err) {
82f5527f 118 console.error('Cannot process video.', { info, url, err })
a7fea183 119 }
de29e90c 120 }
a7fea183 121
ba5a8d89 122 log.info('Video/s for user %s imported: %s', user.username, options.targetUrl)
de29e90c 123 process.exit(0)
a7fea183
C
124}
125
82f5527f 126async function processVideo (parameters: {
a1587156
C
127 cwd: string
128 url: string
129 user: { username: string, password: string }
1a12f66d
C
130 youtubeInfo: any
131}) {
132 const { youtubeInfo, cwd, url, user } = parameters
1bcb03a1 133 const youtubeDL = new YoutubeDL('', [])
1a12f66d 134
82f5527f 135 log.debug('Fetching object.', youtubeInfo)
61b3e146 136
82f5527f
F
137 const videoInfo = await fetchObject(youtubeInfo)
138 log.debug('Fetched object.', videoInfo)
d0198ff9 139
1bcb03a1 140 const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo)
ba5a8d89 141 if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) {
82f5527f 142 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
ba5a8d89 143 videoInfo.title, formatDate(options.since))
82f5527f
F
144 return
145 }
ba5a8d89 146 if (options.until && originallyPublishedAt && originallyPublishedAt.getTime() > options.until.getTime()) {
82f5527f 147 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
ba5a8d89 148 videoInfo.title, formatDate(options.until))
82f5527f
F
149 return
150 }
e7872038 151
d7764e2e 152 const result = await advancedVideosSearch(url, { search: videoInfo.title, sort: '-match', searchTarget: 'local' })
e7872038 153
82f5527f 154 log.info('############################################################\n')
a7fea183 155
82f5527f
F
156 if (result.body.data.find(v => v.name === videoInfo.title)) {
157 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
158 return
159 }
a7fea183 160
82f5527f 161 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
a7fea183 162
82f5527f 163 log.info('Downloading video "%s"...', videoInfo.title)
f97d2992 164
1bcb03a1 165 const youtubeDLOptions = [ '-f', youtubeDL.getYoutubeDLVideoFormat(), ...command.args, '-o', path ]
82f5527f 166 try {
1bcb03a1
C
167 const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL()
168 const youtubeDLExec = promisify(youtubeDLBinary.exec).bind(youtubeDLBinary)
ba5a8d89 169 const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions)
82f5527f
F
170 log.info(output.join('\n'))
171 await uploadVideoOnPeerTube({
1bcb03a1 172 youtubeDL,
82f5527f
F
173 cwd,
174 url,
175 user,
176 videoInfo: normalizeObject(videoInfo),
177 videoPath: path
178 })
179 } catch (err) {
180 log.error(err.message)
181 }
a7fea183
C
182}
183
1a12f66d 184async function uploadVideoOnPeerTube (parameters: {
1bcb03a1 185 youtubeDL: YoutubeDL
a1587156
C
186 videoInfo: any
187 videoPath: string
188 cwd: string
189 url: string
190 user: { username: string, password: string }
1a12f66d 191}) {
1bcb03a1 192 const { youtubeDL, videoInfo, videoPath, cwd, url, user } = parameters
1a12f66d 193
8704acf4 194 const category = await getCategory(videoInfo.categories, url)
a7fea183 195 const licence = getLicence(videoInfo.license)
34cbef8c
C
196 let tags = []
197 if (Array.isArray(videoInfo.tags)) {
02988fdc 198 tags = videoInfo.tags
2b4dd7e2
C
199 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
200 .map(t => t.normalize())
201 .slice(0, 5)
34cbef8c 202 }
a7fea183 203
1d791a26
C
204 let thumbnailfile
205 if (videoInfo.thumbnail) {
fa27f076 206 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
1d791a26 207
b5c36108 208 await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile)
1d791a26
C
209 }
210
1bcb03a1 211 const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo)
84929846 212
1205823f 213 const defaultAttributes = {
45b8a42c 214 name: truncate(videoInfo.title, {
a1587156
C
215 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
216 separator: /,? +/,
217 omission: ' […]'
45b8a42c 218 }),
a7fea183
C
219 category,
220 licence,
a41e183c 221 nsfw: isNSFW(videoInfo),
1205823f
C
222 description: videoInfo.description,
223 tags
a7fea183
C
224 }
225
1205823f
C
226 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
227
228 Object.assign(videoAttributes, {
229 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
230 thumbnailfile,
231 previewfile: thumbnailfile,
232 fixture: videoPath
233 })
1a12f66d 234
bda3b705 235 log.info('\nUploading on PeerTube video "%s".', videoAttributes.name)
1a12f66d
C
236
237 let accessToken = await getAccessTokenOrDie(url, user)
238
71578f31 239 try {
8704acf4 240 await uploadVideo(url, accessToken, videoAttributes)
61b3e146 241 } catch (err) {
b6fe1f98 242 if (err.message.indexOf('401') !== -1) {
bda3b705 243 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
61b3e146 244
1a12f66d 245 accessToken = await getAccessTokenOrDie(url, user)
61b3e146 246
8704acf4 247 await uploadVideo(url, accessToken, videoAttributes)
61b3e146 248 } else {
bda3b705 249 exitError(err.message)
71578f31
L
250 }
251 }
1d791a26 252
62689b94
C
253 await remove(videoPath)
254 if (thumbnailfile) await remove(thumbnailfile)
1d791a26 255
bda3b705 256 log.warn('Uploaded video "%s"!\n', videoAttributes.name)
a7fea183
C
257}
258
1a12f66d
C
259/* ---------------------------------------------------------- */
260
8704acf4 261async function getCategory (categories: string[], url: string) {
61b3e146
C
262 if (!categories) return undefined
263
a1587156 264 const categoryString = categories[0]
a7fea183
C
265
266 if (categoryString === 'News & Politics') return 11
267
8704acf4 268 const res = await getVideoCategories(url)
a7fea183
C
269 const categoriesServer = res.body
270
271 for (const key of Object.keys(categoriesServer)) {
a1587156 272 const categoryServer = categoriesServer[key]
a7fea183
C
273 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
274 }
275
276 return undefined
277}
278
279function getLicence (licence: string) {
61b3e146
C
280 if (!licence) return undefined
281
bdd428a6 282 if (licence.includes('Creative Commons Attribution licence')) return 1
a7fea183
C
283
284 return undefined
285}
e7872038
C
286
287function normalizeObject (obj: any) {
288 const newObj: any = {}
289
290 for (const key of Object.keys(obj)) {
291 // Deprecated key
292 if (key === 'resolution') continue
293
a1587156 294 const value = obj[key]
e7872038
C
295
296 if (typeof value === 'string') {
a1587156 297 newObj[key] = value.normalize()
e7872038 298 } else {
a1587156 299 newObj[key] = value
e7872038
C
300 }
301 }
302
303 return newObj
304}
61b3e146
C
305
306function fetchObject (info: any) {
307 const url = buildUrl(info)
308
309 return new Promise<any>(async (res, rej) => {
1bcb03a1 310 const youtubeDL = await YoutubeDL.safeGetYoutubeDL()
a1587156 311 youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
61b3e146
C
312 if (err) return rej(err)
313
314 const videoInfoWithUrl = Object.assign(videoInfo, { url })
315 return res(normalizeObject(videoInfoWithUrl))
316 })
317 })
318}
319
320function buildUrl (info: any) {
a41e183c 321 const webpageUrl = info.webpage_url as string
a1587156 322 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
a41e183c 323
61b3e146 324 const url = info.url as string
a1587156 325 if (url?.match(/^https?:\/\//)) return url
61b3e146
C
326
327 // It seems youtube-dl does not return the video url
328 return 'https://www.youtube.com/watch?v=' + info.id
329}
a41e183c
C
330
331function isNSFW (info: any) {
1a12f66d 332 return info.age_limit && info.age_limit >= 16
a41e183c 333}
ab4dbe36 334
da69b886
C
335function normalizeTargetUrl (url: string) {
336 let normalizedUrl = url.replace(/\/+$/, '')
337
4449d269 338 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
da69b886
C
339 normalizedUrl = 'https://' + normalizedUrl
340 }
341
342 return normalizedUrl
ab4dbe36 343}
1a12f66d
C
344
345async function promptPassword () {
346 return new Promise<string>((res, rej) => {
347 prompt.start()
348 const schema = {
349 properties: {
350 password: {
351 hidden: true,
352 required: true
353 }
354 }
355 }
356 prompt.get(schema, function (err, result) {
357 if (err) {
358 return rej(err)
359 }
360 return res(result.password)
361 })
362 })
363}
364
365async function getAccessTokenOrDie (url: string, user: UserInfo) {
366 const resClient = await getClient(url)
367 const client = {
368 id: resClient.body.client_id,
369 secret: resClient.body.client_secret
370 }
371
372 try {
373 const res = await login(url, client, user)
374 return res.body.access_token
375 } catch (err) {
bda3b705 376 exitError('Cannot authenticate. Please check your username/password.')
1a12f66d
C
377 }
378}
d0198ff9
F
379
380function parseDate (dateAsStr: string): Date {
381 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
da69b886 382 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
d0198ff9 383 }
da69b886
C
384 const date = new Date(dateAsStr)
385 date.setHours(0, 0, 0)
d0198ff9 386 if (isNaN(date.getTime())) {
da69b886 387 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
d0198ff9 388 }
da69b886 389 return date
d0198ff9
F
390}
391
392function formatDate (date: Date): string {
a1587156 393 return date.toISOString().split('T')[0]
d0198ff9 394}
bda3b705 395
82f5527f
F
396function convertIntoMs (secondsAsStr: string): number {
397 const seconds = parseInt(secondsAsStr, 10)
398 if (seconds <= 0) {
399 exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
400 }
401 return Math.round(seconds * 1000)
402}
403
da69b886 404function exitError (message: string, ...meta: any[]) {
bda3b705
FL
405 // use console.error instead of log.error here
406 console.error(message, ...meta)
407 process.exit(-1)
408}
de29e90c
C
409
410function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) {
411 return new Promise<any>((res, rej) => {
412 const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ]
413
414 youtubeDL.getInfo(url, options, processOptions, async (err, info) => {
415 if (err) return rej(err)
416
417 return res(info)
418 })
419 })
420}