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