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