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