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