Cleanup utils helper
[oweals/peertube.git] / server / controllers / api / config.ts
1 import * as express from 'express'
2 import { omit } from 'lodash'
3 import { ServerConfig, UserRight } from '../../../shared'
4 import { About } from '../../../shared/models/server/about.model'
5 import { CustomConfig } from '../../../shared/models/server/custom-config.model'
6 import { unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
7 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
8 import { CONFIG, CONSTRAINTS_FIELDS, reloadConfig } from '../../initializers'
9 import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../middlewares'
10 import { customConfigUpdateValidator } from '../../middlewares/validators/config'
11 import { ClientHtml } from '../../lib/client-html'
12 import { auditLoggerFactory, CustomConfigAuditView } from '../../helpers/audit-logger'
13
14 const packageJSON = require('../../../../package.json')
15 const configRouter = express.Router()
16
17 const auditLogger = auditLoggerFactory('config')
18
19 configRouter.get('/about', getAbout)
20 configRouter.get('/',
21   asyncMiddleware(getConfig)
22 )
23
24 configRouter.get('/custom',
25   authenticate,
26   ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
27   asyncMiddleware(getCustomConfig)
28 )
29 configRouter.put('/custom',
30   authenticate,
31   ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
32   asyncMiddleware(customConfigUpdateValidator),
33   asyncMiddleware(updateCustomConfig)
34 )
35 configRouter.delete('/custom',
36   authenticate,
37   ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
38   asyncMiddleware(deleteCustomConfig)
39 )
40
41 async function getConfig (req: express.Request, res: express.Response, next: express.NextFunction) {
42   const allowed = await isSignupAllowed()
43   const allowedForCurrentIP = isSignupAllowedForCurrentIP(req.ip)
44
45   const enabledResolutions = Object.keys(CONFIG.TRANSCODING.RESOLUTIONS)
46    .filter(key => CONFIG.TRANSCODING.RESOLUTIONS[key] === true)
47    .map(r => parseInt(r, 10))
48
49   const json: ServerConfig = {
50     instance: {
51       name: CONFIG.INSTANCE.NAME,
52       shortDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
53       defaultClientRoute: CONFIG.INSTANCE.DEFAULT_CLIENT_ROUTE,
54       defaultNSFWPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
55       customizations: {
56         javascript: CONFIG.INSTANCE.CUSTOMIZATIONS.JAVASCRIPT,
57         css: CONFIG.INSTANCE.CUSTOMIZATIONS.CSS
58       }
59     },
60     serverVersion: packageJSON.version,
61     signup: {
62       allowed,
63       allowedForCurrentIP
64     },
65     transcoding: {
66       enabledResolutions
67     },
68     import: {
69       videos: {
70         http: {
71           enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
72         },
73         torrent: {
74           enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
75         }
76       }
77     },
78     avatar: {
79       file: {
80         size: {
81           max: CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max
82         },
83         extensions: CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME
84       }
85     },
86     video: {
87       image: {
88         extensions: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME,
89         size: {
90           max: CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max
91         }
92       },
93       file: {
94         extensions: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME
95       }
96     },
97     videoCaption: {
98       file: {
99         size: {
100           max: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
101         },
102         extensions: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.EXTNAME
103       }
104     },
105     user: {
106       videoQuota: CONFIG.USER.VIDEO_QUOTA
107     }
108   }
109
110   return res.json(json)
111 }
112
113 function getAbout (req: express.Request, res: express.Response, next: express.NextFunction) {
114   const about: About = {
115     instance: {
116       name: CONFIG.INSTANCE.NAME,
117       shortDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
118       description: CONFIG.INSTANCE.DESCRIPTION,
119       terms: CONFIG.INSTANCE.TERMS
120     }
121   }
122
123   return res.json(about).end()
124 }
125
126 async function getCustomConfig (req: express.Request, res: express.Response, next: express.NextFunction) {
127   const data = customConfig()
128
129   return res.json(data).end()
130 }
131
132 async function deleteCustomConfig (req: express.Request, res: express.Response, next: express.NextFunction) {
133   await unlinkPromise(CONFIG.CUSTOM_FILE)
134
135   auditLogger.delete(
136     res.locals.oauth.token.User.Account.Actor.getIdentifier(),
137     new CustomConfigAuditView(customConfig())
138   )
139
140   reloadConfig()
141   ClientHtml.invalidCache()
142
143   const data = customConfig()
144
145   return res.json(data).end()
146 }
147
148 async function updateCustomConfig (req: express.Request, res: express.Response, next: express.NextFunction) {
149   const toUpdate: CustomConfig = req.body
150   const oldCustomConfigAuditKeys = new CustomConfigAuditView(customConfig())
151
152   // Force number conversion
153   toUpdate.cache.previews.size = parseInt('' + toUpdate.cache.previews.size, 10)
154   toUpdate.cache.captions.size = parseInt('' + toUpdate.cache.captions.size, 10)
155   toUpdate.signup.limit = parseInt('' + toUpdate.signup.limit, 10)
156   toUpdate.user.videoQuota = parseInt('' + toUpdate.user.videoQuota, 10)
157   toUpdate.transcoding.threads = parseInt('' + toUpdate.transcoding.threads, 10)
158
159   // camelCase to snake_case key
160   const toUpdateJSON = omit(toUpdate, 'user.videoQuota', 'instance.defaultClientRoute', 'instance.shortDescription', 'cache.videoCaptions')
161   toUpdateJSON.user['video_quota'] = toUpdate.user.videoQuota
162   toUpdateJSON.instance['default_client_route'] = toUpdate.instance.defaultClientRoute
163   toUpdateJSON.instance['short_description'] = toUpdate.instance.shortDescription
164   toUpdateJSON.instance['default_nsfw_policy'] = toUpdate.instance.defaultNSFWPolicy
165
166   await writeFilePromise(CONFIG.CUSTOM_FILE, JSON.stringify(toUpdateJSON, undefined, 2))
167
168   reloadConfig()
169   ClientHtml.invalidCache()
170
171   const data = customConfig()
172
173   auditLogger.update(
174     res.locals.oauth.token.User.Account.Actor.getIdentifier(),
175     new CustomConfigAuditView(data),
176     oldCustomConfigAuditKeys
177   )
178
179   return res.json(data).end()
180 }
181
182 // ---------------------------------------------------------------------------
183
184 export {
185   configRouter
186 }
187
188 // ---------------------------------------------------------------------------
189
190 function customConfig (): CustomConfig {
191   return {
192     instance: {
193       name: CONFIG.INSTANCE.NAME,
194       shortDescription: CONFIG.INSTANCE.SHORT_DESCRIPTION,
195       description: CONFIG.INSTANCE.DESCRIPTION,
196       terms: CONFIG.INSTANCE.TERMS,
197       defaultClientRoute: CONFIG.INSTANCE.DEFAULT_CLIENT_ROUTE,
198       defaultNSFWPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
199       customizations: {
200         css: CONFIG.INSTANCE.CUSTOMIZATIONS.CSS,
201         javascript: CONFIG.INSTANCE.CUSTOMIZATIONS.JAVASCRIPT
202       }
203     },
204     services: {
205       twitter: {
206         username: CONFIG.SERVICES.TWITTER.USERNAME,
207         whitelisted: CONFIG.SERVICES.TWITTER.WHITELISTED
208       }
209     },
210     cache: {
211       previews: {
212         size: CONFIG.CACHE.PREVIEWS.SIZE
213       },
214       captions: {
215         size: CONFIG.CACHE.VIDEO_CAPTIONS.SIZE
216       }
217     },
218     signup: {
219       enabled: CONFIG.SIGNUP.ENABLED,
220       limit: CONFIG.SIGNUP.LIMIT
221     },
222     admin: {
223       email: CONFIG.ADMIN.EMAIL
224     },
225     user: {
226       videoQuota: CONFIG.USER.VIDEO_QUOTA
227     },
228     transcoding: {
229       enabled: CONFIG.TRANSCODING.ENABLED,
230       threads: CONFIG.TRANSCODING.THREADS,
231       resolutions: {
232         '240p': CONFIG.TRANSCODING.RESOLUTIONS[ '240p' ],
233         '360p': CONFIG.TRANSCODING.RESOLUTIONS[ '360p' ],
234         '480p': CONFIG.TRANSCODING.RESOLUTIONS[ '480p' ],
235         '720p': CONFIG.TRANSCODING.RESOLUTIONS[ '720p' ],
236         '1080p': CONFIG.TRANSCODING.RESOLUTIONS[ '1080p' ]
237       }
238     },
239     import: {
240       videos: {
241         http: {
242           enabled: CONFIG.IMPORT.VIDEOS.HTTP.ENABLED
243         },
244         torrent: {
245           enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED
246         }
247       }
248     }
249   }
250 }