]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/peertube-import-videos.ts
Fix URL normalization in import script
[github/Chocobozzz/PeerTube.git] / server / tools / peertube-import-videos.ts
1 import { registerTSPaths } from '../helpers/register-ts-paths'
2
3 registerTSPaths()
4
5 // FIXME: https://github.com/nodejs/node/pull/16853
6 require('tls').DEFAULT_ECDH_CURVE = 'auto'
7
8 import * as program from 'commander'
9 import { join } from 'path'
10 import { doRequestAndSaveToFile } from '../helpers/requests'
11 import { CONSTRAINTS_FIELDS } from '../initializers/constants'
12 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
13 import { truncate } from 'lodash'
14 import * as prompt from 'prompt'
15 import { accessSync, constants } from 'fs'
16 import { remove } from 'fs-extra'
17 import { sha256 } from '../helpers/core-utils'
18 import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
19 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials, getLogger } from './cli'
20
21 type UserInfo = {
22 username: string
23 password: string
24 }
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('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
45 .parse(process.argv)
46
47 let log = getLogger(program[ 'verbose' ])
48
49 getServerCredentials(command)
50 .then(({ url, username, password }) => {
51 if (!program[ 'targetUrl' ]) {
52 exitError('--target-url field is required.')
53 }
54
55 try {
56 accessSync(program[ 'tmpdir' ], constants.R_OK | constants.W_OK)
57 } catch (e) {
58 exitError('--tmpdir %s: directory does not exist or is not accessible', program[ 'tmpdir' ])
59 }
60
61 url = normalizeTargetUrl(url)
62 program[ 'targetUrl' ] = normalizeTargetUrl(program[ 'targetUrl' ])
63
64 const user = { username, password }
65
66 run(url, user)
67 .catch(err => {
68 exitError(err)
69 })
70 })
71
72 async function run (url: string, user: UserInfo) {
73 if (!user.password) {
74 user.password = await promptPassword()
75 }
76
77 const youtubeDL = await safeGetYoutubeDL()
78
79 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
80 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
81 if (err) {
82 exitError(err.message)
83 }
84
85 let infoArray: any[]
86
87 // Normalize utf8 fields
88 infoArray = [].concat(info)
89 if (program[ 'first' ]) {
90 infoArray = infoArray.slice(0, program[ 'first' ])
91 } else if (program[ 'last' ]) {
92 infoArray = infoArray.slice(-program[ 'last' ])
93 }
94 infoArray = infoArray.map(i => normalizeObject(i))
95
96 log.info('Will download and upload %d videos.\n', infoArray.length)
97
98 for (const info of infoArray) {
99 await processVideo({
100 cwd: program[ 'tmpdir' ],
101 url,
102 user,
103 youtubeInfo: info
104 })
105 }
106
107 log.info('Video/s for user %s imported: %s', user.username, program[ 'targetUrl' ])
108 process.exit(0)
109 })
110 }
111
112 function processVideo (parameters: {
113 cwd: string,
114 url: string,
115 user: { username: string, password: string },
116 youtubeInfo: any
117 }) {
118 const { youtubeInfo, cwd, url, user } = parameters
119
120 return new Promise(async res => {
121 log.debug('Fetching object.', youtubeInfo)
122
123 const videoInfo = await fetchObject(youtubeInfo)
124 log.debug('Fetched object.', videoInfo)
125
126 if (program[ 'since' ]) {
127 if (buildOriginallyPublishedAt(videoInfo).getTime() < program[ 'since' ].getTime()) {
128 log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
129 videoInfo.title, formatDate(program[ 'since' ]))
130 return res()
131 }
132 }
133 if (program[ 'until' ]) {
134 if (buildOriginallyPublishedAt(videoInfo).getTime() > program[ 'until' ].getTime()) {
135 log.info('Video "%s" has been published after "%s", don\'t upload it.\n',
136 videoInfo.title, formatDate(program[ 'until' ]))
137 return res()
138 }
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', '-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.indexOf('Creative Commons Attribution licence') !== -1) 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, async (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 && webpageUrl.match(/^https?:\/\//)) return webpageUrl
321
322 const url = info.url as string
323 if (url && 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 }