]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/tools/peertube-import-videos.ts
WIP plugins: add plugin settings/uninstall in client
[github/Chocobozzz/PeerTube.git] / server / tools / peertube-import-videos.ts
CommitLineData
27d56b54
C
1// FIXME: https://github.com/nodejs/node/pull/16853
2require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
a7fea183 4import * as program from 'commander'
a7fea183 5import { join } from 'path'
1d791a26 6import { doRequestAndSaveToFile } from '../helpers/requests'
74dc3bca 7import { CONSTRAINTS_FIELDS } from '../initializers/constants'
94565d52 8import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/extra-utils/index'
45b8a42c 9import { truncate } from 'lodash'
066fc8ba 10import * as prompt from 'prompt'
62689b94 11import { remove } from 'fs-extra'
fa27f076 12import { sha256 } from '../helpers/core-utils'
e8a739e8 13import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl'
1205823f 14import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getNetrc, getRemoteObjectOrDie, getSettings } from './cli'
8704acf4 15
1a12f66d
C
16type UserInfo = {
17 username: string
18 password: string
19}
8704acf4
RK
20
21const processOptions = {
22 cwd: __dirname,
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')
61b3e146 35 .option('-t, --target-url <targetUrl>', 'Video target URL')
61b3e146 36 .option('-v, --verbose', 'Verbose mode')
a7fea183
C
37 .parse(process.argv)
38
2b4dd7e2
C
39Promise.all([ getSettings(), getNetrc() ])
40 .then(([ settings, netrc ]) => {
1a12f66d 41 const { url, username, password } = getRemoteObjectOrDie(program, settings, netrc)
e8a739e8 42
2b4dd7e2
C
43 if (!program[ 'targetUrl' ]) {
44 console.error('--targetUrl field is required.')
61b3e146 45
2b4dd7e2
C
46 process.exit(-1)
47 }
066fc8ba 48
2b4dd7e2
C
49 removeEndSlashes(url)
50 removeEndSlashes(program[ 'targetUrl' ])
ab4dbe36 51
1a12f66d 52 const user = { username, password }
8a2db2e8 53
1a12f66d 54 run(url, user)
2b4dd7e2
C
55 .catch(err => {
56 console.error(err)
57 process.exit(-1)
58 })
59 })
a7fea183 60
1a12f66d 61async function run (url: string, user: UserInfo) {
e2b9d0ca
JL
62 if (!user.password) {
63 user.password = await promptPassword()
066fc8ba 64 }
8a2db2e8 65
8704acf4
RK
66 const youtubeDL = await safeGetYoutubeDL()
67
5f26c735 68 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
2b4dd7e2 69 youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => {
f5b611f9 70 if (err) {
5c5638a0
O
71 console.log(err.message)
72 process.exit(1)
f5b611f9 73 }
a7fea183 74
61b3e146 75 let infoArray: any[]
a7fea183 76
61b3e146
C
77 // Normalize utf8 fields
78 if (Array.isArray(info) === true) {
79 infoArray = info.map(i => normalizeObject(i))
80 } else {
81 infoArray = [ normalizeObject(info) ]
82 }
83 console.log('Will download and upload %d videos.\n', infoArray.length)
a7fea183 84
61b3e146 85 for (const info of infoArray) {
1a12f66d
C
86 await processVideo({
87 cwd: processOptions.cwd,
88 url,
89 user,
90 youtubeInfo: info
91 })
a7fea183
C
92 }
93
2b4dd7e2 94 console.log('Video/s for user %s imported: %s', program[ 'username' ], program[ 'targetUrl' ])
a7fea183
C
95 process.exit(0)
96 })
97}
98
1a12f66d
C
99function processVideo (parameters: {
100 cwd: string,
101 url: string,
102 user: { username: string, password: string },
103 youtubeInfo: any
104}) {
105 const { youtubeInfo, cwd, url, user } = parameters
106
a7fea183 107 return new Promise(async res => {
1a12f66d 108 if (program[ 'verbose' ]) console.log('Fetching object.', youtubeInfo)
61b3e146 109
1a12f66d 110 const videoInfo = await fetchObject(youtubeInfo)
2b4dd7e2 111 if (program[ 'verbose' ]) console.log('Fetched object.', videoInfo)
61b3e146 112
8704acf4 113 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
e7872038
C
114
115 console.log('############################################################\n')
116
61b3e146
C
117 if (result.body.data.find(v => v.name === videoInfo.title)) {
118 console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
a7fea183
C
119 return res()
120 }
121
fa27f076 122 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
a7fea183 123
61b3e146 124 console.log('Downloading video "%s"...', videoInfo.title)
a7fea183 125
61b3e146 126 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
f97d2992 127 try {
8704acf4 128 const youtubeDL = await safeGetYoutubeDL()
f97d2992 129 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
130 if (err) {
131 console.error(err)
132 return res()
133 }
134
135 console.log(output.join('\n'))
1a12f66d
C
136 await uploadVideoOnPeerTube({
137 cwd,
138 url,
139 user,
140 videoInfo: normalizeObject(videoInfo),
141 videoPath: path
142 })
f97d2992 143 return res()
144 })
145 } catch (err) {
146 console.log(err.message)
61b3e146 147 return res()
f97d2992 148 }
a7fea183
C
149 })
150}
151
1a12f66d
C
152async function uploadVideoOnPeerTube (parameters: {
153 videoInfo: any,
154 videoPath: string,
155 cwd: string,
156 url: string,
157 user: { username: string; password: string }
158}) {
159 const { videoInfo, videoPath, cwd, url, user } = parameters
160
8704acf4 161 const category = await getCategory(videoInfo.categories, url)
a7fea183 162 const licence = getLicence(videoInfo.license)
34cbef8c
C
163 let tags = []
164 if (Array.isArray(videoInfo.tags)) {
02988fdc 165 tags = videoInfo.tags
2b4dd7e2
C
166 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
167 .map(t => t.normalize())
168 .slice(0, 5)
34cbef8c 169 }
a7fea183 170
1d791a26
C
171 let thumbnailfile
172 if (videoInfo.thumbnail) {
fa27f076 173 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
1d791a26
C
174
175 await doRequestAndSaveToFile({
176 method: 'GET',
177 uri: videoInfo.thumbnail
178 }, thumbnailfile)
179 }
180
c74c9be9 181 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
84929846 182
1205823f 183 const defaultAttributes = {
45b8a42c
RK
184 name: truncate(videoInfo.title, {
185 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
186 'separator': /,? +/,
187 'omission': ' […]'
188 }),
a7fea183
C
189 category,
190 licence,
a41e183c 191 nsfw: isNSFW(videoInfo),
1205823f
C
192 description: videoInfo.description,
193 tags
a7fea183
C
194 }
195
1205823f
C
196 const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
197
198 Object.assign(videoAttributes, {
199 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null,
200 thumbnailfile,
201 previewfile: thumbnailfile,
202 fixture: videoPath
203 })
1a12f66d 204
a7fea183 205 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
1a12f66d
C
206
207 let accessToken = await getAccessTokenOrDie(url, user)
208
71578f31 209 try {
8704acf4 210 await uploadVideo(url, accessToken, videoAttributes)
61b3e146 211 } catch (err) {
b6fe1f98 212 if (err.message.indexOf('401') !== -1) {
61b3e146
C
213 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
214
1a12f66d 215 accessToken = await getAccessTokenOrDie(url, user)
61b3e146 216
8704acf4 217 await uploadVideo(url, accessToken, videoAttributes)
61b3e146 218 } else {
5c5638a0
O
219 console.log(err.message)
220 process.exit(1)
71578f31
L
221 }
222 }
1d791a26 223
62689b94
C
224 await remove(videoPath)
225 if (thumbnailfile) await remove(thumbnailfile)
1d791a26 226
a7fea183
C
227 console.log('Uploaded video "%s"!\n', videoAttributes.name)
228}
229
1a12f66d
C
230/* ---------------------------------------------------------- */
231
8704acf4 232async function getCategory (categories: string[], url: string) {
61b3e146
C
233 if (!categories) return undefined
234
2b4dd7e2 235 const categoryString = categories[ 0 ]
a7fea183
C
236
237 if (categoryString === 'News & Politics') return 11
238
8704acf4 239 const res = await getVideoCategories(url)
a7fea183
C
240 const categoriesServer = res.body
241
242 for (const key of Object.keys(categoriesServer)) {
2b4dd7e2 243 const categoryServer = categoriesServer[ key ]
a7fea183
C
244 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
245 }
246
247 return undefined
248}
249
250function getLicence (licence: string) {
61b3e146
C
251 if (!licence) return undefined
252
a7fea183
C
253 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
254
255 return undefined
256}
e7872038
C
257
258function normalizeObject (obj: any) {
259 const newObj: any = {}
260
261 for (const key of Object.keys(obj)) {
262 // Deprecated key
263 if (key === 'resolution') continue
264
2b4dd7e2 265 const value = obj[ key ]
e7872038
C
266
267 if (typeof value === 'string') {
2b4dd7e2 268 newObj[ key ] = value.normalize()
e7872038 269 } else {
2b4dd7e2 270 newObj[ key ] = value
e7872038
C
271 }
272 }
273
274 return newObj
275}
61b3e146
C
276
277function fetchObject (info: any) {
278 const url = buildUrl(info)
279
280 return new Promise<any>(async (res, rej) => {
8704acf4 281 const youtubeDL = await safeGetYoutubeDL()
61b3e146
C
282 youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
283 if (err) return rej(err)
284
285 const videoInfoWithUrl = Object.assign(videoInfo, { url })
286 return res(normalizeObject(videoInfoWithUrl))
287 })
288 })
289}
290
291function buildUrl (info: any) {
a41e183c
C
292 const webpageUrl = info.webpage_url as string
293 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
294
61b3e146 295 const url = info.url as string
a41e183c 296 if (url && url.match(/^https?:\/\//)) return url
61b3e146
C
297
298 // It seems youtube-dl does not return the video url
299 return 'https://www.youtube.com/watch?v=' + info.id
300}
a41e183c
C
301
302function isNSFW (info: any) {
1a12f66d 303 return info.age_limit && info.age_limit >= 16
a41e183c 304}
ab4dbe36
H
305
306function removeEndSlashes (url: string) {
307 while (url.endsWith('/')) {
308 url.slice(0, -1)
309 }
310}
1a12f66d
C
311
312async function promptPassword () {
313 return new Promise<string>((res, rej) => {
314 prompt.start()
315 const schema = {
316 properties: {
317 password: {
318 hidden: true,
319 required: true
320 }
321 }
322 }
323 prompt.get(schema, function (err, result) {
324 if (err) {
325 return rej(err)
326 }
327 return res(result.password)
328 })
329 })
330}
331
332async function getAccessTokenOrDie (url: string, user: UserInfo) {
333 const resClient = await getClient(url)
334 const client = {
335 id: resClient.body.client_id,
336 secret: resClient.body.client_secret
337 }
338
339 try {
340 const res = await login(url, client, user)
341 return res.body.access_token
342 } catch (err) {
343 console.error('Cannot authenticate. Please check your username/password.')
344 process.exit(-1)
345 }
346}