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