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