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