]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/peertube-import-videos.ts
8c4c711f78daf0d4d34624c3ba25b8baf0f008a1
[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 { safeGetYoutubeDL, buildOriginallyPublishedAt } 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 (
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 }
49
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 }
61
62 if (!program['username']) program['username'] = netrc.machines[program['url']].login
63 if (!program['password']) program['password'] = netrc.machines[program['url']].password
64 }
65
66 if (
67 !program['targetUrl']
68 ) {
69 if (!program['targetUrl']) console.error('--targetUrl field is required.')
70 process.exit(-1)
71 }
72
73 removeEndSlashes(program['url'])
74 removeEndSlashes(program['targetUrl'])
75
76 const user = {
77 username: program['username'],
78 password: program['password']
79 }
80
81 run(user, program['url'])
82 .catch(err => {
83 console.error(err)
84 process.exit(-1)
85 })
86 })
87
88 async function promptPassword () {
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 })
105 })
106 }
107
108 async function run (user, url: string) {
109 if (!user.password) {
110 user.password = await promptPassword()
111 }
112
113 const res = await getClient(url)
114 client = {
115 id: res.body.client_id,
116 secret: res.body.client_secret
117 }
118
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 }
125
126 const youtubeDL = await safeGetYoutubeDL()
127
128 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
129 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
130 if (err) {
131 console.log(err.message)
132 process.exit(1)
133 }
134
135 let infoArray: any[]
136
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)
144
145 for (const info of infoArray) {
146 await processVideo(info, program['language'], processOptions.cwd, url, user)
147 }
148
149 console.log('Video/s for user %s imported: %s', program['username'], program['targetUrl'])
150 process.exit(0)
151 })
152 }
153
154 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
155 return new Promise(async res => {
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
161 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
162
163 console.log('############################################################\n')
164
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)
167 return res()
168 }
169
170 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
171
172 console.log('Downloading video "%s"...', videoInfo.title)
173
174 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
175 try {
176 const youtubeDL = await safeGetYoutubeDL()
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'))
184 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
185 return res()
186 })
187 } catch (err) {
188 console.log(err.message)
189 return res()
190 }
191 })
192 }
193
194 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
195 const category = await getCategory(videoInfo.categories, url)
196 const licence = getLicence(videoInfo.license)
197 let tags = []
198 if (Array.isArray(videoInfo.tags)) {
199 tags = videoInfo.tags
200 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
201 .map(t => t.normalize())
202 .slice(0, 5)
203 }
204
205 let thumbnailfile
206 if (videoInfo.thumbnail) {
207 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
208
209 await doRequestAndSaveToFile({
210 method: 'GET',
211 uri: videoInfo.thumbnail
212 }, thumbnailfile)
213 }
214
215 const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo)
216
217 const videoAttributes = {
218 name: truncate(videoInfo.title, {
219 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
220 'separator': /,? +/,
221 'omission': ' […]'
222 }),
223 category,
224 licence,
225 language,
226 nsfw: isNSFW(videoInfo),
227 waitTranscoding: true,
228 commentsEnabled: true,
229 downloadEnabled: true,
230 description: videoInfo.description || undefined,
231 support: undefined,
232 tags,
233 privacy: VideoPrivacy.PUBLIC,
234 fixture: videoPath,
235 thumbnailfile,
236 previewfile: thumbnailfile,
237 originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null
238 }
239
240 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
241 try {
242 await uploadVideo(url, accessToken, videoAttributes)
243 } catch (err) {
244 if (err.message.indexOf('401') !== -1) {
245 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
246
247 const res = await login(url, client, user)
248 accessToken = res.body.access_token
249
250 await uploadVideo(url, accessToken, videoAttributes)
251 } else {
252 console.log(err.message)
253 process.exit(1)
254 }
255 }
256
257 await remove(videoPath)
258 if (thumbnailfile) await remove(thumbnailfile)
259
260 console.log('Uploaded video "%s"!\n', videoAttributes.name)
261 }
262
263 async function getCategory (categories: string[], url: string) {
264 if (!categories) return undefined
265
266 const categoryString = categories[0]
267
268 if (categoryString === 'News & Politics') return 11
269
270 const res = await getVideoCategories(url)
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
281 /* ---------------------------------------------------------- */
282
283 function getLicence (licence: string) {
284 if (!licence) return undefined
285
286 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
287
288 return undefined
289 }
290
291 function 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 }
309
310 function fetchObject (info: any) {
311 const url = buildUrl(info)
312
313 return new Promise<any>(async (res, rej) => {
314 const youtubeDL = await safeGetYoutubeDL()
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
324 function buildUrl (info: any) {
325 const webpageUrl = info.webpage_url as string
326 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
327
328 const url = info.url as string
329 if (url && url.match(/^https?:\/\//)) return url
330
331 // It seems youtube-dl does not return the video url
332 return 'https://www.youtube.com/watch?v=' + info.id
333 }
334
335 function isNSFW (info: any) {
336 if (info.age_limit && info.age_limit >= 16) return true
337
338 return false
339 }
340
341 function removeEndSlashes (url: string) {
342 while (url.endsWith('/')) {
343 url.slice(0, -1)
344 }
345 }