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