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