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