]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/import-videos.ts
433cee6525e06971ba19a64d28def7afd2cff1f2
[github/Chocobozzz/PeerTube.git] / server / tools / import-videos.ts
1 import * as program from 'commander'
2 import { join } from 'path'
3 import * as youtubeDL from 'youtube-dl'
4 import { VideoPrivacy } from '../../shared/models/videos'
5 import { unlinkPromise } from '../helpers/core-utils'
6 import { doRequestAndSaveToFile } from '../helpers/requests'
7 import { CONSTRAINTS_FIELDS } from '../initializers'
8 import { getClient, getVideoCategories, login, searchVideo, uploadVideo } from '../tests/utils'
9
10 program
11 .option('-u, --url <url>', 'Server url')
12 .option('-U, --username <username>', 'Username')
13 .option('-p, --password <token>', 'Password')
14 .option('-t, --target-url <targetUrl>', 'Video target URL')
15 .option('-l, --language <languageCode>', 'Language code')
16 .option('-v, --verbose', 'Verbose mode')
17 .parse(process.argv)
18
19 if (
20 !program['url'] ||
21 !program['username'] ||
22 !program['password'] ||
23 !program['targetUrl']
24 ) {
25 console.error('All arguments are required.')
26 process.exit(-1)
27 }
28
29 run().catch(err => console.error(err))
30
31 let accessToken: string
32 let client: { id: string, secret: string }
33
34 const user = {
35 username: program['username'],
36 password: program['password']
37 }
38
39 const processOptions = {
40 cwd: __dirname,
41 maxBuffer: Infinity
42 }
43
44 async function run () {
45 const res = await getClient(program['url'])
46 client = {
47 id: res.body.client_id,
48 secret: res.body.client_secret
49 }
50
51 const res2 = await login(program['url'], client, user)
52 accessToken = res2.body.access_token
53
54 const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
55 youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
56 if (err) throw err
57
58 let infoArray: any[]
59
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)
67
68 for (const info of infoArray) {
69 await processVideo(info, program['language'])
70 }
71
72 // https://www.youtube.com/watch?v=2Upx39TBc1s
73 console.log('I\'m finished!')
74 process.exit(0)
75 })
76 }
77
78 function processVideo (info: any, languageCode: number) {
79 return new Promise(async res => {
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)
86
87 console.log('############################################################\n')
88
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)
91 return res()
92 }
93
94 const path = join(__dirname, new Date().getTime() + '.mp4')
95
96 console.log('Downloading video "%s"...', videoInfo.title)
97
98 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
99 youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
100 if (err) return console.error(err)
101
102 console.log(output.join('\n'))
103
104 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
105
106 return res()
107 })
108 })
109 }
110
111 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: number) {
112 const category = await getCategory(videoInfo.categories)
113 const licence = getLicence(videoInfo.license)
114 let tags = []
115 if (Array.isArray(videoInfo.tags)) {
116 tags = videoInfo.tags
117 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
118 .map(t => t.normalize())
119 .slice(0, 5)
120 }
121
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
132 const videoAttributes = {
133 name: videoInfo.title,
134 category,
135 licence,
136 language,
137 nsfw: isNSFW(videoInfo),
138 commentsEnabled: true,
139 description: videoInfo.description,
140 support: undefined,
141 tags,
142 privacy: VideoPrivacy.PUBLIC,
143 fixture: videoPath,
144 thumbnailfile,
145 previewfile: thumbnailfile
146 }
147
148 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
149 try {
150 await uploadVideo(program['url'], accessToken, videoAttributes)
151 } catch (err) {
152 if (err.message.indexOf('401') !== -1) {
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
158 await uploadVideo(program['url'], accessToken, videoAttributes)
159 } else {
160 throw err
161 }
162 }
163
164 await unlinkPromise(videoPath)
165 if (thumbnailfile) {
166 await unlinkPromise(thumbnailfile)
167 }
168
169 console.log('Uploaded video "%s"!\n', videoAttributes.name)
170 }
171
172 async function getCategory (categories: string[]) {
173 if (!categories) return undefined
174
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
190 function getLicence (licence: string) {
191 if (!licence) return undefined
192
193 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
194
195 return undefined
196 }
197
198 function 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 }
216
217 function 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
230 function buildUrl (info: any) {
231 const webpageUrl = info.webpage_url as string
232 if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
233
234 const url = info.url as string
235 if (url && url.match(/^https?:\/\//)) return url
236
237 // It seems youtube-dl does not return the video url
238 return 'https://www.youtube.com/watch?v=' + info.id
239 }
240
241 function isNSFW (info: any) {
242 if (info.age_limit && info.age_limit >= 16) return true
243
244 return false
245 }