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