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