]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/peertube-import-videos.ts
Enable video watch
[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'
9 import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../../shared/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 } 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']).catch(err => console.error(err))
82 })
83
84 async function promptPassword () {
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 })
101 })
102 }
103
104 async function run (user, url: string) {
105 if (!user.password) {
106 user.password = await promptPassword()
107 }
108
109 const res = await getClient(url)
110 client = {
111 id: res.body.client_id,
112 secret: res.body.client_secret
113 }
114
115 const res2 = await login(url, client, user)
116 accessToken = res2.body.access_token
117
118 const youtubeDL = await safeGetYoutubeDL()
119
120 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
121 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
122 if (err) {
123 console.log(err.message)
124 process.exit(1)
125 }
126
127 let infoArray: any[]
128
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)
136
137 for (const info of infoArray) {
138 await processVideo(info, program['language'], processOptions.cwd, url, user)
139 }
140
141 console.log('Video/s for user %s imported: %s', program['username'], program['targetUrl'])
142 process.exit(0)
143 })
144 }
145
146 function processVideo (info: any, languageCode: string, cwd: string, url: string, user) {
147 return new Promise(async res => {
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
153 const result = await searchVideoWithSort(url, videoInfo.title, '-match')
154
155 console.log('############################################################\n')
156
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)
159 return res()
160 }
161
162 const path = join(cwd, sha256(videoInfo.url) + '.mp4')
163
164 console.log('Downloading video "%s"...', videoInfo.title)
165
166 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
167 try {
168 const youtubeDL = await safeGetYoutubeDL()
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'))
176 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, cwd, url, user, languageCode)
177 return res()
178 })
179 } catch (err) {
180 console.log(err.message)
181 return res()
182 }
183 })
184 }
185
186 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, cwd: string, url: string, user, language?: string) {
187 const category = await getCategory(videoInfo.categories, url)
188 const licence = getLicence(videoInfo.license)
189 let tags = []
190 if (Array.isArray(videoInfo.tags)) {
191 tags = videoInfo.tags
192 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
193 .map(t => t.normalize())
194 .slice(0, 5)
195 }
196
197 let thumbnailfile
198 if (videoInfo.thumbnail) {
199 thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg')
200
201 await doRequestAndSaveToFile({
202 method: 'GET',
203 uri: videoInfo.thumbnail
204 }, thumbnailfile)
205 }
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 description: videoInfo.description || undefined,
220 support: undefined,
221 tags,
222 privacy: VideoPrivacy.PUBLIC,
223 fixture: videoPath,
224 thumbnailfile,
225 previewfile: thumbnailfile
226 }
227
228 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
229 try {
230 await uploadVideo(url, accessToken, videoAttributes)
231 } catch (err) {
232 if (err.message.indexOf('401') !== -1) {
233 console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
234
235 const res = await login(url, client, user)
236 accessToken = res.body.access_token
237
238 await uploadVideo(url, accessToken, videoAttributes)
239 } else {
240 console.log(err.message)
241 process.exit(1)
242 }
243 }
244
245 await remove(videoPath)
246 if (thumbnailfile) await remove(thumbnailfile)
247
248 console.log('Uploaded video "%s"!\n', videoAttributes.name)
249 }
250
251 async function getCategory (categories: string[], url: string) {
252 if (!categories) return undefined
253
254 const categoryString = categories[0]
255
256 if (categoryString === 'News & Politics') return 11
257
258 const res = await getVideoCategories(url)
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
269 /* ---------------------------------------------------------- */
270
271 function getLicence (licence: string) {
272 if (!licence) return undefined
273
274 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
275
276 return undefined
277 }
278
279 function 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 }
297
298 function fetchObject (info: any) {
299 const url = buildUrl(info)
300
301 return new Promise<any>(async (res, rej) => {
302 const youtubeDL = await safeGetYoutubeDL()
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
312 function buildUrl (info: any) {
313 const webpageUrl = info.webpage_url as string
314 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
315
316 const url = info.url as string
317 if (url && url.match(/^https?:\/\//)) return url
318
319 // It seems youtube-dl does not return the video url
320 return 'https://www.youtube.com/watch?v=' + info.id
321 }
322
323 function isNSFW (info: any) {
324 if (info.age_limit && info.age_limit >= 16) return true
325
326 return false
327 }
328
329 function removeEndSlashes (url: string) {
330 while (url.endsWith('/')) {
331 url.slice(0, -1)
332 }
333 }