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