]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/import-youtube.ts
Fix remote image fetching
[github/Chocobozzz/PeerTube.git] / server / tools / import-youtube.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('-y, --youtube-url <youtubeUrl>', 'Youtube URL')
15 .option('-l, --language <languageCode>', 'Language code')
16 .parse(process.argv)
17
18 if (
19 !program['url'] ||
20 !program['username'] ||
21 !program['password'] ||
22 !program['youtubeUrl']
23 ) {
24 console.error('All arguments are required.')
25 process.exit(-1)
26 }
27
28 run().catch(err => console.error(err))
29
30 let accessToken: string
31 const processOptions = {
32 cwd: __dirname,
33 maxBuffer: Infinity
34 }
35
36 async 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
51 const options = [ '-j', '--flat-playlist' ]
52 youtubeDL.getInfo(program['youtubeUrl'], options, processOptions, async (err, info) => {
53 if (err) throw err
54
55 // Normalize utf8 fields
56 info = info.map(i => normalizeObject(i))
57
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) {
65 await processVideo(video, program['language'])
66 }
67
68 console.log('I\'m finished!')
69 process.exit(0)
70 })
71 }
72
73 function processVideo (video: { name: string, url: string }, languageCode: number) {
74 return new Promise(async res => {
75 const result = await searchVideo(program['url'], video.name)
76
77 console.log('############################################################\n')
78
79 if (result.body.total !== 0) {
80 console.log('Video "%s" already exists, don\'t reupload it.\n', video.name)
81 return res()
82 }
83
84 const path = join(__dirname, new Date().getTime() + '.mp4')
85
86 console.log('Downloading video "%s"...', video.name)
87
88 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]', '-o', path ]
89 youtubeDL.exec(video.url, options, processOptions, async (err, output) => {
90 if (err) return console.error(err)
91
92 console.log(output.join('\n'))
93
94 youtubeDL.getInfo(video.url, undefined, processOptions, async (err, videoInfo) => {
95 if (err) return console.error(err)
96
97 await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
98
99 return res()
100 })
101 })
102 })
103 }
104
105 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: number) {
106 const category = await getCategory(videoInfo.categories)
107 const licence = getLicence(videoInfo.license)
108 let tags = []
109 if (Array.isArray(videoInfo.tags)) {
110 tags = videoInfo.tags
111 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max)
112 .map(t => t.normalize())
113 .slice(0, 5)
114 }
115
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
126 const videoAttributes = {
127 name: videoInfo.title,
128 category,
129 licence,
130 language,
131 nsfw: false,
132 commentsEnabled: true,
133 description: videoInfo.description,
134 tags,
135 privacy: VideoPrivacy.PUBLIC,
136 fixture: videoPath,
137 thumbnailfile,
138 previewfile: thumbnailfile
139 }
140
141 console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
142 await uploadVideo(program['url'], accessToken, videoAttributes)
143
144 await unlinkPromise(videoPath)
145 if (thumbnailfile) {
146 await unlinkPromise(thumbnailfile)
147 }
148
149 console.log('Uploaded video "%s"!\n', videoAttributes.name)
150 }
151
152 async 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
168 function getLicence (licence: string) {
169 if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
170
171 return undefined
172 }
173
174 function 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 }