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