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