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