]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/tools/peertube-import-videos.ts
Update changelog
[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
1a73a7dc 16} from './shared'
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)
7e0f50d6 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) {
7e0f50d6 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
cbdd81da
C
134 if (
135 options.since &&
136 videoInfo.originallyPublishedAtWithoutTime &&
137 videoInfo.originallyPublishedAtWithoutTime.getTime() < options.since.getTime()
138 ) {
62549e6c 139 log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.since))
e291096f 140 return true
82f5527f 141 }
078f17e6 142
cbdd81da
C
143 if (
144 options.until &&
145 videoInfo.originallyPublishedAtWithoutTime &&
146 videoInfo.originallyPublishedAtWithoutTime.getTime() > options.until.getTime()
147 ) {
62549e6c 148 log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.until))
e291096f 149 return true
82f5527f 150 }
e7872038 151
078f17e6 152 const server = buildServer(url)
89d241a7 153 const { data } = await server.search.advancedVideoSearch({
078f17e6 154 search: {
62549e6c 155 search: videoInfo.name,
078f17e6
C
156 sort: '-match',
157 searchTarget: 'local'
158 }
159 })
e7872038 160
82f5527f 161 log.info('############################################################\n')
a7fea183 162
62549e6c
C
163 if (data.find(v => v.name === videoInfo.name)) {
164 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.name)
e291096f 165 return true
82f5527f 166 }
a7fea183 167
82f5527f 168 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
a7fea183 169
62549e6c 170 log.info('Downloading video "%s"...', videoInfo.name)
f97d2992 171
82f5527f 172 try {
62549e6c
C
173 const youtubeDLBinary = await YoutubeDLCLI.safeGet()
174 const output = await youtubeDLBinary.download({
175 url: videoInfo.url,
b42c2c7e 176 format: YoutubeDLCLI.getYoutubeDLVideoFormat([], false),
62549e6c
C
177 output: path,
178 additionalYoutubeDLArgs: command.args,
179 processOptions
180 })
181
82f5527f
F
182 log.info(output.join('\n'))
183 await uploadVideoOnPeerTube({
184 cwd,
185 url,
078f17e6
C
186 username,
187 password,
62549e6c 188 videoInfo,
82f5527f
F
189 videoPath: path
190 })
191 } catch (err) {
192 log.error(err.message)
193 }
e291096f 194
195 return false
a7fea183
C
196}
197
1a12f66d 198async function uploadVideoOnPeerTube (parameters: {
62549e6c 199 videoInfo: YoutubeDLInfo
a1587156
C
200 videoPath: string
201 cwd: string
202 url: string
078f17e6
C
203 username: string
204 password: string
1a12f66d 205}) {
62549e6c 206 const { videoInfo, videoPath, cwd, url, username, password } = parameters
1a12f66d 207
d23dd9fb
C
208 const server = buildServer(url)
209 await assignToken(server, username, password)
210
62549e6c
C
211 let thumbnailfile: string
212 if (videoInfo.thumbnailUrl) {
213 thumbnailfile = join(cwd, sha256(videoInfo.thumbnailUrl) + '.jpg')
1d791a26 214
62549e6c 215 await doRequestAndSaveToFile(videoInfo.thumbnailUrl, thumbnailfile)
1d791a26
C
216 }
217
62549e6c 218 const baseAttributes = await buildVideoAttributesFromCommander(server, program, videoInfo)
078f17e6 219
d23dd9fb
C
220 const attributes = {
221 ...baseAttributes,
1205823f 222
cbdd81da
C
223 originallyPublishedAtWithoutTime: videoInfo.originallyPublishedAtWithoutTime
224 ? videoInfo.originallyPublishedAtWithoutTime.toISOString()
62549e6c
C
225 : null,
226
1205823f
C
227 thumbnailfile,
228 previewfile: thumbnailfile,
229 fixture: videoPath
d23dd9fb 230 }
1a12f66d 231
d23dd9fb 232 log.info('\nUploading on PeerTube video "%s".', attributes.name)
1a12f66d 233
71578f31 234 try {
89d241a7 235 await server.videos.upload({ attributes })
61b3e146 236 } catch (err) {
b6fe1f98 237 if (err.message.indexOf('401') !== -1) {
bda3b705 238 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
61b3e146 239
89d241a7 240 server.accessToken = await server.login.getAccessToken(username, password)
61b3e146 241
89d241a7 242 await server.videos.upload({ attributes })
61b3e146 243 } else {
bda3b705 244 exitError(err.message)
71578f31
L
245 }
246 }
1d791a26 247
62689b94
C
248 await remove(videoPath)
249 if (thumbnailfile) await remove(thumbnailfile)
1d791a26 250
62549e6c 251 log.info('Uploaded video "%s"!\n', attributes.name)
a7fea183
C
252}
253
1a12f66d
C
254/* ---------------------------------------------------------- */
255
62549e6c
C
256async function fetchObject (info: any) {
257 const url = buildUrl(info)
e7872038 258
62549e6c
C
259 const youtubeDLCLI = await YoutubeDLCLI.safeGet()
260 const result = await youtubeDLCLI.getInfo({
261 url,
b42c2c7e 262 format: YoutubeDLCLI.getYoutubeDLVideoFormat([], false),
62549e6c
C
263 processOptions
264 })
61b3e146 265
62549e6c 266 const builder = new YoutubeDLInfoBuilder(result)
61b3e146 267
62549e6c 268 const videoInfo = builder.getInfo()
61b3e146 269
62549e6c 270 return { ...videoInfo, url }
61b3e146
C
271}
272
273function buildUrl (info: any) {
a41e183c 274 const webpageUrl = info.webpage_url as string
a1587156 275 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
a41e183c 276
61b3e146 277 const url = info.url as string
a1587156 278 if (url?.match(/^https?:\/\//)) return url
61b3e146
C
279
280 // It seems youtube-dl does not return the video url
281 return 'https://www.youtube.com/watch?v=' + info.id
282}
a41e183c 283
da69b886
C
284function normalizeTargetUrl (url: string) {
285 let normalizedUrl = url.replace(/\/+$/, '')
286
4449d269 287 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
da69b886
C
288 normalizedUrl = 'https://' + normalizedUrl
289 }
290
291 return normalizedUrl
ab4dbe36 292}
1a12f66d
C
293
294async function promptPassword () {
295 return new Promise<string>((res, rej) => {
296 prompt.start()
297 const schema = {
298 properties: {
299 password: {
300 hidden: true,
301 required: true
302 }
303 }
304 }
305 prompt.get(schema, function (err, result) {
306 if (err) {
307 return rej(err)
308 }
309 return res(result.password)
310 })
311 })
312}
313
d0198ff9
F
314function parseDate (dateAsStr: string): Date {
315 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
da69b886 316 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
d0198ff9 317 }
da69b886
C
318 const date = new Date(dateAsStr)
319 date.setHours(0, 0, 0)
d0198ff9 320 if (isNaN(date.getTime())) {
da69b886 321 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
d0198ff9 322 }
da69b886 323 return date
d0198ff9
F
324}
325
326function formatDate (date: Date): string {
a1587156 327 return date.toISOString().split('T')[0]
d0198ff9 328}
bda3b705 329
82f5527f
F
330function convertIntoMs (secondsAsStr: string): number {
331 const seconds = parseInt(secondsAsStr, 10)
332 if (seconds <= 0) {
333 exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
334 }
335 return Math.round(seconds * 1000)
336}
337
da69b886 338function exitError (message: string, ...meta: any[]) {
bda3b705
FL
339 // use console.error instead of log.error here
340 console.error(message, ...meta)
341 process.exit(-1)
342}
de29e90c 343
62549e6c
C
344function getYoutubeDLInfo (youtubeDLCLI: YoutubeDLCLI, url: string, args: string[]) {
345 return youtubeDLCLI.getInfo({
346 url,
b42c2c7e 347 format: YoutubeDLCLI.getYoutubeDLVideoFormat([], false),
62549e6c
C
348 additionalYoutubeDLArgs: [ '-j', '--flat-playlist', '--playlist-reverse', ...args ],
349 processOptions
de29e90c
C
350 })
351}