Add ability to update some configuration keys
[oweals/peertube.git] / server / controllers / api / users.ts
1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import * as sharp from 'sharp'
4 import * as uuidv4 from 'uuid/v4'
5 import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
6 import { unlinkPromise } from '../../helpers/core-utils'
7 import { retryTransactionWrapper } from '../../helpers/database-utils'
8 import { logger } from '../../helpers/logger'
9 import { createReqFiles, getFormattedObjects } from '../../helpers/utils'
10 import { AVATAR_MIMETYPE_EXT, AVATARS_SIZE, CONFIG, sequelizeTypescript } from '../../initializers'
11 import { updateActorAvatarInstance } from '../../lib/activitypub'
12 import { sendUpdateUser } from '../../lib/activitypub/send'
13 import { createUserAccountAndChannel } from '../../lib/user'
14 import {
15   asyncMiddleware, authenticate, ensureUserHasRight, ensureUserRegistrationAllowed, paginationValidator, setPagination, setUsersSort,
16   setVideosSort, token, usersAddValidator, usersGetValidator, usersRegisterValidator, usersRemoveValidator, usersSortValidator,
17   usersUpdateMeValidator, usersUpdateValidator, usersVideoRatingValidator
18 } from '../../middlewares'
19 import { usersUpdateMyAvatarValidator, videosSortValidator } from '../../middlewares/validators'
20 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
21 import { UserModel } from '../../models/account/user'
22 import { VideoModel } from '../../models/video/video'
23
24 const reqAvatarFile = createReqFiles('avatarfile', CONFIG.STORAGE.AVATARS_DIR, AVATAR_MIMETYPE_EXT)
25
26 const usersRouter = express.Router()
27
28 usersRouter.get('/me',
29   authenticate,
30   asyncMiddleware(getUserInformation)
31 )
32
33 usersRouter.get('/me/video-quota-used',
34   authenticate,
35   asyncMiddleware(getUserVideoQuotaUsed)
36 )
37
38 usersRouter.get('/me/videos',
39   authenticate,
40   paginationValidator,
41   videosSortValidator,
42   setVideosSort,
43   setPagination,
44   asyncMiddleware(getUserVideos)
45 )
46
47 usersRouter.get('/me/videos/:videoId/rating',
48   authenticate,
49   asyncMiddleware(usersVideoRatingValidator),
50   asyncMiddleware(getUserVideoRating)
51 )
52
53 usersRouter.get('/',
54   authenticate,
55   ensureUserHasRight(UserRight.MANAGE_USERS),
56   paginationValidator,
57   usersSortValidator,
58   setUsersSort,
59   setPagination,
60   asyncMiddleware(listUsers)
61 )
62
63 usersRouter.get('/:id',
64   asyncMiddleware(usersGetValidator),
65   getUser
66 )
67
68 usersRouter.post('/',
69   authenticate,
70   ensureUserHasRight(UserRight.MANAGE_USERS),
71   asyncMiddleware(usersAddValidator),
72   asyncMiddleware(createUserRetryWrapper)
73 )
74
75 usersRouter.post('/register',
76   asyncMiddleware(ensureUserRegistrationAllowed),
77   asyncMiddleware(usersRegisterValidator),
78   asyncMiddleware(registerUserRetryWrapper)
79 )
80
81 usersRouter.put('/me',
82   authenticate,
83   usersUpdateMeValidator,
84   asyncMiddleware(updateMe)
85 )
86
87 usersRouter.post('/me/avatar/pick',
88   authenticate,
89   reqAvatarFile,
90   usersUpdateMyAvatarValidator,
91   asyncMiddleware(updateMyAvatar)
92 )
93
94 usersRouter.put('/:id',
95   authenticate,
96   ensureUserHasRight(UserRight.MANAGE_USERS),
97   asyncMiddleware(usersUpdateValidator),
98   asyncMiddleware(updateUser)
99 )
100
101 usersRouter.delete('/:id',
102   authenticate,
103   ensureUserHasRight(UserRight.MANAGE_USERS),
104   asyncMiddleware(usersRemoveValidator),
105   asyncMiddleware(removeUser)
106 )
107
108 usersRouter.post('/token', token, success)
109 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
110
111 // ---------------------------------------------------------------------------
112
113 export {
114   usersRouter
115 }
116
117 // ---------------------------------------------------------------------------
118
119 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
120   const user = res.locals.oauth.token.User as UserModel
121   const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
122
123   return res.json(getFormattedObjects(resultList.data, resultList.total))
124 }
125
126 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
127   const options = {
128     arguments: [ req ],
129     errorMessage: 'Cannot insert the user with many retries.'
130   }
131
132   await retryTransactionWrapper(createUser, options)
133
134   // TODO : include Location of the new user -> 201
135   return res.type('json').status(204).end()
136 }
137
138 async function createUser (req: express.Request) {
139   const body: UserCreate = req.body
140   const user = new UserModel({
141     username: body.username,
142     password: body.password,
143     email: body.email,
144     displayNSFW: false,
145     autoPlayVideo: true,
146     role: body.role,
147     videoQuota: body.videoQuota
148   })
149
150   await createUserAccountAndChannel(user)
151
152   logger.info('User %s with its channel and account created.', body.username)
153 }
154
155 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
156   const options = {
157     arguments: [ req ],
158     errorMessage: 'Cannot insert the user with many retries.'
159   }
160
161   await retryTransactionWrapper(registerUser, options)
162
163   return res.type('json').status(204).end()
164 }
165
166 async function registerUser (req: express.Request) {
167   const body: UserCreate = req.body
168
169   const user = new UserModel({
170     username: body.username,
171     password: body.password,
172     email: body.email,
173     displayNSFW: false,
174     autoPlayVideo: true,
175     role: UserRole.USER,
176     videoQuota: CONFIG.USER.VIDEO_QUOTA
177   })
178
179   await createUserAccountAndChannel(user)
180
181   logger.info('User %s with its channel and account registered.', body.username)
182 }
183
184 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
185   // We did not load channels in res.locals.user
186   const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
187
188   return res.json(user.toFormattedJSON())
189 }
190
191 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
192   // We did not load channels in res.locals.user
193   const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
194   const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
195
196   return res.json({
197     videoQuotaUsed
198   })
199 }
200
201 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
202   return res.json((res.locals.user as UserModel).toFormattedJSON())
203 }
204
205 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
206   const videoId = +req.params.videoId
207   const accountId = +res.locals.oauth.token.User.Account.id
208
209   const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
210   const rating = ratingObj ? ratingObj.type : 'none'
211
212   const json: FormattedUserVideoRate = {
213     videoId,
214     rating
215   }
216   res.json(json)
217 }
218
219 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
220   const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
221
222   return res.json(getFormattedObjects(resultList.data, resultList.total))
223 }
224
225 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
226   const user = await UserModel.loadById(req.params.id)
227
228   await user.destroy()
229
230   return res.sendStatus(204)
231 }
232
233 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
234   const body: UserUpdateMe = req.body
235
236   const user = res.locals.oauth.token.user
237
238   if (body.password !== undefined) user.password = body.password
239   if (body.email !== undefined) user.email = body.email
240   if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
241   if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
242
243   await user.save()
244   await sendUpdateUser(user, undefined)
245
246   return res.sendStatus(204)
247 }
248
249 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
250   const avatarPhysicalFile = req.files['avatarfile'][0]
251   const user = res.locals.oauth.token.user
252   const actor = user.Account.Actor
253
254   const avatarDir = CONFIG.STORAGE.AVATARS_DIR
255   const source = join(avatarDir, avatarPhysicalFile.filename)
256   const extension = extname(avatarPhysicalFile.filename)
257   const avatarName = uuidv4() + extension
258   const destination = join(avatarDir, avatarName)
259
260   await sharp(source)
261     .resize(AVATARS_SIZE.width, AVATARS_SIZE.height)
262     .toFile(destination)
263
264   await unlinkPromise(source)
265
266   const avatar = await sequelizeTypescript.transaction(async t => {
267     const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
268     await updatedActor.save({ transaction: t })
269
270     await sendUpdateUser(user, t)
271
272     return updatedActor.Avatar
273   })
274
275   return res
276     .json({
277       avatar: avatar.toFormattedJSON()
278     })
279     .end()
280 }
281
282 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
283   const body: UserUpdate = req.body
284   const user = res.locals.user as UserModel
285
286   if (body.email !== undefined) user.email = body.email
287   if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
288   if (body.role !== undefined) user.role = body.role
289
290   await user.save()
291
292   // Don't need to send this update to followers, these attributes are not propagated
293
294   return res.sendStatus(204)
295 }
296
297 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
298   res.end()
299 }