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