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'
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'
25 const reqAvatarFile = createReqFiles('avatarfile', CONFIG.STORAGE.AVATARS_DIR, AVATAR_MIMETYPE_EXT)
27 const usersRouter = express.Router()
29 usersRouter.get('/me',
31 asyncMiddleware(getUserInformation)
34 usersRouter.get('/me/video-quota-used',
36 asyncMiddleware(getUserVideoQuotaUsed)
39 usersRouter.get('/me/videos',
45 asyncMiddleware(getUserVideos)
48 usersRouter.get('/me/videos/:videoId/rating',
50 asyncMiddleware(usersVideoRatingValidator),
51 asyncMiddleware(getUserVideoRating)
56 ensureUserHasRight(UserRight.MANAGE_USERS),
61 asyncMiddleware(listUsers)
64 usersRouter.get('/:id',
65 asyncMiddleware(usersGetValidator),
71 ensureUserHasRight(UserRight.MANAGE_USERS),
72 asyncMiddleware(usersAddValidator),
73 asyncMiddleware(createUserRetryWrapper)
76 usersRouter.post('/register',
77 asyncMiddleware(ensureUserRegistrationAllowed),
78 asyncMiddleware(usersRegisterValidator),
79 asyncMiddleware(registerUserRetryWrapper)
82 usersRouter.put('/me',
84 usersUpdateMeValidator,
85 asyncMiddleware(updateMe)
88 usersRouter.post('/me/avatar/pick',
91 usersUpdateMyAvatarValidator,
92 asyncMiddleware(updateMyAvatar)
95 usersRouter.put('/:id',
97 ensureUserHasRight(UserRight.MANAGE_USERS),
98 asyncMiddleware(usersUpdateValidator),
99 asyncMiddleware(updateUser)
102 usersRouter.delete('/:id',
104 ensureUserHasRight(UserRight.MANAGE_USERS),
105 asyncMiddleware(usersRemoveValidator),
106 asyncMiddleware(removeUser)
109 usersRouter.post('/token', token, success)
110 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
112 // ---------------------------------------------------------------------------
118 // ---------------------------------------------------------------------------
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)
124 return res.json(getFormattedObjects(resultList.data, resultList.total))
127 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
130 errorMessage: 'Cannot insert the user with many retries.'
133 const { user, account } = await retryTransactionWrapper(createUser, options)
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,
152 videoQuota: body.videoQuota
155 const { user, account } = await createUserAccountAndChannel(userToCreate)
157 logger.info('User %s with its channel and account created.', body.username)
159 return { user, account }
162 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
165 errorMessage: 'Cannot insert the user with many retries.'
168 await retryTransactionWrapper(registerUser, options)
170 return res.type('json').status(204).end()
173 async function registerUser (req: express.Request) {
174 const body: UserCreate = req.body
176 const user = new UserModel({
177 username: body.username,
178 password: body.password,
183 videoQuota: CONFIG.USER.VIDEO_QUOTA
186 await createUserAccountAndChannel(user)
188 logger.info('User %s with its channel and account registered.', body.username)
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)
195 return res.json(user.toFormattedJSON())
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)
208 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
209 return res.json((res.locals.user as UserModel).toFormattedJSON())
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
216 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
217 const rating = ratingObj ? ratingObj.type : 'none'
219 const json: FormattedUserVideoRate = {
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)
229 return res.json(getFormattedObjects(resultList.data, resultList.total))
232 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
233 const user = await UserModel.loadById(req.params.id)
237 return res.sendStatus(204)
240 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
241 const body: UserUpdateMe = req.body
243 const user = res.locals.oauth.token.user
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
251 await sendUpdateUser(user, undefined)
253 return res.sendStatus(204)
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
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)
268 .resize(AVATARS_SIZE.width, AVATARS_SIZE.height)
271 await unlinkPromise(source)
273 const avatar = await sequelizeTypescript.transaction(async t => {
274 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
275 await updatedActor.save({ transaction: t })
277 await sendUpdateUser(user, t)
279 return updatedActor.Avatar
284 avatar: avatar.toFormattedJSON()
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
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
300 // Destroy user token to refresh rights
302 await OAuthTokenModel.deleteUserToken(user.id)
305 // Don't need to send this update to followers, these attributes are not propagated
307 return res.sendStatus(204)
310 function success (req: express.Request, res: express.Response, next: express.NextFunction) {