diff options
Diffstat (limited to 'server/tools/import-videos.ts')
-rw-r--r-- | server/tools/import-videos.ts | 235 |
1 files changed, 235 insertions, 0 deletions
diff --git a/server/tools/import-videos.ts b/server/tools/import-videos.ts new file mode 100644 index 000000000..268101b41 --- /dev/null +++ b/server/tools/import-videos.ts | |||
@@ -0,0 +1,235 @@ | |||
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('-t, --target-url <targetUrl>', 'Video target URL') | ||
15 | .option('-l, --language <languageCode>', 'Language code') | ||
16 | .option('-v, --verbose', 'Verbose mode') | ||
17 | .parse(process.argv) | ||
18 | |||
19 | if ( | ||
20 | !program['url'] || | ||
21 | !program['username'] || | ||
22 | !program['password'] || | ||
23 | !program['targetUrl'] | ||
24 | ) { | ||
25 | console.error('All arguments are required.') | ||
26 | process.exit(-1) | ||
27 | } | ||
28 | |||
29 | run().catch(err => console.error(err)) | ||
30 | |||
31 | let accessToken: string | ||
32 | let client: { id: string, secret: string } | ||
33 | |||
34 | const user = { | ||
35 | username: program['username'], | ||
36 | password: program['password'] | ||
37 | } | ||
38 | |||
39 | const processOptions = { | ||
40 | cwd: __dirname, | ||
41 | maxBuffer: Infinity | ||
42 | } | ||
43 | |||
44 | async function run () { | ||
45 | const res = await getClient(program['url']) | ||
46 | client = { | ||
47 | id: res.body.client_id, | ||
48 | secret: res.body.client_secret | ||
49 | } | ||
50 | |||
51 | const res2 = await login(program['url'], client, user) | ||
52 | accessToken = res2.body.access_token | ||
53 | |||
54 | const options = [ '-j', '--flat-playlist', '--playlist-reverse' ] | ||
55 | youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => { | ||
56 | if (err) throw err | ||
57 | |||
58 | let infoArray: any[] | ||
59 | |||
60 | // Normalize utf8 fields | ||
61 | if (Array.isArray(info) === true) { | ||
62 | infoArray = info.map(i => normalizeObject(i)) | ||
63 | } else { | ||
64 | infoArray = [ normalizeObject(info) ] | ||
65 | } | ||
66 | console.log('Will download and upload %d videos.\n', infoArray.length) | ||
67 | |||
68 | for (const info of infoArray) { | ||
69 | await processVideo(info, program['language']) | ||
70 | } | ||
71 | |||
72 | // https://www.youtube.com/watch?v=2Upx39TBc1s | ||
73 | console.log('I\'m finished!') | ||
74 | process.exit(0) | ||
75 | }) | ||
76 | } | ||
77 | |||
78 | function processVideo (info: any, languageCode: number) { | ||
79 | return new Promise(async res => { | ||
80 | if (program['verbose']) console.log('Fetching object.', info) | ||
81 | |||
82 | const videoInfo = await fetchObject(info) | ||
83 | if (program['verbose']) console.log('Fetched object.', videoInfo) | ||
84 | |||
85 | const result = await searchVideo(program['url'], videoInfo.title) | ||
86 | |||
87 | console.log('############################################################\n') | ||
88 | |||
89 | if (result.body.data.find(v => v.name === videoInfo.title)) { | ||
90 | console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title) | ||
91 | return res() | ||
92 | } | ||
93 | |||
94 | const path = join(__dirname, new Date().getTime() + '.mp4') | ||
95 | |||
96 | console.log('Downloading video "%s"...', videoInfo.title) | ||
97 | |||
98 | const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ] | ||
99 | youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => { | ||
100 | if (err) return console.error(err) | ||
101 | |||
102 | console.log(output.join('\n')) | ||
103 | |||
104 | await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode) | ||
105 | |||
106 | return res() | ||
107 | }) | ||
108 | }) | ||
109 | } | ||
110 | |||
111 | async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: number) { | ||
112 | const category = await getCategory(videoInfo.categories) | ||
113 | const licence = getLicence(videoInfo.license) | ||
114 | let tags = [] | ||
115 | if (Array.isArray(videoInfo.tags)) { | ||
116 | tags = videoInfo.tags | ||
117 | .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max) | ||
118 | .map(t => t.normalize()) | ||
119 | .slice(0, 5) | ||
120 | } | ||
121 | |||
122 | let thumbnailfile | ||
123 | if (videoInfo.thumbnail) { | ||
124 | thumbnailfile = join(__dirname, 'thumbnail.jpg') | ||
125 | |||
126 | await doRequestAndSaveToFile({ | ||
127 | method: 'GET', | ||
128 | uri: videoInfo.thumbnail | ||
129 | }, thumbnailfile) | ||
130 | } | ||
131 | |||
132 | const videoAttributes = { | ||
133 | name: videoInfo.title, | ||
134 | category, | ||
135 | licence, | ||
136 | language, | ||
137 | nsfw: false, | ||
138 | commentsEnabled: true, | ||
139 | description: videoInfo.description, | ||
140 | tags, | ||
141 | privacy: VideoPrivacy.PUBLIC, | ||
142 | fixture: videoPath, | ||
143 | thumbnailfile, | ||
144 | previewfile: thumbnailfile | ||
145 | } | ||
146 | |||
147 | console.log('\nUploading on PeerTube video "%s".', videoAttributes.name) | ||
148 | try { | ||
149 | await uploadVideo(program['url'], accessToken, videoAttributes) | ||
150 | } catch (err) { | ||
151 | if (err.message.indexOf('401')) { | ||
152 | console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.') | ||
153 | |||
154 | const res = await login(program['url'], client, user) | ||
155 | accessToken = res.body.access_token | ||
156 | |||
157 | await uploadVideo(program['url'], accessToken, videoAttributes) | ||
158 | } else { | ||
159 | throw err | ||
160 | } | ||
161 | } | ||
162 | |||
163 | await unlinkPromise(videoPath) | ||
164 | if (thumbnailfile) { | ||
165 | await unlinkPromise(thumbnailfile) | ||
166 | } | ||
167 | |||
168 | console.log('Uploaded video "%s"!\n', videoAttributes.name) | ||
169 | } | ||
170 | |||
171 | async function getCategory (categories: string[]) { | ||
172 | if (!categories) return undefined | ||
173 | |||
174 | const categoryString = categories[0] | ||
175 | |||
176 | if (categoryString === 'News & Politics') return 11 | ||
177 | |||
178 | const res = await getVideoCategories(program['url']) | ||
179 | const categoriesServer = res.body | ||
180 | |||
181 | for (const key of Object.keys(categoriesServer)) { | ||
182 | const categoryServer = categoriesServer[key] | ||
183 | if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10) | ||
184 | } | ||
185 | |||
186 | return undefined | ||
187 | } | ||
188 | |||
189 | function getLicence (licence: string) { | ||
190 | if (!licence) return undefined | ||
191 | |||
192 | if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1 | ||
193 | |||
194 | return undefined | ||
195 | } | ||
196 | |||
197 | function normalizeObject (obj: any) { | ||
198 | const newObj: any = {} | ||
199 | |||
200 | for (const key of Object.keys(obj)) { | ||
201 | // Deprecated key | ||
202 | if (key === 'resolution') continue | ||
203 | |||
204 | const value = obj[key] | ||
205 | |||
206 | if (typeof value === 'string') { | ||
207 | newObj[key] = value.normalize() | ||
208 | } else { | ||
209 | newObj[key] = value | ||
210 | } | ||
211 | } | ||
212 | |||
213 | return newObj | ||
214 | } | ||
215 | |||
216 | function fetchObject (info: any) { | ||
217 | const url = buildUrl(info) | ||
218 | |||
219 | return new Promise<any>(async (res, rej) => { | ||
220 | youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => { | ||
221 | if (err) return rej(err) | ||
222 | |||
223 | const videoInfoWithUrl = Object.assign(videoInfo, { url }) | ||
224 | return res(normalizeObject(videoInfoWithUrl)) | ||
225 | }) | ||
226 | }) | ||
227 | } | ||
228 | |||
229 | function buildUrl (info: any) { | ||
230 | const url = info.url as string | ||
231 | if (url && url.match(/^https?:\/\//)) return info.url | ||
232 | |||
233 | // It seems youtube-dl does not return the video url | ||
234 | return 'https://www.youtube.com/watch?v=' + info.id | ||
235 | } | ||