]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/peertube-import-videos.ts
Force video updatedAt update on update
[github/Chocobozzz/PeerTube.git] / server / tools / peertube-import-videos.ts
1 import { registerTSPaths } from '../helpers/register-ts-paths'
2 registerTSPaths()
3
4 import { program } from 'commander'
5 import { accessSync, constants } from 'fs'
6 import { remove } from 'fs-extra'
7 import { join } from 'path'
8 import { sha256 } from '../helpers/core-utils'
9 import { doRequestAndSaveToFile } from '../helpers/requests'
10 import {
11 assignToken,
12 buildCommonVideoOptions,
13 buildServer,
14 buildVideoAttributesFromCommander,
15 getLogger,
16 getServerCredentials
17 } from './cli'
18 import { wait } from '@shared/extra-utils'
19 import { YoutubeDLCLI, YoutubeDLInfo, YoutubeDLInfoBuilder } from '@server/helpers/youtube-dl'
20 import prompt = require('prompt')
21
22 const processOptions = {
23 maxBuffer: Infinity
24 }
25
26 let command = program
27 .name('import-videos')
28
29 command = buildCommonVideoOptions(command)
30
31 command
32 .option('-u, --url <url>', 'Server url')
33 .option('-U, --username <username>', 'Username')
34 .option('-p, --password <token>', 'Password')
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)
38 .option('--first <first>', 'Process first n elements of returned playlist')
39 .option('--last <last>', 'Process last n elements of returned playlist')
40 .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs)
41 .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
42 .usage("[global options] [ -- youtube-dl options]")
43 .parse(process.argv)
44
45 const options = command.opts()
46
47 const log = getLogger(options.verbose)
48
49 getServerCredentials(command)
50 .then(({ url, username, password }) => {
51 if (!options.targetUrl) {
52 exitError('--target-url field is required.')
53 }
54
55 try {
56 accessSync(options.tmpdir, constants.R_OK | constants.W_OK)
57 } catch (e) {
58 exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir)
59 }
60
61 url = normalizeTargetUrl(url)
62 options.targetUrl = normalizeTargetUrl(options.targetUrl)
63
64 run(url, username, password)
65 .catch(err => exitError(err))
66 })
67 .catch(err => console.error(err))
68
69 async function run (url: string, username: string, password: string) {
70 if (!password) password = await promptPassword()
71
72 const youtubeDLBinary = await YoutubeDLCLI.safeGet()
73
74 let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args)
75
76 if (!Array.isArray(info)) info = [ info ]
77
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
84 info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args)
85 }
86
87 let infoArray: any[]
88
89 infoArray = [].concat(info)
90 if (options.first) {
91 infoArray = infoArray.slice(0, options.first)
92 } else if (options.last) {
93 infoArray = infoArray.slice(-options.last)
94 }
95
96 log.info('Will download and upload %d videos.\n', infoArray.length)
97
98 for (const [ index, info ] of infoArray.entries()) {
99 try {
100 if (index > 0 && options.waitInterval) {
101 log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000)
102 await wait(options.waitInterval)
103 }
104
105 await processVideo({
106 cwd: options.tmpdir,
107 url,
108 username,
109 password,
110 youtubeInfo: info
111 })
112 } catch (err) {
113 console.error('Cannot process video.', { info, url, err })
114 }
115 }
116
117 log.info('Video/s for user %s imported: %s', username, options.targetUrl)
118 process.exit(0)
119 }
120
121 async function processVideo (parameters: {
122 cwd: string
123 url: string
124 username: string
125 password: string
126 youtubeInfo: any
127 }) {
128 const { youtubeInfo, cwd, url, username, password } = parameters
129
130 log.debug('Fetching object.', youtubeInfo)
131
132 const videoInfo = await fetchObject(youtubeInfo)
133 log.debug('Fetched object.', videoInfo)
134
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))
137 return
138 }
139
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))
142 return
143 }
144
145 const server = buildServer(url)
146 const { data } = await server.search.advancedVideoSearch({
147 search: {
148 search: videoInfo.name,
149 sort: '-match',
150 searchTarget: 'local'
151 }
152 })
153
154 log.info('############################################################\n')
155
156 if (data.find(v => v.name === videoInfo.name)) {
157 log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.name)
158 return
159 }
160
161 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
162
163 log.info('Downloading video "%s"...', videoInfo.name)
164
165 try {
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
175 log.info(output.join('\n'))
176 await uploadVideoOnPeerTube({
177 cwd,
178 url,
179 username,
180 password,
181 videoInfo,
182 videoPath: path
183 })
184 } catch (err) {
185 log.error(err.message)
186 }
187 }
188
189 async function uploadVideoOnPeerTube (parameters: {
190 videoInfo: YoutubeDLInfo
191 videoPath: string
192 cwd: string
193 url: string
194 username: string
195 password: string
196 }) {
197 const { videoInfo, videoPath, cwd, url, username, password } = parameters
198
199 const server = buildServer(url)
200 await assignToken(server, username, password)
201
202 let thumbnailfile: string
203 if (videoInfo.thumbnailUrl) {
204 thumbnailfile = join(cwd, sha256(videoInfo.thumbnailUrl) + '.jpg')
205
206 await doRequestAndSaveToFile(videoInfo.thumbnailUrl, thumbnailfile)
207 }
208
209 const baseAttributes = await buildVideoAttributesFromCommander(server, program, videoInfo)
210
211 const attributes = {
212 ...baseAttributes,
213
214 originallyPublishedAt: videoInfo.originallyPublishedAt
215 ? videoInfo.originallyPublishedAt.toISOString()
216 : null,
217
218 thumbnailfile,
219 previewfile: thumbnailfile,
220 fixture: videoPath
221 }
222
223 log.info('\nUploading on PeerTube video "%s".', attributes.name)
224
225 try {
226 await server.videos.upload({ attributes })
227 } catch (err) {
228 if (err.message.indexOf('401') !== -1) {
229 log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
230
231 server.accessToken = await server.login.getAccessToken(username, password)
232
233 await server.videos.upload({ attributes })
234 } else {
235 exitError(err.message)
236 }
237 }
238
239 await remove(videoPath)
240 if (thumbnailfile) await remove(thumbnailfile)
241
242 log.info('Uploaded video "%s"!\n', attributes.name)
243 }
244
245 /* ---------------------------------------------------------- */
246
247 async function fetchObject (info: any) {
248 const url = buildUrl(info)
249
250 const youtubeDLCLI = await YoutubeDLCLI.safeGet()
251 const result = await youtubeDLCLI.getInfo({
252 url,
253 format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
254 processOptions
255 })
256
257 const builder = new YoutubeDLInfoBuilder(result)
258
259 const videoInfo = builder.getInfo()
260
261 return { ...videoInfo, url }
262 }
263
264 function buildUrl (info: any) {
265 const webpageUrl = info.webpage_url as string
266 if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
267
268 const url = info.url as string
269 if (url?.match(/^https?:\/\//)) return url
270
271 // It seems youtube-dl does not return the video url
272 return 'https://www.youtube.com/watch?v=' + info.id
273 }
274
275 function normalizeTargetUrl (url: string) {
276 let normalizedUrl = url.replace(/\/+$/, '')
277
278 if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
279 normalizedUrl = 'https://' + normalizedUrl
280 }
281
282 return normalizedUrl
283 }
284
285 async 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
305 function parseDate (dateAsStr: string): Date {
306 if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
307 exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
308 }
309 const date = new Date(dateAsStr)
310 date.setHours(0, 0, 0)
311 if (isNaN(date.getTime())) {
312 exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
313 }
314 return date
315 }
316
317 function formatDate (date: Date): string {
318 return date.toISOString().split('T')[0]
319 }
320
321 function 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
329 function exitError (message: string, ...meta: any[]) {
330 // use console.error instead of log.error here
331 console.error(message, ...meta)
332 process.exit(-1)
333 }
334
335 function 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
341 })
342 }