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