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