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