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