]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users.ts
Fix max buffer reached in youtube import
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
ac81d1a0 2import 'multer'
c5911fd3
C
3import { extname, join } from 'path'
4import * as uuidv4 from 'uuid/v4'
571389d4 5import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
da854ddd 6import { retryTransactionWrapper } from '../../helpers/database-utils'
ac81d1a0 7import { processImage } from '../../helpers/image-utils'
da854ddd 8import { logger } from '../../helpers/logger'
f076daa7 9import { createReqFiles, getFormattedObjects } from '../../helpers/utils'
ac81d1a0 10import { AVATARS_SIZE, CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../initializers'
a5625b41 11import { updateActorAvatarInstance } from '../../lib/activitypub'
265ba139 12import { sendUpdateUser } from '../../lib/activitypub/send'
ecb4e35f 13import { Emailer } from '../../lib/emailer'
ecb4e35f 14import { Redis } from '../../lib/redis'
50d6de9c 15import { createUserAccountAndChannel } from '../../lib/user'
65fcc311 16import {
f076daa7
C
17 asyncMiddleware,
18 authenticate,
19 ensureUserHasRight,
20 ensureUserRegistrationAllowed,
21 paginationValidator,
22 setDefaultPagination,
23 setDefaultSort,
24 token,
25 usersAddValidator,
26 usersGetValidator,
27 usersRegisterValidator,
28 usersRemoveValidator,
29 usersSortValidator,
30 usersUpdateMeValidator,
31 usersUpdateValidator,
32 usersVideoRatingValidator
65fcc311 33} from '../../middlewares'
ecb4e35f 34import {
f076daa7
C
35 usersAskResetPasswordValidator,
36 usersResetPasswordValidator,
37 usersUpdateMyAvatarValidator,
ecb4e35f
C
38 videosSortValidator
39} from '../../middlewares/validators'
3fd3ab2d
C
40import { AccountVideoRateModel } from '../../models/account/account-video-rate'
41import { UserModel } from '../../models/account/user'
f8b8c36b 42import { OAuthTokenModel } from '../../models/oauth/oauth-token'
3fd3ab2d 43import { VideoModel } from '../../models/video/video'
65fcc311 44
ac81d1a0 45const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
c5911fd3 46
65fcc311
C
47const usersRouter = express.Router()
48
49usersRouter.get('/me',
50 authenticate,
eb080476 51 asyncMiddleware(getUserInformation)
d38b8281
C
52)
53
ce5496d6
C
54usersRouter.get('/me/video-quota-used',
55 authenticate,
56 asyncMiddleware(getUserVideoQuotaUsed)
57)
58
fd45e8f4
C
59usersRouter.get('/me/videos',
60 authenticate,
61 paginationValidator,
62 videosSortValidator,
1174a847 63 setDefaultSort,
f05a1c30 64 setDefaultPagination,
fd45e8f4
C
65 asyncMiddleware(getUserVideos)
66)
67
65fcc311
C
68usersRouter.get('/me/videos/:videoId/rating',
69 authenticate,
a2431b7d 70 asyncMiddleware(usersVideoRatingValidator),
eb080476 71 asyncMiddleware(getUserVideoRating)
d38b8281 72)
9bd26629 73
65fcc311 74usersRouter.get('/',
86d13ec2
C
75 authenticate,
76 ensureUserHasRight(UserRight.MANAGE_USERS),
65fcc311
C
77 paginationValidator,
78 usersSortValidator,
1174a847 79 setDefaultSort,
f05a1c30 80 setDefaultPagination,
eb080476 81 asyncMiddleware(listUsers)
5c39adb7
C
82)
83
8094a898 84usersRouter.get('/:id',
a2431b7d 85 asyncMiddleware(usersGetValidator),
8094a898
C
86 getUser
87)
88
65fcc311
C
89usersRouter.post('/',
90 authenticate,
954605a8 91 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d
C
92 asyncMiddleware(usersAddValidator),
93 asyncMiddleware(createUserRetryWrapper)
9bd26629
C
94)
95
65fcc311 96usersRouter.post('/register',
a2431b7d
C
97 asyncMiddleware(ensureUserRegistrationAllowed),
98 asyncMiddleware(usersRegisterValidator),
47e0652b 99 asyncMiddleware(registerUserRetryWrapper)
2c2e9092
C
100)
101
8094a898
C
102usersRouter.put('/me',
103 authenticate,
104 usersUpdateMeValidator,
eb080476 105 asyncMiddleware(updateMe)
8094a898
C
106)
107
c5911fd3
C
108usersRouter.post('/me/avatar/pick',
109 authenticate,
110 reqAvatarFile,
111 usersUpdateMyAvatarValidator,
112 asyncMiddleware(updateMyAvatar)
113)
114
65fcc311
C
115usersRouter.put('/:id',
116 authenticate,
954605a8 117 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 118 asyncMiddleware(usersUpdateValidator),
eb080476 119 asyncMiddleware(updateUser)
9bd26629
C
120)
121
65fcc311
C
122usersRouter.delete('/:id',
123 authenticate,
954605a8 124 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 125 asyncMiddleware(usersRemoveValidator),
eb080476 126 asyncMiddleware(removeUser)
9bd26629 127)
6606150c 128
ecb4e35f
C
129usersRouter.post('/ask-reset-password',
130 asyncMiddleware(usersAskResetPasswordValidator),
131 asyncMiddleware(askResetUserPassword)
132)
133
134usersRouter.post('/:id/reset-password',
135 asyncMiddleware(usersResetPasswordValidator),
136 asyncMiddleware(resetUserPassword)
137)
138
65fcc311 139usersRouter.post('/token', token, success)
9bd26629 140// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
9457bf88
C
141
142// ---------------------------------------------------------------------------
143
65fcc311
C
144export {
145 usersRouter
146}
9457bf88
C
147
148// ---------------------------------------------------------------------------
149
fd45e8f4 150async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d
C
151 const user = res.locals.oauth.token.User as UserModel
152 const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
fd45e8f4
C
153
154 return res.json(getFormattedObjects(resultList.data, resultList.total))
155}
156
eb080476 157async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
72c7248b 158 const options = {
47e0652b 159 arguments: [ req ],
72c7248b
C
160 errorMessage: 'Cannot insert the user with many retries.'
161 }
162
f05a1c30 163 const { user, account } = await retryTransactionWrapper(createUser, options)
eb080476 164
f05a1c30
C
165 return res.json({
166 user: {
167 id: user.id,
168 uuid: account.uuid
169 }
170 }).end()
72c7248b
C
171}
172
47e0652b 173async function createUser (req: express.Request) {
4771e000 174 const body: UserCreate = req.body
f05a1c30 175 const userToCreate = new UserModel({
4771e000
C
176 username: body.username,
177 password: body.password,
178 email: body.email,
1d49e1e2 179 displayNSFW: false,
7efe153b 180 autoPlayVideo: true,
954605a8 181 role: body.role,
b0f9f39e 182 videoQuota: body.videoQuota
9bd26629
C
183 })
184
f05a1c30 185 const { user, account } = await createUserAccountAndChannel(userToCreate)
eb080476 186
38fa2065 187 logger.info('User %s with its channel and account created.', body.username)
f05a1c30
C
188
189 return { user, account }
9bd26629
C
190}
191
47e0652b
C
192async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
193 const options = {
194 arguments: [ req ],
195 errorMessage: 'Cannot insert the user with many retries.'
196 }
197
198 await retryTransactionWrapper(registerUser, options)
199
200 return res.type('json').status(204).end()
201}
202
203async function registerUser (req: express.Request) {
77a5501f
C
204 const body: UserCreate = req.body
205
3fd3ab2d 206 const user = new UserModel({
77a5501f
C
207 username: body.username,
208 password: body.password,
209 email: body.email,
210 displayNSFW: false,
7efe153b 211 autoPlayVideo: true,
954605a8 212 role: UserRole.USER,
77a5501f
C
213 videoQuota: CONFIG.USER.VIDEO_QUOTA
214 })
215
38fa2065 216 await createUserAccountAndChannel(user)
47e0652b
C
217
218 logger.info('User %s with its channel and account registered.', body.username)
77a5501f
C
219}
220
eb080476 221async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
fd45e8f4 222 // We did not load channels in res.locals.user
3fd3ab2d 223 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
eb080476
C
224
225 return res.json(user.toFormattedJSON())
99a64bfe
C
226}
227
ce5496d6
C
228async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
229 // We did not load channels in res.locals.user
230 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
231 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
232
233 return res.json({
234 videoQuotaUsed
235 })
236}
237
8094a898 238function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
ce5496d6 239 return res.json((res.locals.user as UserModel).toFormattedJSON())
8094a898
C
240}
241
eb080476 242async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
0a6658fd 243 const videoId = +req.params.videoId
571389d4 244 const accountId = +res.locals.oauth.token.User.Account.id
d38b8281 245
3fd3ab2d 246 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
faab3a84
C
247 const rating = ratingObj ? ratingObj.type : 'none'
248
249 const json: FormattedUserVideoRate = {
250 videoId,
251 rating
252 }
253 res.json(json)
d38b8281
C
254}
255
eb080476 256async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d 257 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
eb080476
C
258
259 return res.json(getFormattedObjects(resultList.data, resultList.total))
9bd26629
C
260}
261
eb080476 262async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d 263 const user = await UserModel.loadById(req.params.id)
eb080476
C
264
265 await user.destroy()
266
267 return res.sendStatus(204)
9bd26629
C
268}
269
eb080476 270async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 271 const body: UserUpdateMe = req.body
4771e000 272
eb080476 273 const user = res.locals.oauth.token.user
1d49e1e2 274
eb080476
C
275 if (body.password !== undefined) user.password = body.password
276 if (body.email !== undefined) user.email = body.email
277 if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
7efe153b 278 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
eb080476
C
279
280 await user.save()
265ba139 281 await sendUpdateUser(user, undefined)
eb080476 282
d412e80e 283 return res.sendStatus(204)
9bd26629
C
284}
285
c5911fd3
C
286async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
287 const avatarPhysicalFile = req.files['avatarfile'][0]
265ba139
C
288 const user = res.locals.oauth.token.user
289 const actor = user.Account.Actor
c5911fd3 290
c5911fd3
C
291 const extension = extname(avatarPhysicalFile.filename)
292 const avatarName = uuidv4() + extension
ac81d1a0
C
293 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
294 await processImage(avatarPhysicalFile, destination, AVATARS_SIZE)
c5911fd3 295
a5625b41 296 const avatar = await sequelizeTypescript.transaction(async t => {
bb82394c
C
297 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
298 await updatedActor.save({ transaction: t })
c5911fd3 299
a5625b41 300 await sendUpdateUser(user, t)
c5911fd3 301
bb82394c 302 return updatedActor.Avatar
c5911fd3
C
303 })
304
305 return res
306 .json({
307 avatar: avatar.toFormattedJSON()
308 })
309 .end()
310}
311
eb080476 312async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 313 const body: UserUpdate = req.body
3fd3ab2d 314 const user = res.locals.user as UserModel
f8b8c36b 315 const roleChanged = body.role !== undefined && body.role !== user.role
8094a898
C
316
317 if (body.email !== undefined) user.email = body.email
318 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
954605a8 319 if (body.role !== undefined) user.role = body.role
8094a898 320
eb080476
C
321 await user.save()
322
f8b8c36b
C
323 // Destroy user token to refresh rights
324 if (roleChanged) {
325 await OAuthTokenModel.deleteUserToken(user.id)
326 }
327
265ba139
C
328 // Don't need to send this update to followers, these attributes are not propagated
329
eb080476 330 return res.sendStatus(204)
8094a898
C
331}
332
ecb4e35f
C
333async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
334 const user = res.locals.user as UserModel
335
336 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
337 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
338 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
339
340 return res.status(204).end()
341}
342
343async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
344 const user = res.locals.user as UserModel
345 user.password = req.body.password
346
347 await user.save()
348
349 return res.status(204).end()
350}
351
69818c93 352function success (req: express.Request, res: express.Response, next: express.NextFunction) {
9457bf88
C
353 res.end()
354}