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