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