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