]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/tools/import-youtube.ts
Fix remote image fetching
[github/Chocobozzz/PeerTube.git] / server / tools / import-youtube.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')
e7872038 14 .option('-y, --youtube-url <youtubeUrl>', 'Youtube URL')
34cbef8c 15 .option('-l, --language <languageCode>', 'Language code')
a7fea183
C
16 .parse(process.argv)
17
18if (
19 !program['url'] ||
20 !program['username'] ||
21 !program['password'] ||
22 !program['youtubeUrl']
23) {
a87d467a
C
24 console.error('All arguments are required.')
25 process.exit(-1)
a7fea183
C
26}
27
28run().catch(err => console.error(err))
29
30let accessToken: string
34cbef8c
C
31const processOptions = {
32 cwd: __dirname,
33 maxBuffer: Infinity
34}
a7fea183
C
35
36async function run () {
37 const res = await getClient(program['url'])
38 const client = {
39 id: res.body.client_id,
40 secret: res.body.client_secret
41 }
42
43 const user = {
44 username: program['username'],
45 password: program['password']
46 }
47
48 const res2 = await login(program['url'], client, user)
49 accessToken = res2.body.access_token
50
34cbef8c
C
51 const options = [ '-j', '--flat-playlist' ]
52 youtubeDL.getInfo(program['youtubeUrl'], options, processOptions, async (err, info) => {
a7fea183
C
53 if (err) throw err
54
e7872038
C
55 // Normalize utf8 fields
56 info = info.map(i => normalizeObject(i))
57
a7fea183
C
58 const videos = info.map(i => {
59 return { url: 'https://www.youtube.com/watch?v=' + i.id, name: i.title }
60 })
61
62 console.log('Will download and upload %d videos.\n', videos.length)
63
64 for (const video of videos) {
02988fdc 65 await processVideo(video, program['language'])
a7fea183
C
66 }
67
68 console.log('I\'m finished!')
69 process.exit(0)
70 })
71}
72
34cbef8c 73function processVideo (video: { name: string, url: string }, languageCode: number) {
a7fea183 74 return new Promise(async res => {
e7872038
C
75 const result = await searchVideo(program['url'], video.name)
76
77 console.log('############################################################\n')
78
a7fea183 79 if (result.body.total !== 0) {
e7872038 80 console.log('Video "%s" already exists, don\'t reupload it.\n', video.name)
a7fea183
C
81 return res()
82 }
83
e7872038 84 const path = join(__dirname, new Date().getTime() + '.mp4')
a7fea183 85
e7872038 86 console.log('Downloading video "%s"...', video.name)
a7fea183 87
34cbef8c
C
88 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]', '-o', path ]
89 youtubeDL.exec(video.url, options, processOptions, async (err, output) => {
e7872038 90 if (err) return console.error(err)
a7fea183 91
e7872038 92 console.log(output.join('\n'))
a7fea183 93
34cbef8c 94 youtubeDL.getInfo(video.url, undefined, processOptions, async (err, videoInfo) => {
e7872038 95 if (err) return console.error(err)
a7fea183 96
34cbef8c 97 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
a7fea183 98
e7872038
C
99 return res()
100 })
a7fea183
C
101 })
102 })
103}
104
34cbef8c 105async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: number) {
a7fea183
C
106 const category = await getCategory(videoInfo.categories)
107 const licence = getLicence(videoInfo.license)
34cbef8c
C
108 let tags = []
109 if (Array.isArray(videoInfo.tags)) {
02988fdc
C
110 tags = videoInfo.tags
111 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max)
112 .map(t => t.normalize())
113 .slice(0, 5)
34cbef8c 114 }
a7fea183 115
1d791a26
C
116 let thumbnailfile
117 if (videoInfo.thumbnail) {
118 thumbnailfile = join(__dirname, 'thumbnail.jpg')
119
120 await doRequestAndSaveToFile({
121 method: 'GET',
122 uri: videoInfo.thumbnail
123 }, thumbnailfile)
124 }
125
a7fea183
C
126 const videoAttributes = {
127 name: videoInfo.title,
128 category,
129 licence,
130 language,
131 nsfw: false,
132 commentsEnabled: true,
133 description: videoInfo.description,
34cbef8c 134 tags,
a7fea183 135 privacy: VideoPrivacy.PUBLIC,
1d791a26 136 fixture: videoPath,
8cac1b64
C
137 thumbnailfile,
138 previewfile: thumbnailfile
a7fea183
C
139 }
140
141 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
142 await uploadVideo(program['url'], accessToken, videoAttributes)
1d791a26 143
a7fea183 144 await unlinkPromise(videoPath)
1d791a26
C
145 if (thumbnailfile) {
146 await unlinkPromise(thumbnailfile)
147 }
148
a7fea183
C
149 console.log('Uploaded video "%s"!\n', videoAttributes.name)
150}
151
152async function getCategory (categories: string[]) {
153 const categoryString = categories[0]
154
155 if (categoryString === 'News & Politics') return 11
156
157 const res = await getVideoCategories(program['url'])
158 const categoriesServer = res.body
159
160 for (const key of Object.keys(categoriesServer)) {
161 const categoryServer = categoriesServer[key]
162 if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
163 }
164
165 return undefined
166}
167
168function getLicence (licence: string) {
169 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
170
171 return undefined
172}
e7872038
C
173
174function normalizeObject (obj: any) {
175 const newObj: any = {}
176
177 for (const key of Object.keys(obj)) {
178 // Deprecated key
179 if (key === 'resolution') continue
180
181 const value = obj[key]
182
183 if (typeof value === 'string') {
184 newObj[key] = value.normalize()
185 } else {
186 newObj[key] = value
187 }
188 }
189
190 return newObj
191}