diff options
author | Rigel Kent <sendmemail@rigelk.eu> | 2018-09-13 14:27:44 +0200 |
---|---|---|
committer | Rigel Kent <sendmemail@rigelk.eu> | 2018-09-14 11:08:55 +0200 |
commit | 8704acf49efc770d73bf07c10468ed8c74d28a83 (patch) | |
tree | ffd46289fcf9a13ac4412b167e9f71dfb35753c5 /server/tools/import-videos.ts | |
parent | 1d9d9cfdcf3983e3fd89026bc4b5633a8abf5752 (diff) | |
download | PeerTube-8704acf49efc770d73bf07c10468ed8c74d28a83.tar.gz PeerTube-8704acf49efc770d73bf07c10468ed8c74d28a83.tar.zst PeerTube-8704acf49efc770d73bf07c10468ed8c74d28a83.zip |
one cli to unite them all
Ash nazg thrakatulûk agh burzum-ishi krimpatul
- refactor import-videos to use the youtubeDL helper
- add very basic tests for the cli
Diffstat (limited to 'server/tools/import-videos.ts')
-rw-r--r-- | server/tools/import-videos.ts | 286 |
1 files changed, 0 insertions, 286 deletions
diff --git a/server/tools/import-videos.ts b/server/tools/import-videos.ts deleted file mode 100644 index 3ff194c83..000000000 --- a/server/tools/import-videos.ts +++ /dev/null | |||
@@ -1,286 +0,0 @@ | |||
1 | // FIXME: https://github.com/nodejs/node/pull/16853 | ||
2 | require('tls').DEFAULT_ECDH_CURVE = 'auto' | ||
3 | |||
4 | import * as program from 'commander' | ||
5 | import { join } from 'path' | ||
6 | import * as youtubeDL from 'youtube-dl' | ||
7 | import { VideoPrivacy } from '../../shared/models/videos' | ||
8 | import { doRequestAndSaveToFile } from '../helpers/requests' | ||
9 | import { CONSTRAINTS_FIELDS } from '../initializers' | ||
10 | import { getClient, getVideoCategories, login, searchVideoWithSort, uploadVideo } from '../tests/utils' | ||
11 | import { truncate } from 'lodash' | ||
12 | import * as prompt from 'prompt' | ||
13 | import { remove } from 'fs-extra' | ||
14 | |||
15 | program | ||
16 | .option('-u, --url <url>', 'Server url') | ||
17 | .option('-U, --username <username>', 'Username') | ||
18 | .option('-p, --password <token>', 'Password') | ||
19 | .option('-t, --target-url <targetUrl>', 'Video target URL') | ||
20 | .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)') | ||
21 | .option('-v, --verbose', 'Verbose mode') | ||
22 | .parse(process.argv) | ||
23 | |||
24 | if ( | ||
25 | !program['url'] || | ||
26 | !program['username'] || | ||
27 | !program['targetUrl'] | ||
28 | ) { | ||
29 | console.error('All arguments are required.') | ||
30 | process.exit(-1) | ||
31 | } | ||
32 | |||
33 | const user = { | ||
34 | username: program['username'], | ||
35 | password: program['password'] | ||
36 | } | ||
37 | |||
38 | run().catch(err => console.error(err)) | ||
39 | |||
40 | let accessToken: string | ||
41 | let client: { id: string, secret: string } | ||
42 | |||
43 | const processOptions = { | ||
44 | cwd: __dirname, | ||
45 | maxBuffer: Infinity | ||
46 | } | ||
47 | |||
48 | async function promptPassword () { | ||
49 | return new Promise((res, rej) => { | ||
50 | prompt.start() | ||
51 | const schema = { | ||
52 | properties: { | ||
53 | password: { | ||
54 | hidden: true, | ||
55 | required: true | ||
56 | } | ||
57 | } | ||
58 | } | ||
59 | prompt.get(schema, function (err, result) { | ||
60 | if (err) { | ||
61 | return rej(err) | ||
62 | } | ||
63 | return res(result.password) | ||
64 | }) | ||
65 | }) | ||
66 | } | ||
67 | |||
68 | async function run () { | ||
69 | if (!user.password) { | ||
70 | user.password = await promptPassword() | ||
71 | } | ||
72 | |||
73 | const res = await getClient(program['url']) | ||
74 | client = { | ||
75 | id: res.body.client_id, | ||
76 | secret: res.body.client_secret | ||
77 | } | ||
78 | |||
79 | const res2 = await login(program['url'], client, user) | ||
80 | accessToken = res2.body.access_token | ||
81 | |||
82 | const options = [ '-j', '--flat-playlist', '--playlist-reverse' ] | ||
83 | youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => { | ||
84 | if (err) { | ||
85 | console.log(err.message) | ||
86 | process.exit(1) | ||
87 | } | ||
88 | |||
89 | let infoArray: any[] | ||
90 | |||
91 | // Normalize utf8 fields | ||
92 | if (Array.isArray(info) === true) { | ||
93 | infoArray = info.map(i => normalizeObject(i)) | ||
94 | } else { | ||
95 | infoArray = [ normalizeObject(info) ] | ||
96 | } | ||
97 | console.log('Will download and upload %d videos.\n', infoArray.length) | ||
98 | |||
99 | for (const info of infoArray) { | ||
100 | await processVideo(info, program['language']) | ||
101 | } | ||
102 | |||
103 | // https://www.youtube.com/watch?v=2Upx39TBc1s | ||
104 | console.log('I\'m finished!') | ||
105 | process.exit(0) | ||
106 | }) | ||
107 | } | ||
108 | |||
109 | function processVideo (info: any, languageCode: string) { | ||
110 | return new Promise(async res => { | ||
111 | if (program['verbose']) console.log('Fetching object.', info) | ||
112 | |||
113 | const videoInfo = await fetchObject(info) | ||
114 | if (program['verbose']) console.log('Fetched object.', videoInfo) | ||
115 | |||
116 | const result = await searchVideoWithSort(program['url'], videoInfo.title, '-match') | ||
117 | |||
118 | console.log('############################################################\n') | ||
119 | |||
120 | if (result.body.data.find(v => v.name === videoInfo.title)) { | ||
121 | console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title) | ||
122 | return res() | ||
123 | } | ||
124 | |||
125 | const path = join(__dirname, new Date().getTime() + '.mp4') | ||
126 | |||
127 | console.log('Downloading video "%s"...', videoInfo.title) | ||
128 | |||
129 | const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ] | ||
130 | try { | ||
131 | youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => { | ||
132 | if (err) { | ||
133 | console.error(err) | ||
134 | return res() | ||
135 | } | ||
136 | |||
137 | console.log(output.join('\n')) | ||
138 | await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode) | ||
139 | return res() | ||
140 | }) | ||
141 | } catch (err) { | ||
142 | console.log(err.message) | ||
143 | return res() | ||
144 | } | ||
145 | }) | ||
146 | } | ||
147 | |||
148 | async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: string) { | ||
149 | const category = await getCategory(videoInfo.categories) | ||
150 | const licence = getLicence(videoInfo.license) | ||
151 | let tags = [] | ||
152 | if (Array.isArray(videoInfo.tags)) { | ||
153 | tags = videoInfo.tags | ||
154 | .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min) | ||
155 | .map(t => t.normalize()) | ||
156 | .slice(0, 5) | ||
157 | } | ||
158 | |||
159 | let thumbnailfile | ||
160 | if (videoInfo.thumbnail) { | ||
161 | thumbnailfile = join(__dirname, 'thumbnail.jpg') | ||
162 | |||
163 | await doRequestAndSaveToFile({ | ||
164 | method: 'GET', | ||
165 | uri: videoInfo.thumbnail | ||
166 | }, thumbnailfile) | ||
167 | } | ||
168 | |||
169 | const videoAttributes = { | ||
170 | name: truncate(videoInfo.title, { | ||
171 | 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max, | ||
172 | 'separator': /,? +/, | ||
173 | 'omission': ' […]' | ||
174 | }), | ||
175 | category, | ||
176 | licence, | ||
177 | language, | ||
178 | nsfw: isNSFW(videoInfo), | ||
179 | waitTranscoding: true, | ||
180 | commentsEnabled: true, | ||
181 | description: videoInfo.description || undefined, | ||
182 | support: undefined, | ||
183 | tags, | ||
184 | privacy: VideoPrivacy.PUBLIC, | ||
185 | fixture: videoPath, | ||
186 | thumbnailfile, | ||
187 | previewfile: thumbnailfile | ||
188 | } | ||
189 | |||
190 | console.log('\nUploading on PeerTube video "%s".', videoAttributes.name) | ||
191 | try { | ||
192 | await uploadVideo(program['url'], accessToken, videoAttributes) | ||
193 | } catch (err) { | ||
194 | if (err.message.indexOf('401') !== -1) { | ||
195 | console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.') | ||
196 | |||
197 | const res = await login(program['url'], client, user) | ||
198 | accessToken = res.body.access_token | ||
199 | |||
200 | await uploadVideo(program['url'], accessToken, videoAttributes) | ||
201 | } else { | ||
202 | console.log(err.message) | ||
203 | process.exit(1) | ||
204 | } | ||
205 | } | ||
206 | |||
207 | await remove(videoPath) | ||
208 | if (thumbnailfile) await remove(thumbnailfile) | ||
209 | |||
210 | console.log('Uploaded video "%s"!\n', videoAttributes.name) | ||
211 | } | ||
212 | |||
213 | async function getCategory (categories: string[]) { | ||
214 | if (!categories) return undefined | ||
215 | |||
216 | const categoryString = categories[0] | ||
217 | |||
218 | if (categoryString === 'News & Politics') return 11 | ||
219 | |||
220 | const res = await getVideoCategories(program['url']) | ||
221 | const categoriesServer = res.body | ||
222 | |||
223 | for (const key of Object.keys(categoriesServer)) { | ||
224 | const categoryServer = categoriesServer[key] | ||
225 | if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10) | ||
226 | } | ||
227 | |||
228 | return undefined | ||
229 | } | ||
230 | |||
231 | function getLicence (licence: string) { | ||
232 | if (!licence) return undefined | ||
233 | |||
234 | if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1 | ||
235 | |||
236 | return undefined | ||
237 | } | ||
238 | |||
239 | function normalizeObject (obj: any) { | ||
240 | const newObj: any = {} | ||
241 | |||
242 | for (const key of Object.keys(obj)) { | ||
243 | // Deprecated key | ||
244 | if (key === 'resolution') continue | ||
245 | |||
246 | const value = obj[key] | ||
247 | |||
248 | if (typeof value === 'string') { | ||
249 | newObj[key] = value.normalize() | ||
250 | } else { | ||
251 | newObj[key] = value | ||
252 | } | ||
253 | } | ||
254 | |||
255 | return newObj | ||
256 | } | ||
257 | |||
258 | function fetchObject (info: any) { | ||
259 | const url = buildUrl(info) | ||
260 | |||
261 | return new Promise<any>(async (res, rej) => { | ||
262 | youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => { | ||
263 | if (err) return rej(err) | ||
264 | |||
265 | const videoInfoWithUrl = Object.assign(videoInfo, { url }) | ||
266 | return res(normalizeObject(videoInfoWithUrl)) | ||
267 | }) | ||
268 | }) | ||
269 | } | ||
270 | |||
271 | function buildUrl (info: any) { | ||
272 | const webpageUrl = info.webpage_url as string | ||
273 | if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl | ||
274 | |||
275 | const url = info.url as string | ||
276 | if (url && url.match(/^https?:\/\//)) return url | ||
277 | |||
278 | // It seems youtube-dl does not return the video url | ||
279 | return 'https://www.youtube.com/watch?v=' + info.id | ||
280 | } | ||
281 | |||
282 | function isNSFW (info: any) { | ||
283 | if (info.age_limit && info.age_limit >= 16) return true | ||
284 | |||
285 | return false | ||
286 | } | ||