]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users/me.ts
Retrieve user by id instead of username
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / me.ts
CommitLineData
d03cd8bb 1import 'multer'
67ed6552 2import * as express from 'express'
2dbc170d 3import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '@server/helpers/audit-logger'
67ed6552 4import { UserUpdateMe, UserVideoRate as FormattedUserVideoRate, VideoSortField } from '../../../../shared'
2dbc170d 5import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
67ed6552
C
6import { UserVideoQuota } from '../../../../shared/models/users/user-video-quota.model'
7import { createReqFiles } from '../../../helpers/express-utils'
d03cd8bb 8import { getFormattedObjects } from '../../../helpers/utils'
67ed6552 9import { CONFIG } from '../../../initializers/config'
74dc3bca 10import { MIMETYPES } from '../../../initializers/constants'
67ed6552 11import { sequelizeTypescript } from '../../../initializers/database'
d03cd8bb 12import { sendUpdateActor } from '../../../lib/activitypub/send'
67ed6552 13import { updateActorAvatarFile } from '../../../lib/avatar'
fb719404 14import { getOriginalVideoFileTotalDailyFromUser, getOriginalVideoFileTotalFromUser, sendVerifyUserEmail } from '../../../lib/user'
d03cd8bb 15import {
993cef4b
C
16 asyncMiddleware,
17 asyncRetryTransactionMiddleware,
d03cd8bb
C
18 authenticate,
19 paginationValidator,
20 setDefaultPagination,
21 setDefaultSort,
8054669f 22 setDefaultVideosSort,
d03cd8bb
C
23 usersUpdateMeValidator,
24 usersVideoRatingValidator
25} from '../../../middlewares'
cf405589 26import { deleteMeValidator, videoImportsSortValidator, videosSortValidator } from '../../../middlewares/validators'
67ed6552
C
27import { updateAvatarValidator } from '../../../middlewares/validators/avatar'
28import { AccountModel } from '../../../models/account/account'
d03cd8bb
C
29import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
30import { UserModel } from '../../../models/account/user'
31import { VideoModel } from '../../../models/video/video'
d03cd8bb 32import { VideoImportModel } from '../../../models/video/video-import'
2dbc170d
C
33
34const auditLogger = auditLoggerFactory('users')
d03cd8bb 35
14e2014a 36const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
d03cd8bb
C
37
38const meRouter = express.Router()
39
40meRouter.get('/me',
41 authenticate,
42 asyncMiddleware(getUserInformation)
43)
44meRouter.delete('/me',
45 authenticate,
a1587156 46 deleteMeValidator,
d03cd8bb
C
47 asyncMiddleware(deleteMe)
48)
49
50meRouter.get('/me/video-quota-used',
51 authenticate,
52 asyncMiddleware(getUserVideoQuotaUsed)
53)
54
55meRouter.get('/me/videos/imports',
56 authenticate,
57 paginationValidator,
58 videoImportsSortValidator,
59 setDefaultSort,
60 setDefaultPagination,
61 asyncMiddleware(getUserVideoImports)
62)
63
64meRouter.get('/me/videos',
65 authenticate,
66 paginationValidator,
67 videosSortValidator,
8054669f 68 setDefaultVideosSort,
d03cd8bb
C
69 setDefaultPagination,
70 asyncMiddleware(getUserVideos)
71)
72
73meRouter.get('/me/videos/:videoId/rating',
74 authenticate,
75 asyncMiddleware(usersVideoRatingValidator),
76 asyncMiddleware(getUserVideoRating)
77)
78
79meRouter.put('/me',
80 authenticate,
a890d1e0 81 asyncMiddleware(usersUpdateMeValidator),
176e2114 82 asyncRetryTransactionMiddleware(updateMe)
d03cd8bb
C
83)
84
85meRouter.post('/me/avatar/pick',
86 authenticate,
87 reqAvatarFile,
88 updateAvatarValidator,
176e2114 89 asyncRetryTransactionMiddleware(updateMyAvatar)
d03cd8bb
C
90)
91
92// ---------------------------------------------------------------------------
93
94export {
95 meRouter
96}
97
98// ---------------------------------------------------------------------------
99
dae86118
C
100async function getUserVideos (req: express.Request, res: express.Response) {
101 const user = res.locals.oauth.token.User
d03cd8bb
C
102 const resultList = await VideoModel.listUserVideosForApi(
103 user.Account.id,
104 req.query.start as number,
105 req.query.count as number,
bf64ed41
RK
106 req.query.sort as VideoSortField,
107 req.query.search as string
d03cd8bb
C
108 )
109
110 const additionalAttributes = {
111 waitTranscoding: true,
112 state: true,
113 scheduledUpdate: true,
114 blacklistInfo: true
115 }
116 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
117}
118
dae86118
C
119async function getUserVideoImports (req: express.Request, res: express.Response) {
120 const user = res.locals.oauth.token.User
d03cd8bb
C
121 const resultList = await VideoImportModel.listUserVideoImportsForApi(
122 user.id,
123 req.query.start as number,
124 req.query.count as number,
125 req.query.sort
126 )
127
128 return res.json(getFormattedObjects(resultList.data, resultList.total))
129}
130
dae86118 131async function getUserInformation (req: express.Request, res: express.Response) {
d03cd8bb 132 // We did not load channels in res.locals.user
1acb9475 133 const user = await UserModel.loadForMeAPI(res.locals.oauth.token.user.id)
d03cd8bb 134
ac0868bc 135 return res.json(user.toMeFormattedJSON())
d03cd8bb
C
136}
137
dae86118 138async function getUserVideoQuotaUsed (req: express.Request, res: express.Response) {
ac0868bc 139 const user = res.locals.oauth.token.user
fb719404
C
140 const videoQuotaUsed = await getOriginalVideoFileTotalFromUser(user)
141 const videoQuotaUsedDaily = await getOriginalVideoFileTotalDailyFromUser(user)
d03cd8bb
C
142
143 const data: UserVideoQuota = {
bee0abff
FA
144 videoQuotaUsed,
145 videoQuotaUsedDaily
d03cd8bb
C
146 }
147 return res.json(data)
148}
149
dae86118 150async function getUserVideoRating (req: express.Request, res: express.Response) {
453e83ea 151 const videoId = res.locals.videoId.id
d03cd8bb
C
152 const accountId = +res.locals.oauth.token.User.Account.id
153
154 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
155 const rating = ratingObj ? ratingObj.type : 'none'
156
157 const json: FormattedUserVideoRate = {
158 videoId,
159 rating
160 }
06a05d5f 161 return res.json(json)
d03cd8bb
C
162}
163
164async function deleteMe (req: express.Request, res: express.Response) {
2dbc170d
C
165 const user = await UserModel.loadByIdWithChannels(res.locals.oauth.token.User.id)
166
167 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
d03cd8bb
C
168
169 await user.destroy()
170
2d53be02 171 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
d03cd8bb
C
172}
173
b426edd4 174async function updateMe (req: express.Request, res: express.Response) {
d03cd8bb 175 const body: UserUpdateMe = req.body
d1ab89de 176 let sendVerificationEmail = false
d03cd8bb 177
dae86118 178 const user = res.locals.oauth.token.user
d03cd8bb
C
179
180 if (body.password !== undefined) user.password = body.password
d03cd8bb 181 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
ed638e53 182 if (body.webTorrentEnabled !== undefined) user.webTorrentEnabled = body.webTorrentEnabled
d03cd8bb 183 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
6aa54148 184 if (body.autoPlayNextVideo !== undefined) user.autoPlayNextVideo = body.autoPlayNextVideo
bee29df8 185 if (body.autoPlayNextVideoPlaylist !== undefined) user.autoPlayNextVideoPlaylist = body.autoPlayNextVideoPlaylist
8b9a525a 186 if (body.videosHistoryEnabled !== undefined) user.videosHistoryEnabled = body.videosHistoryEnabled
3caf77d3 187 if (body.videoLanguages !== undefined) user.videoLanguages = body.videoLanguages
7cd4d2ba 188 if (body.theme !== undefined) user.theme = body.theme
43d0ea7f
C
189 if (body.noInstanceConfigWarningModal !== undefined) user.noInstanceConfigWarningModal = body.noInstanceConfigWarningModal
190 if (body.noWelcomeModal !== undefined) user.noWelcomeModal = body.noWelcomeModal
d03cd8bb 191
d1ab89de
C
192 if (body.email !== undefined) {
193 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
194 user.pendingEmail = body.email
195 sendVerificationEmail = true
196 } else {
197 user.email = body.email
198 }
199 }
200
589d9f55
C
201 await sequelizeTypescript.transaction(async t => {
202 await user.save({ transaction: t })
91411dba 203
589d9f55
C
204 if (body.displayName !== undefined || body.description !== undefined) {
205 const userAccount = await AccountModel.load(user.Account.id, t)
d03cd8bb 206
43d0ea7f
C
207 if (body.displayName !== undefined) userAccount.name = body.displayName
208 if (body.description !== undefined) userAccount.description = body.description
209 await userAccount.save({ transaction: t })
d03cd8bb 210
43d0ea7f 211 await sendUpdateActor(userAccount, t)
589d9f55
C
212 }
213 })
d03cd8bb 214
d1ab89de
C
215 if (sendVerificationEmail === true) {
216 await sendVerifyUserEmail(user, true)
217 }
218
2d53be02 219 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
d03cd8bb
C
220}
221
6040f87d 222async function updateMyAvatar (req: express.Request, res: express.Response) {
a1587156 223 const avatarPhysicalFile = req.files['avatarfile'][0]
dae86118 224 const user = res.locals.oauth.token.user
d03cd8bb 225
91411dba 226 const userAccount = await AccountModel.load(user.Account.id)
d03cd8bb 227
f201a749 228 const avatar = await updateActorAvatarFile(avatarPhysicalFile, userAccount)
91411dba 229
06a05d5f 230 return res.json({ avatar: avatar.toFormattedJSON() })
d03cd8bb 231}