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