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