]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/peertube-import-videos.ts
Merge branch 'develop' into pr/1285
[github/Chocobozzz/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 downloadEnabled: true,
228 description: videoInfo.description || undefined,
229 support: undefined,
230 tags,
231 privacy: VideoPrivacy.PUBLIC,
232 fixture: videoPath,
233 thumbnailfile,
234 previewfile: thumbnailfile
235 }
236
237 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
238 try {
239 await uploadVideo(url, accessToken, videoAttributes)
240 } catch (err) {
241 if (err.message.indexOf('401') !== -1) {
242 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
243
244 const res = await login(url, client, user)
245 accessToken = res.body.access_token
246
247 await uploadVideo(url, accessToken, videoAttributes)
248 } else {
249 console.log(err.message)
250 process.exit(1)
251 }
252 }
253
254 await remove(videoPath)
255 if (thumbnailfile) await remove(thumbnailfile)
256
257 console.log('Uploaded video "%s"!\n', videoAttributes.name)
258 }
259
260 async function getCategory (categories: string[], url: string) {
261 if (!categories) return undefined
262
263 const categoryString = categories[0]
264
265 if (categoryString === 'News & Politics') return 11
266
267 const res = await getVideoCategories(url)
268 const categoriesServer = res.body
269
270 for (const key of Object.keys(categoriesServer)) {
271 const categoryServer = categoriesServer[key]
272 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
273 }
274
275 return undefined
276 }
277
278 /* ---------------------------------------------------------- */
279
280 function getLicence (licence: string) {
281 if (!licence) return undefined
282
283 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
284
285 return undefined
286 }
287
288 function normalizeObject (obj: any) {
289 const newObj: any = {}
290
291 for (const key of Object.keys(obj)) {
292 // Deprecated key
293 if (key === 'resolution') continue
294
295 const value = obj[key]
296
297 if (typeof value === 'string') {
298 newObj[key] = value.normalize()
299 } else {
300 newObj[key] = value
301 }
302 }
303
304 return newObj
305 }
306
307 function fetchObject (info: any) {
308 const url = buildUrl(info)
309
310 return new Promise<any>(async (res, rej) => {
311 const youtubeDL = await safeGetYoutubeDL()
312 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
313 if (err) return rej(err)
314
315 const videoInfoWithUrl = Object.assign(videoInfo, { url })
316 return res(normalizeObject(videoInfoWithUrl))
317 })
318 })
319 }
320
321 function buildUrl (info: any) {
322 const webpageUrl = info.webpage_url as string
323 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
324
325 const url = info.url as string
326 if (url && url.match(/^https?:\/\//)) return url
327
328 // It seems youtube-dl does not return the video url
329 return 'https://www.youtube.com/watch?v=' + info.id
330 }
331
332 function isNSFW (info: any) {
333 if (info.age_limit && info.age_limit >= 16) return true
334
335 return false
336 }
337
338 function removeEndSlashes (url: string) {
339 while (url.endsWith('/')) {
340 url.slice(0, -1)
341 }
342 }