]>
Commit | Line | Data |
---|---|---|
2aaa1a3f C |
1 | import { registerTSPaths } from '../helpers/register-ts-paths' |
2 | registerTSPaths() | |
3 | ||
12152aa0 | 4 | import { program } from 'commander' |
d7764e2e | 5 | import { accessSync, constants } from 'fs' |
82f5527f | 6 | import { remove } from 'fs-extra' |
d7764e2e | 7 | import { join } from 'path' |
06aad801 | 8 | import { sha256 } from '@shared/core-utils/crypto' |
d7764e2e | 9 | import { doRequestAndSaveToFile } from '../helpers/requests' |
078f17e6 | 10 | import { |
d0a0fa42 | 11 | assignToken, |
078f17e6 C |
12 | buildCommonVideoOptions, |
13 | buildServer, | |
14 | buildVideoAttributesFromCommander, | |
078f17e6 C |
15 | getLogger, |
16 | getServerCredentials | |
17 | } from './cli' | |
62549e6c C |
18 | import { wait } from '@shared/extra-utils' |
19 | import { YoutubeDLCLI, YoutubeDLInfo, YoutubeDLInfoBuilder } from '@server/helpers/youtube-dl' | |
41fb13c3 C |
20 | import prompt = require('prompt') |
21 | ||
8704acf4 | 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') | |
82f5527f | 40 | .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs) |
bda3b705 | 41 | .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname) |
79ee77ea | 42 | .usage("[global options] [ -- youtube-dl options]") |
a7fea183 C |
43 | .parse(process.argv) |
44 | ||
ba5a8d89 C |
45 | const options = command.opts() |
46 | ||
47 | const log = getLogger(options.verbose) | |
bda3b705 | 48 | |
8d2be0ed C |
49 | getServerCredentials(command) |
50 | .then(({ url, username, password }) => { | |
ba5a8d89 | 51 | if (!options.targetUrl) { |
bda3b705 FL |
52 | exitError('--target-url field is required.') |
53 | } | |
e8a739e8 | 54 | |
bda3b705 | 55 | try { |
ba5a8d89 | 56 | accessSync(options.tmpdir, constants.R_OK | constants.W_OK) |
bda3b705 | 57 | } catch (e) { |
ba5a8d89 | 58 | exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir) |
8d2be0ed | 59 | } |
066fc8ba | 60 | |
da69b886 | 61 | url = normalizeTargetUrl(url) |
ba5a8d89 | 62 | options.targetUrl = normalizeTargetUrl(options.targetUrl) |
ab4dbe36 | 63 | |
078f17e6 | 64 | run(url, username, password) |
a1587156 | 65 | .catch(err => exitError(err)) |
8d2be0ed | 66 | }) |
a1587156 | 67 | .catch(err => console.error(err)) |
a7fea183 | 68 | |
078f17e6 C |
69 | async function run (url: string, username: string, password: string) { |
70 | if (!password) password = await promptPassword() | |
8a2db2e8 | 71 | |
62549e6c | 72 | const youtubeDLBinary = await YoutubeDLCLI.safeGet() |
8704acf4 | 73 | |
1bcb03a1 | 74 | let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args) |
79ee77ea | 75 | |
5721fd83 | 76 | if (!Array.isArray(info)) info = [ info ] |
a7fea183 | 77 | |
5721fd83 C |
78 | // Try to fix youtube channels upload |
79 | const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads') | |
80 | ||
81 | if (uploadsObject) { | |
82 | console.log('Fixing URL to %s.', uploadsObject.url) | |
83 | ||
1bcb03a1 | 84 | info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args) |
de29e90c | 85 | } |
a7fea183 | 86 | |
de29e90c | 87 | let infoArray: any[] |
bda3b705 | 88 | |
de29e90c | 89 | infoArray = [].concat(info) |
ba5a8d89 C |
90 | if (options.first) { |
91 | infoArray = infoArray.slice(0, options.first) | |
92 | } else if (options.last) { | |
93 | infoArray = infoArray.slice(-options.last) | |
de29e90c | 94 | } |
a7fea183 | 95 | |
de29e90c C |
96 | log.info('Will download and upload %d videos.\n', infoArray.length) |
97 | ||
e291096f | 98 | let skipInterval = true |
82f5527f | 99 | for (const [ index, info ] of infoArray.entries()) { |
de29e90c | 100 | try { |
e291096f | 101 | if (index > 0 && options.waitInterval && !skipInterval) { |
ba5a8d89 | 102 | log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000) |
62549e6c | 103 | await wait(options.waitInterval) |
82f5527f | 104 | } |
62549e6c | 105 | |
e291096f | 106 | skipInterval = await processVideo({ |
ba5a8d89 | 107 | cwd: options.tmpdir, |
de29e90c | 108 | url, |
078f17e6 C |
109 | username, |
110 | password, | |
de29e90c C |
111 | youtubeInfo: info |
112 | }) | |
113 | } catch (err) { | |
82f5527f | 114 | console.error('Cannot process video.', { info, url, err }) |
a7fea183 | 115 | } |
de29e90c | 116 | } |
a7fea183 | 117 | |
078f17e6 | 118 | log.info('Video/s for user %s imported: %s', username, options.targetUrl) |
de29e90c | 119 | process.exit(0) |
a7fea183 C |
120 | } |
121 | ||
82f5527f | 122 | async function processVideo (parameters: { |
a1587156 C |
123 | cwd: string |
124 | url: string | |
078f17e6 C |
125 | username: string |
126 | password: string | |
1a12f66d C |
127 | youtubeInfo: any |
128 | }) { | |
078f17e6 | 129 | const { youtubeInfo, cwd, url, username, password } = parameters |
1a12f66d | 130 | |
82f5527f | 131 | log.debug('Fetching object.', youtubeInfo) |
61b3e146 | 132 | |
82f5527f F |
133 | const videoInfo = await fetchObject(youtubeInfo) |
134 | log.debug('Fetched object.', videoInfo) | |
d0198ff9 | 135 | |
62549e6c C |
136 | if (options.since && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() < options.since.getTime()) { |
137 | log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.since)) | |
e291096f | 138 | return true |
82f5527f | 139 | } |
078f17e6 | 140 | |
62549e6c C |
141 | if (options.until && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() > options.until.getTime()) { |
142 | log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.until)) | |
e291096f | 143 | return true |
82f5527f | 144 | } |
e7872038 | 145 | |
078f17e6 | 146 | const server = buildServer(url) |
89d241a7 | 147 | const { data } = await server.search.advancedVideoSearch({ |
078f17e6 | 148 | search: { |
62549e6c | 149 | search: videoInfo.name, |
078f17e6 C |
150 | sort: '-match', |
151 | searchTarget: 'local' | |
152 | } | |
153 | }) | |
e7872038 | 154 | |
82f5527f | 155 | log.info('############################################################\n') |
a7fea183 | 156 | |
62549e6c C |
157 | if (data.find(v => v.name === videoInfo.name)) { |
158 | log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.name) | |
e291096f | 159 | return true |
82f5527f | 160 | } |
a7fea183 | 161 | |
82f5527f | 162 | const path = join(cwd, sha256(videoInfo.url) + '.mp4') |
a7fea183 | 163 | |
62549e6c | 164 | log.info('Downloading video "%s"...', videoInfo.name) |
f97d2992 | 165 | |
82f5527f | 166 | try { |
62549e6c C |
167 | const youtubeDLBinary = await YoutubeDLCLI.safeGet() |
168 | const output = await youtubeDLBinary.download({ | |
169 | url: videoInfo.url, | |
170 | format: YoutubeDLCLI.getYoutubeDLVideoFormat([]), | |
171 | output: path, | |
172 | additionalYoutubeDLArgs: command.args, | |
173 | processOptions | |
174 | }) | |
175 | ||
82f5527f F |
176 | log.info(output.join('\n')) |
177 | await uploadVideoOnPeerTube({ | |
178 | cwd, | |
179 | url, | |
078f17e6 C |
180 | username, |
181 | password, | |
62549e6c | 182 | videoInfo, |
82f5527f F |
183 | videoPath: path |
184 | }) | |
185 | } catch (err) { | |
186 | log.error(err.message) | |
187 | } | |
e291096f | 188 | |
189 | return false | |
a7fea183 C |
190 | } |
191 | ||
1a12f66d | 192 | async function uploadVideoOnPeerTube (parameters: { |
62549e6c | 193 | videoInfo: YoutubeDLInfo |
a1587156 C |
194 | videoPath: string |
195 | cwd: string | |
196 | url: string | |
078f17e6 C |
197 | username: string |
198 | password: string | |
1a12f66d | 199 | }) { |
62549e6c | 200 | const { videoInfo, videoPath, cwd, url, username, password } = parameters |
1a12f66d | 201 | |
d23dd9fb C |
202 | const server = buildServer(url) |
203 | await assignToken(server, username, password) | |
204 | ||
62549e6c C |
205 | let thumbnailfile: string |
206 | if (videoInfo.thumbnailUrl) { | |
207 | thumbnailfile = join(cwd, sha256(videoInfo.thumbnailUrl) + '.jpg') | |
1d791a26 | 208 | |
62549e6c | 209 | await doRequestAndSaveToFile(videoInfo.thumbnailUrl, thumbnailfile) |
1d791a26 C |
210 | } |
211 | ||
62549e6c | 212 | const baseAttributes = await buildVideoAttributesFromCommander(server, program, videoInfo) |
078f17e6 | 213 | |
d23dd9fb C |
214 | const attributes = { |
215 | ...baseAttributes, | |
1205823f | 216 | |
62549e6c C |
217 | originallyPublishedAt: videoInfo.originallyPublishedAt |
218 | ? videoInfo.originallyPublishedAt.toISOString() | |
219 | : null, | |
220 | ||
1205823f C |
221 | thumbnailfile, |
222 | previewfile: thumbnailfile, | |
223 | fixture: videoPath | |
d23dd9fb | 224 | } |
1a12f66d | 225 | |
d23dd9fb | 226 | log.info('\nUploading on PeerTube video "%s".', attributes.name) |
1a12f66d | 227 | |
71578f31 | 228 | try { |
89d241a7 | 229 | await server.videos.upload({ attributes }) |
61b3e146 | 230 | } catch (err) { |
b6fe1f98 | 231 | if (err.message.indexOf('401') !== -1) { |
bda3b705 | 232 | log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') |
61b3e146 | 233 | |
89d241a7 | 234 | server.accessToken = await server.login.getAccessToken(username, password) |
61b3e146 | 235 | |
89d241a7 | 236 | await server.videos.upload({ attributes }) |
61b3e146 | 237 | } else { |
bda3b705 | 238 | exitError(err.message) |
71578f31 L |
239 | } |
240 | } | |
1d791a26 | 241 | |
62689b94 C |
242 | await remove(videoPath) |
243 | if (thumbnailfile) await remove(thumbnailfile) | |
1d791a26 | 244 | |
62549e6c | 245 | log.info('Uploaded video "%s"!\n', attributes.name) |
a7fea183 C |
246 | } |
247 | ||
1a12f66d C |
248 | /* ---------------------------------------------------------- */ |
249 | ||
62549e6c C |
250 | async function fetchObject (info: any) { |
251 | const url = buildUrl(info) | |
e7872038 | 252 | |
62549e6c C |
253 | const youtubeDLCLI = await YoutubeDLCLI.safeGet() |
254 | const result = await youtubeDLCLI.getInfo({ | |
255 | url, | |
256 | format: YoutubeDLCLI.getYoutubeDLVideoFormat([]), | |
257 | processOptions | |
258 | }) | |
61b3e146 | 259 | |
62549e6c | 260 | const builder = new YoutubeDLInfoBuilder(result) |
61b3e146 | 261 | |
62549e6c | 262 | const videoInfo = builder.getInfo() |
61b3e146 | 263 | |
62549e6c | 264 | return { ...videoInfo, url } |
61b3e146 C |
265 | } |
266 | ||
267 | function buildUrl (info: any) { | |
a41e183c | 268 | const webpageUrl = info.webpage_url as string |
a1587156 | 269 | if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl |
a41e183c | 270 | |
61b3e146 | 271 | const url = info.url as string |
a1587156 | 272 | if (url?.match(/^https?:\/\//)) return url |
61b3e146 C |
273 | |
274 | // It seems youtube-dl does not return the video url | |
275 | return 'https://www.youtube.com/watch?v=' + info.id | |
276 | } | |
a41e183c | 277 | |
da69b886 C |
278 | function normalizeTargetUrl (url: string) { |
279 | let normalizedUrl = url.replace(/\/+$/, '') | |
280 | ||
4449d269 | 281 | if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) { |
da69b886 C |
282 | normalizedUrl = 'https://' + normalizedUrl |
283 | } | |
284 | ||
285 | return normalizedUrl | |
ab4dbe36 | 286 | } |
1a12f66d C |
287 | |
288 | async function promptPassword () { | |
289 | return new Promise<string>((res, rej) => { | |
290 | prompt.start() | |
291 | const schema = { | |
292 | properties: { | |
293 | password: { | |
294 | hidden: true, | |
295 | required: true | |
296 | } | |
297 | } | |
298 | } | |
299 | prompt.get(schema, function (err, result) { | |
300 | if (err) { | |
301 | return rej(err) | |
302 | } | |
303 | return res(result.password) | |
304 | }) | |
305 | }) | |
306 | } | |
307 | ||
d0198ff9 F |
308 | function parseDate (dateAsStr: string): Date { |
309 | if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) { | |
da69b886 | 310 | exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`) |
d0198ff9 | 311 | } |
da69b886 C |
312 | const date = new Date(dateAsStr) |
313 | date.setHours(0, 0, 0) | |
d0198ff9 | 314 | if (isNaN(date.getTime())) { |
da69b886 | 315 | exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`) |
d0198ff9 | 316 | } |
da69b886 | 317 | return date |
d0198ff9 F |
318 | } |
319 | ||
320 | function formatDate (date: Date): string { | |
a1587156 | 321 | return date.toISOString().split('T')[0] |
d0198ff9 | 322 | } |
bda3b705 | 323 | |
82f5527f F |
324 | function convertIntoMs (secondsAsStr: string): number { |
325 | const seconds = parseInt(secondsAsStr, 10) | |
326 | if (seconds <= 0) { | |
327 | exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`) | |
328 | } | |
329 | return Math.round(seconds * 1000) | |
330 | } | |
331 | ||
da69b886 | 332 | function exitError (message: string, ...meta: any[]) { |
bda3b705 FL |
333 | // use console.error instead of log.error here |
334 | console.error(message, ...meta) | |
335 | process.exit(-1) | |
336 | } | |
de29e90c | 337 | |
62549e6c C |
338 | function getYoutubeDLInfo (youtubeDLCLI: YoutubeDLCLI, url: string, args: string[]) { |
339 | return youtubeDLCLI.getInfo({ | |
340 | url, | |
341 | format: YoutubeDLCLI.getYoutubeDLVideoFormat([]), | |
342 | additionalYoutubeDLArgs: [ '-j', '--flat-playlist', '--playlist-reverse', ...args ], | |
343 | processOptions | |
de29e90c C |
344 | }) |
345 | } |