]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/config.ts
Add external login tests
[github/Chocobozzz/PeerTube.git] / server / controllers / api / config.ts
1 import { Hooks } from '@server/lib/plugins/hooks'
2 import * as express from 'express'
3 import { remove, writeJSON } from 'fs-extra'
4 import { snakeCase } from 'lodash'
5 import validator from 'validator'
6 import { RegisteredExternalAuthConfig, RegisteredIdAndPassAuthConfig, ServerConfig, UserRight } from '../../../shared'
7 import { About } from '../../../shared/models/server/about.model'
8 import { CustomConfig } from '../../../shared/models/server/custom-config.model'
9 import { auditLoggerFactory, CustomConfigAuditView, getAuditIdFromRes } from '../../helpers/audit-logger'
10 import { objectConverter } from '../../helpers/core-utils'
11 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
12 import { getServerCommit } from '../../helpers/utils'
13 import { CONFIG, isEmailEnabled, reloadConfig } from '../../initializers/config'
14 import { CONSTRAINTS_FIELDS, DEFAULT_THEME_NAME, PEERTUBE_VERSION } from '../../initializers/constants'
15 import { ClientHtml } from '../../lib/client-html'
16 import { PluginManager } from '../../lib/plugins/plugin-manager'
17 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
18 import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../middlewares'
19 import { customConfigUpdateValidator } from '../../middlewares/validators/config'
20
21 const configRouter = express.Router()
22
23 const auditLogger = auditLoggerFactory('config')
24
25 configRouter.get('/about', getAbout)
26 configRouter.get('/',
27 asyncMiddleware(getConfig)
28 )
29
30 configRouter.get('/custom',
31 authenticate,
32 ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
33 getCustomConfig
34 )
35 configRouter.put('/custom',
36 authenticate,
37 ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
38 customConfigUpdateValidator,
39 asyncMiddleware(updateCustomConfig)
40 )
41 configRouter.delete('/custom',
42 authenticate,
43 ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
44 asyncMiddleware(deleteCustomConfig)
45 )
46
47 let serverCommit: string
48
49 async function getConfig (req: express.Request, res: express.Response) {
50 const { allowed } = await Hooks.wrapPromiseFun(
51 isSignupAllowed,
52 {
53 ip: req.ip
54 },
55 'filter:api.user.signup.allowed.result'
56 )
57
58 const allowedForCurrentIP = isSignupAllowedForCurrentIP(req.ip)
59 const defaultTheme = getThemeOrDefault(CONFIG.THEME.DEFAULT, DEFAULT_THEME_NAME)
60
61 if (serverCommit === undefined) serverCommit = await getServerCommit()
62
63 const json: ServerConfig = {
64 instance: {
65 name: CONFIG.INSTANCE.NAME,
66 shortDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
67 defaultClientRoute: CONFIG.INSTANCE.DEFAULT_CLIENT_ROUTE,
68 isNSFW: CONFIG.INSTANCE.IS_NSFW,
69 defaultNSFWPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
70 customizations: {
71 javascript: CONFIG.INSTANCE.CUSTOMIZATIONS.JAVASCRIPT,
72 css: CONFIG.INSTANCE.CUSTOMIZATIONS.CSS
73 }
74 },
75 search: {
76 remoteUri: {
77 users: CONFIG.SEARCH.REMOTE_URI.USERS,
78 anonymous: CONFIG.SEARCH.REMOTE_URI.ANONYMOUS
79 }
80 },
81 plugin: {
82 registered: getRegisteredPlugins(),
83 registeredExternalAuths: getExternalAuthsPlugins(),
84 registeredIdAndPassAuths: getIdAndPassAuthPlugins()
85 },
86 theme: {
87 registered: getRegisteredThemes(),
88 default: defaultTheme
89 },
90 email: {
91 enabled: isEmailEnabled()
92 },
93 contactForm: {
94 enabled: CONFIG.CONTACT_FORM.ENABLED
95 },
96 serverVersion: PEERTUBE_VERSION,
97 serverCommit,
98 signup: {
99 allowed,
100 allowedForCurrentIP,
101 requiresEmailVerification: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION
102 },
103 transcoding: {
104 hls: {
105 enabled: CONFIG.TRANSCODING.HLS.ENABLED
106 },
107 webtorrent: {
108 enabled: CONFIG.TRANSCODING.WEBTORRENT.ENABLED
109 },
110 enabledResolutions: getEnabledResolutions()
111 },
112 import: {
113 videos: {
114 http: {
115 enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
116 },
117 torrent: {
118 enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
119 }
120 }
121 },
122 autoBlacklist: {
123 videos: {
124 ofUsers: {
125 enabled: CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED
126 }
127 }
128 },
129 avatar: {
130 file: {
131 size: {
132 max: CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max
133 },
134 extensions: CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME
135 }
136 },
137 video: {
138 image: {
139 extensions: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME,
140 size: {
141 max: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max
142 }
143 },
144 file: {
145 extensions: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME
146 }
147 },
148 videoCaption: {
149 file: {
150 size: {
151 max: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
152 },
153 extensions: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.EXTNAME
154 }
155 },
156 user: {
157 videoQuota: CONFIG.USER.VIDEO_QUOTA,
158 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY
159 },
160 trending: {
161 videos: {
162 intervalDays: CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
163 }
164 },
165 tracker: {
166 enabled: CONFIG.TRACKER.ENABLED
167 },
168
169 followings: {
170 instance: {
171 autoFollowIndex: {
172 indexUrl: CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.INDEX_URL
173 }
174 }
175 }
176 }
177
178 return res.json(json)
179 }
180
181 function getAbout (req: express.Request, res: express.Response) {
182 const about: About = {
183 instance: {
184 name: CONFIG.INSTANCE.NAME,
185 shortDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
186 description: CONFIG.INSTANCE.DESCRIPTION,
187 terms: CONFIG.INSTANCE.TERMS,
188 codeOfConduct: CONFIG.INSTANCE.CODE_OF_CONDUCT,
189
190 hardwareInformation: CONFIG.INSTANCE.HARDWARE_INFORMATION,
191
192 creationReason: CONFIG.INSTANCE.CREATION_REASON,
193 moderationInformation: CONFIG.INSTANCE.MODERATION_INFORMATION,
194 administrator: CONFIG.INSTANCE.ADMINISTRATOR,
195 maintenanceLifetime: CONFIG.INSTANCE.MAINTENANCE_LIFETIME,
196 businessModel: CONFIG.INSTANCE.BUSINESS_MODEL,
197
198 languages: CONFIG.INSTANCE.LANGUAGES,
199 categories: CONFIG.INSTANCE.CATEGORIES
200 }
201 }
202
203 return res.json(about).end()
204 }
205
206 function getCustomConfig (req: express.Request, res: express.Response) {
207 const data = customConfig()
208
209 return res.json(data).end()
210 }
211
212 async function deleteCustomConfig (req: express.Request, res: express.Response) {
213 await remove(CONFIG.CUSTOM_FILE)
214
215 auditLogger.delete(getAuditIdFromRes(res), new CustomConfigAuditView(customConfig()))
216
217 reloadConfig()
218 ClientHtml.invalidCache()
219
220 const data = customConfig()
221
222 return res.json(data).end()
223 }
224
225 async function updateCustomConfig (req: express.Request, res: express.Response) {
226 const oldCustomConfigAuditKeys = new CustomConfigAuditView(customConfig())
227
228 // camelCase to snake_case key + Force number conversion
229 const toUpdateJSON = convertCustomConfigBody(req.body)
230
231 await writeJSON(CONFIG.CUSTOM_FILE, toUpdateJSON, { spaces: 2 })
232
233 reloadConfig()
234 ClientHtml.invalidCache()
235
236 const data = customConfig()
237
238 auditLogger.update(
239 getAuditIdFromRes(res),
240 new CustomConfigAuditView(data),
241 oldCustomConfigAuditKeys
242 )
243
244 return res.json(data).end()
245 }
246
247 function getRegisteredThemes () {
248 return PluginManager.Instance.getRegisteredThemes()
249 .map(t => ({
250 name: t.name,
251 version: t.version,
252 description: t.description,
253 css: t.css,
254 clientScripts: t.clientScripts
255 }))
256 }
257
258 function getEnabledResolutions () {
259 return Object.keys(CONFIG.TRANSCODING.RESOLUTIONS)
260 .filter(key => CONFIG.TRANSCODING.ENABLED && CONFIG.TRANSCODING.RESOLUTIONS[key] === true)
261 .map(r => parseInt(r, 10))
262 }
263
264 function getRegisteredPlugins () {
265 return PluginManager.Instance.getRegisteredPlugins()
266 .map(p => ({
267 name: p.name,
268 version: p.version,
269 description: p.description,
270 clientScripts: p.clientScripts
271 }))
272 }
273
274 function getIdAndPassAuthPlugins () {
275 const result: RegisteredIdAndPassAuthConfig[] = []
276
277 for (const p of PluginManager.Instance.getIdAndPassAuths()) {
278 for (const auth of p.idAndPassAuths) {
279 result.push({
280 npmName: p.npmName,
281 authName: auth.authName,
282 weight: auth.getWeight()
283 })
284 }
285 }
286
287 return result
288 }
289
290 function getExternalAuthsPlugins () {
291 const result: RegisteredExternalAuthConfig[] = []
292
293 for (const p of PluginManager.Instance.getExternalAuths()) {
294 for (const auth of p.externalAuths) {
295 result.push({
296 npmName: p.npmName,
297 authName: auth.authName,
298 authDisplayName: auth.authDisplayName
299 })
300 }
301 }
302
303 return result
304 }
305
306 // ---------------------------------------------------------------------------
307
308 export {
309 configRouter,
310 getEnabledResolutions,
311 getRegisteredPlugins,
312 getRegisteredThemes
313 }
314
315 // ---------------------------------------------------------------------------
316
317 function customConfig (): CustomConfig {
318 return {
319 instance: {
320 name: CONFIG.INSTANCE.NAME,
321 shortDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
322 description: CONFIG.INSTANCE.DESCRIPTION,
323 terms: CONFIG.INSTANCE.TERMS,
324 codeOfConduct: CONFIG.INSTANCE.CODE_OF_CONDUCT,
325
326 creationReason: CONFIG.INSTANCE.CREATION_REASON,
327 moderationInformation: CONFIG.INSTANCE.MODERATION_INFORMATION,
328 administrator: CONFIG.INSTANCE.ADMINISTRATOR,
329 maintenanceLifetime: CONFIG.INSTANCE.MAINTENANCE_LIFETIME,
330 businessModel: CONFIG.INSTANCE.BUSINESS_MODEL,
331 hardwareInformation: CONFIG.INSTANCE.HARDWARE_INFORMATION,
332
333 languages: CONFIG.INSTANCE.LANGUAGES,
334 categories: CONFIG.INSTANCE.CATEGORIES,
335
336 isNSFW: CONFIG.INSTANCE.IS_NSFW,
337 defaultClientRoute: CONFIG.INSTANCE.DEFAULT_CLIENT_ROUTE,
338 defaultNSFWPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
339 customizations: {
340 css: CONFIG.INSTANCE.CUSTOMIZATIONS.CSS,
341 javascript: CONFIG.INSTANCE.CUSTOMIZATIONS.JAVASCRIPT
342 }
343 },
344 theme: {
345 default: CONFIG.THEME.DEFAULT
346 },
347 services: {
348 twitter: {
349 username: CONFIG.SERVICES.TWITTER.USERNAME,
350 whitelisted: CONFIG.SERVICES.TWITTER.WHITELISTED
351 }
352 },
353 cache: {
354 previews: {
355 size: CONFIG.CACHE.PREVIEWS.SIZE
356 },
357 captions: {
358 size: CONFIG.CACHE.VIDEO_CAPTIONS.SIZE
359 }
360 },
361 signup: {
362 enabled: CONFIG.SIGNUP.ENABLED,
363 limit: CONFIG.SIGNUP.LIMIT,
364 requiresEmailVerification: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION
365 },
366 admin: {
367 email: CONFIG.ADMIN.EMAIL
368 },
369 contactForm: {
370 enabled: CONFIG.CONTACT_FORM.ENABLED
371 },
372 user: {
373 videoQuota: CONFIG.USER.VIDEO_QUOTA,
374 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY
375 },
376 transcoding: {
377 enabled: CONFIG.TRANSCODING.ENABLED,
378 allowAdditionalExtensions: CONFIG.TRANSCODING.ALLOW_ADDITIONAL_EXTENSIONS,
379 allowAudioFiles: CONFIG.TRANSCODING.ALLOW_AUDIO_FILES,
380 threads: CONFIG.TRANSCODING.THREADS,
381 resolutions: {
382 '0p': CONFIG.TRANSCODING.RESOLUTIONS['0p'],
383 '240p': CONFIG.TRANSCODING.RESOLUTIONS['240p'],
384 '360p': CONFIG.TRANSCODING.RESOLUTIONS['360p'],
385 '480p': CONFIG.TRANSCODING.RESOLUTIONS['480p'],
386 '720p': CONFIG.TRANSCODING.RESOLUTIONS['720p'],
387 '1080p': CONFIG.TRANSCODING.RESOLUTIONS['1080p'],
388 '2160p': CONFIG.TRANSCODING.RESOLUTIONS['2160p']
389 },
390 webtorrent: {
391 enabled: CONFIG.TRANSCODING.WEBTORRENT.ENABLED
392 },
393 hls: {
394 enabled: CONFIG.TRANSCODING.HLS.ENABLED
395 }
396 },
397 import: {
398 videos: {
399 http: {
400 enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
401 },
402 torrent: {
403 enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
404 }
405 }
406 },
407 autoBlacklist: {
408 videos: {
409 ofUsers: {
410 enabled: CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED
411 }
412 }
413 },
414 followers: {
415 instance: {
416 enabled: CONFIG.FOLLOWERS.INSTANCE.ENABLED,
417 manualApproval: CONFIG.FOLLOWERS.INSTANCE.MANUAL_APPROVAL
418 }
419 },
420 followings: {
421 instance: {
422 autoFollowBack: {
423 enabled: CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_BACK.ENABLED
424 },
425
426 autoFollowIndex: {
427 enabled: CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.ENABLED,
428 indexUrl: CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.INDEX_URL
429 }
430 }
431 }
432 }
433 }
434
435 function convertCustomConfigBody (body: CustomConfig) {
436 function keyConverter (k: string) {
437 // Transcoding resolutions exception
438 if (/^\d{3,4}p$/.exec(k)) return k
439 if (k === '0p') return k
440
441 return snakeCase(k)
442 }
443
444 function valueConverter (v: any) {
445 if (validator.isNumeric(v + '')) return parseInt('' + v, 10)
446
447 return v
448 }
449
450 return objectConverter(body, keyConverter, valueConverter)
451 }