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