allow peertube-import-videos.ts CLI script to run concurrently (#1334)
[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 '../tests/utils'
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     if (!program['username']) program['username'] = netrc.machines[program['url']].login
62     if (!program['password']) program['password'] = netrc.machines[program['url']].password
63   }
64
65   if (
66     !program['targetUrl']
67   ) {
68     if (!program['targetUrl']) console.error('--targetUrl field is required.')
69     process.exit(-1)
70   }
71
72   const user = {
73     username: program['username'],
74     password: program['password']
75   }
76
77   run(user, program['url']).catch(err => console.error(err))
78 })
79
80 async function promptPassword () {
81   return new Promise((res, rej) => {
82     prompt.start()
83     const schema = {
84       properties: {
85         password: {
86           hidden: true,
87           required: true
88         }
89       }
90     }
91     prompt.get(schema, function (err, result) {
92       if (err) {
93         return rej(err)
94       }
95       return res(result.password)
96     })
97   })
98 }
99
100 async function run (user, url: string) {
101   if (!user.password) {
102     user.password = await promptPassword()
103   }
104
105   const res = await getClient(url)
106   client = {
107     id: res.body.client_id,
108     secret: res.body.client_secret
109   }
110
111   const res2 = await login(url, client, user)
112   accessToken = res2.body.access_token
113
114   const youtubeDL = await safeGetYoutubeDL()
115
116   const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
117   youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
118     if (err) {
119       console.log(err.message)
120       process.exit(1)
121     }
122
123     let infoArray: any[]
124
125     // Normalize utf8 fields
126     if (Array.isArray(info) === true) {
127       infoArray = info.map(i => normalizeObject(i))
128     } else {
129       infoArray = [ normalizeObject(info) ]
130     }
131     console.log('Will download and upload %d videos.\n', infoArray.length)
132
133     for (const info of infoArray) {
134       await processVideo(info, program['language'], processOptions.cwd, url, user)
135     }
136
137     console.log('Video/s for user %s imported: %s', program['username'], program['targetUrl'])
138     process.exit(0)
139   })
140 }
141
142 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
143   return new Promise(async res => {
144     if (program['verbose']) console.log('Fetching object.', info)
145
146     const videoInfo = await fetchObject(info)
147     if (program['verbose']) console.log('Fetched object.', videoInfo)
148
149     const result = await searchVideoWithSort(url, videoInfo.title, '-match')
150
151     console.log('############################################################\n')
152
153     if (result.body.data.find(v => v.name === videoInfo.title)) {
154       console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
155       return res()
156     }
157
158     const path = join(cwd, sha256(videoInfo.url) + '.mp4')
159
160     console.log('Downloading video "%s"...', videoInfo.title)
161
162     const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
163     try {
164       const youtubeDL = await safeGetYoutubeDL()
165       youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
166         if (err) {
167           console.error(err)
168           return res()
169         }
170
171         console.log(output.join('\n'))
172         await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
173         return res()
174       })
175     } catch (err) {
176       console.log(err.message)
177       return res()
178     }
179   })
180 }
181
182 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
183   const category = await getCategory(videoInfo.categories, url)
184   const licence = getLicence(videoInfo.license)
185   let tags = []
186   if (Array.isArray(videoInfo.tags)) {
187     tags = videoInfo.tags
188       .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
189       .map(t => t.normalize())
190       .slice(0, 5)
191   }
192
193   let thumbnailfile
194   if (videoInfo.thumbnail) {
195     thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
196
197     await doRequestAndSaveToFile({
198       method: 'GET',
199       uri: videoInfo.thumbnail
200     }, thumbnailfile)
201   }
202
203   const videoAttributes = {
204     name: truncate(videoInfo.title, {
205       'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
206       'separator': /,? +/,
207       'omission': ' […]'
208     }),
209     category,
210     licence,
211     language,
212     nsfw: isNSFW(videoInfo),
213     waitTranscoding: true,
214     commentsEnabled: true,
215     description: videoInfo.description || undefined,
216     support: undefined,
217     tags,
218     privacy: VideoPrivacy.PUBLIC,
219     fixture: videoPath,
220     thumbnailfile,
221     previewfile: thumbnailfile
222   }
223
224   console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
225   try {
226     await uploadVideo(url, accessToken, videoAttributes)
227   } catch (err) {
228     if (err.message.indexOf('401') !== -1) {
229       console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
230
231       const res = await login(url, client, user)
232       accessToken = res.body.access_token
233
234       await uploadVideo(url, accessToken, videoAttributes)
235     } else {
236       console.log(err.message)
237       process.exit(1)
238     }
239   }
240
241   await remove(videoPath)
242   if (thumbnailfile) await remove(thumbnailfile)
243
244   console.log('Uploaded video "%s"!\n', videoAttributes.name)
245 }
246
247 async function getCategory (categories: string[], url: string) {
248   if (!categories) return undefined
249
250   const categoryString = categories[0]
251
252   if (categoryString === 'News & Politics') return 11
253
254   const res = await getVideoCategories(url)
255   const categoriesServer = res.body
256
257   for (const key of Object.keys(categoriesServer)) {
258     const categoryServer = categoriesServer[key]
259     if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
260   }
261
262   return undefined
263 }
264
265 /* ---------------------------------------------------------- */
266
267 function getLicence (licence: string) {
268   if (!licence) return undefined
269
270   if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
271
272   return undefined
273 }
274
275 function normalizeObject (obj: any) {
276   const newObj: any = {}
277
278   for (const key of Object.keys(obj)) {
279     // Deprecated key
280     if (key === 'resolution') continue
281
282     const value = obj[key]
283
284     if (typeof value === 'string') {
285       newObj[key] = value.normalize()
286     } else {
287       newObj[key] = value
288     }
289   }
290
291   return newObj
292 }
293
294 function fetchObject (info: any) {
295   const url = buildUrl(info)
296
297   return new Promise<any>(async (res, rej) => {
298     const youtubeDL = await safeGetYoutubeDL()
299     youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
300       if (err) return rej(err)
301
302       const videoInfoWithUrl = Object.assign(videoInfo, { url })
303       return res(normalizeObject(videoInfoWithUrl))
304     })
305   })
306 }
307
308 function buildUrl (info: any) {
309   const webpageUrl = info.webpage_url as string
310   if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
311
312   const url = info.url as string
313   if (url && url.match(/^https?:\/\//)) return url
314
315   // It seems youtube-dl does not return the video url
316   return 'https://www.youtube.com/watch?v=' + info.id
317 }
318
319 function isNSFW (info: any) {
320   if (info.age_limit && info.age_limit >= 16) return true
321
322   return false
323 }