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