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