Merge branch 'release/v1.2.0'
[oweals/peertube.git] / server / tools / peertube-import-videos.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
4 import * as program from 'commander'
5 import { join } from 'path'
6 import { VideoPrivacy } from '../../shared/models/videos'
7 import { doRequestAndSaveToFile } from '../helpers/requests'
8 import { CONSTRAINTS_FIELDS } from '../initializers'
9 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/utils/index'
10 import { truncate } from 'lodash'
11 import * as prompt from 'prompt'
12 import { remove } from 'fs-extra'
13 import { sha256 } from '../helpers/core-utils'
14 import { safeGetYoutubeDL } from '../helpers/youtube-dl'
15 import { getSettings, netrc } from './cli'
16
17 let accessToken: string
18 let client: { id: string, secret: string }
19
20 const processOptions = {
21   cwd: __dirname,
22   maxBuffer: Infinity
23 }
24
25 program
26   .name('import-videos')
27   .option('-u, --url <url>', 'Server url')
28   .option('-U, --username <username>', 'Username')
29   .option('-p, --password <token>', 'Password')
30   .option('-t, --target-url <targetUrl>', 'Video target URL')
31   .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)')
32   .option('-v, --verbose', 'Verbose mode')
33   .parse(process.argv)
34
35 getSettings()
36 .then(settings => {
37   if (
38     (!program['url'] ||
39     !program['username'] ||
40     !program['password']) &&
41     (settings.remotes.length === 0)
42   ) {
43     if (!program['url']) console.error('--url field is required.')
44     if (!program['username']) console.error('--username field is required.')
45     if (!program['password']) console.error('--password field is required.')
46     if (!program['targetUrl']) console.error('--targetUrl field is required.')
47     process.exit(-1)
48   }
49
50   if (
51     (!program['url'] ||
52     !program['username'] ||
53     !program['password']) &&
54     (settings.remotes.length > 0)
55   ) {
56     if (!program['url']) {
57       program['url'] = (settings.default !== -1) ?
58         settings.remotes[settings.default] :
59         settings.remotes[0]
60     }
61
62     if (!program['username']) program['username'] = netrc.machines[program['url']].login
63     if (!program['password']) program['password'] = netrc.machines[program['url']].password
64   }
65
66   if (
67     !program['targetUrl']
68   ) {
69     if (!program['targetUrl']) console.error('--targetUrl field is required.')
70     process.exit(-1)
71   }
72
73   removeEndSlashes(program['url'])
74   removeEndSlashes(program['targetUrl'])
75
76   const user = {
77     username: program['username'],
78     password: program['password']
79   }
80
81   run(user, program['url'])
82     .catch(err => {
83       console.error(err)
84       process.exit(-1)
85     })
86 })
87
88 async function promptPassword () {
89   return new Promise((res, rej) => {
90     prompt.start()
91     const schema = {
92       properties: {
93         password: {
94           hidden: true,
95           required: true
96         }
97       }
98     }
99     prompt.get(schema, function (err, result) {
100       if (err) {
101         return rej(err)
102       }
103       return res(result.password)
104     })
105   })
106 }
107
108 async function run (user, url: string) {
109   if (!user.password) {
110     user.password = await promptPassword()
111   }
112
113   const res = await getClient(url)
114   client = {
115     id: res.body.client_id,
116     secret: res.body.client_secret
117   }
118
119   try {
120     const res = await login(program[ 'url' ], client, user)
121     accessToken = res.body.access_token
122   } catch (err) {
123     throw new Error('Cannot authenticate. Please check your username/password.')
124   }
125
126   const youtubeDL = await safeGetYoutubeDL()
127
128   const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
129   youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
130     if (err) {
131       console.log(err.message)
132       process.exit(1)
133     }
134
135     let infoArray: any[]
136
137     // Normalize utf8 fields
138     if (Array.isArray(info) === true) {
139       infoArray = info.map(i => normalizeObject(i))
140     } else {
141       infoArray = [ normalizeObject(info) ]
142     }
143     console.log('Will download and upload %d videos.\n', infoArray.length)
144
145     for (const info of infoArray) {
146       await processVideo(info, program['language'], processOptions.cwd, url, user)
147     }
148
149     console.log('Video/s for user %s imported: %s', program['username'], program['targetUrl'])
150     process.exit(0)
151   })
152 }
153
154 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
155   return new Promise(async res => {
156     if (program['verbose']) console.log('Fetching object.', info)
157
158     const videoInfo = await fetchObject(info)
159     if (program['verbose']) console.log('Fetched object.', videoInfo)
160
161     const result = await searchVideoWithSort(url, videoInfo.title, '-match')
162
163     console.log('############################################################\n')
164
165     if (result.body.data.find(v => v.name === videoInfo.title)) {
166       console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
167       return res()
168     }
169
170     const path = join(cwd, sha256(videoInfo.url) + '.mp4')
171
172     console.log('Downloading video "%s"...', videoInfo.title)
173
174     const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
175     try {
176       const youtubeDL = await safeGetYoutubeDL()
177       youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
178         if (err) {
179           console.error(err)
180           return res()
181         }
182
183         console.log(output.join('\n'))
184         await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
185         return res()
186       })
187     } catch (err) {
188       console.log(err.message)
189       return res()
190     }
191   })
192 }
193
194 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
195   const category = await getCategory(videoInfo.categories, url)
196   const licence = getLicence(videoInfo.license)
197   let tags = []
198   if (Array.isArray(videoInfo.tags)) {
199     tags = videoInfo.tags
200       .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
201       .map(t => t.normalize())
202       .slice(0, 5)
203   }
204
205   let thumbnailfile
206   if (videoInfo.thumbnail) {
207     thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
208
209     await doRequestAndSaveToFile({
210       method: 'GET',
211       uri: videoInfo.thumbnail
212     }, thumbnailfile)
213   }
214
215   const videoAttributes = {
216     name: truncate(videoInfo.title, {
217       'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
218       'separator': /,? +/,
219       'omission': ' […]'
220     }),
221     category,
222     licence,
223     language,
224     nsfw: isNSFW(videoInfo),
225     waitTranscoding: true,
226     commentsEnabled: true,
227     description: videoInfo.description || undefined,
228     support: undefined,
229     tags,
230     privacy: VideoPrivacy.PUBLIC,
231     fixture: videoPath,
232     thumbnailfile,
233     previewfile: thumbnailfile
234   }
235
236   console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
237   try {
238     await uploadVideo(url, accessToken, videoAttributes)
239   } catch (err) {
240     if (err.message.indexOf('401') !== -1) {
241       console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
242
243       const res = await login(url, client, user)
244       accessToken = res.body.access_token
245
246       await uploadVideo(url, accessToken, videoAttributes)
247     } else {
248       console.log(err.message)
249       process.exit(1)
250     }
251   }
252
253   await remove(videoPath)
254   if (thumbnailfile) await remove(thumbnailfile)
255
256   console.log('Uploaded video "%s"!\n', videoAttributes.name)
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 /* ---------------------------------------------------------- */
278
279 function getLicence (licence: string) {
280   if (!licence) return undefined
281
282   if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
283
284   return undefined
285 }
286
287 function normalizeObject (obj: any) {
288   const newObj: any = {}
289
290   for (const key of Object.keys(obj)) {
291     // Deprecated key
292     if (key === 'resolution') continue
293
294     const value = obj[key]
295
296     if (typeof value === 'string') {
297       newObj[key] = value.normalize()
298     } else {
299       newObj[key] = value
300     }
301   }
302
303   return newObj
304 }
305
306 function fetchObject (info: any) {
307   const url = buildUrl(info)
308
309   return new Promise<any>(async (res, rej) => {
310     const youtubeDL = await safeGetYoutubeDL()
311     youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
312       if (err) return rej(err)
313
314       const videoInfoWithUrl = Object.assign(videoInfo, { url })
315       return res(normalizeObject(videoInfoWithUrl))
316     })
317   })
318 }
319
320 function buildUrl (info: any) {
321   const webpageUrl = info.webpage_url as string
322   if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
323
324   const url = info.url as string
325   if (url && url.match(/^https?:\/\//)) return url
326
327   // It seems youtube-dl does not return the video url
328   return 'https://www.youtube.com/watch?v=' + info.id
329 }
330
331 function isNSFW (info: any) {
332   if (info.age_limit && info.age_limit >= 16) return true
333
334   return false
335 }
336
337 function removeEndSlashes (url: string) {
338   while (url.endsWith('/')) {
339     url.slice(0, -1)
340   }
341 }