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