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