me.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
  27. import { VideoImportModel } from '../../../models/video/video-import'
  28. import { AccountModel } from '../../../models/account/account'
  29. import { CONFIG } from '../../../initializers/config'
  30. import { sequelizeTypescript } from '../../../initializers/database'
  31. import { sendVerifyUserEmail } from '../../../lib/user'
  32. const auditLogger = auditLoggerFactory('users-me')
  33. const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
  34. const meRouter = express.Router()
  35. meRouter.get('/me',
  36. authenticate,
  37. asyncMiddleware(getUserInformation)
  38. )
  39. meRouter.delete('/me',
  40. authenticate,
  41. asyncMiddleware(deleteMeValidator),
  42. asyncMiddleware(deleteMe)
  43. )
  44. meRouter.get('/me/video-quota-used',
  45. authenticate,
  46. asyncMiddleware(getUserVideoQuotaUsed)
  47. )
  48. meRouter.get('/me/videos/imports',
  49. authenticate,
  50. paginationValidator,
  51. videoImportsSortValidator,
  52. setDefaultSort,
  53. setDefaultPagination,
  54. asyncMiddleware(getUserVideoImports)
  55. )
  56. meRouter.get('/me/videos',
  57. authenticate,
  58. paginationValidator,
  59. videosSortValidator,
  60. setDefaultSort,
  61. setDefaultPagination,
  62. asyncMiddleware(getUserVideos)
  63. )
  64. meRouter.get('/me/videos/:videoId/rating',
  65. authenticate,
  66. asyncMiddleware(usersVideoRatingValidator),
  67. asyncMiddleware(getUserVideoRating)
  68. )
  69. meRouter.put('/me',
  70. authenticate,
  71. asyncMiddleware(usersUpdateMeValidator),
  72. asyncRetryTransactionMiddleware(updateMe)
  73. )
  74. meRouter.post('/me/avatar/pick',
  75. authenticate,
  76. reqAvatarFile,
  77. updateAvatarValidator,
  78. asyncRetryTransactionMiddleware(updateMyAvatar)
  79. )
  80. // ---------------------------------------------------------------------------
  81. export {
  82. meRouter
  83. }
  84. // ---------------------------------------------------------------------------
  85. async function getUserVideos (req: express.Request, res: express.Response) {
  86. const user = res.locals.oauth.token.User
  87. const resultList = await VideoModel.listUserVideosForApi(
  88. user.Account.id,
  89. req.query.start as number,
  90. req.query.count as number,
  91. req.query.sort as VideoSortField
  92. )
  93. const additionalAttributes = {
  94. waitTranscoding: true,
  95. state: true,
  96. scheduledUpdate: true,
  97. blacklistInfo: true
  98. }
  99. return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
  100. }
  101. async function getUserVideoImports (req: express.Request, res: express.Response) {
  102. const user = res.locals.oauth.token.User
  103. const resultList = await VideoImportModel.listUserVideoImportsForApi(
  104. user.id,
  105. req.query.start as number,
  106. req.query.count as number,
  107. req.query.sort
  108. )
  109. return res.json(getFormattedObjects(resultList.data, resultList.total))
  110. }
  111. async function getUserInformation (req: express.Request, res: express.Response) {
  112. // We did not load channels in res.locals.user
  113. const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
  114. return res.json(user.toFormattedJSON({}))
  115. }
  116. async function getUserVideoQuotaUsed (req: express.Request, res: express.Response) {
  117. // We did not load channels in res.locals.user
  118. const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
  119. const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
  120. const videoQuotaUsedDaily = await UserModel.getOriginalVideoFileTotalDailyFromUser(user)
  121. const data: UserVideoQuota = {
  122. videoQuotaUsed,
  123. videoQuotaUsedDaily
  124. }
  125. return res.json(data)
  126. }
  127. async function getUserVideoRating (req: express.Request, res: express.Response) {
  128. const videoId = res.locals.video.id
  129. const accountId = +res.locals.oauth.token.User.Account.id
  130. const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
  131. const rating = ratingObj ? ratingObj.type : 'none'
  132. const json: FormattedUserVideoRate = {
  133. videoId,
  134. rating
  135. }
  136. return res.json(json)
  137. }
  138. async function deleteMe (req: express.Request, res: express.Response) {
  139. const user = res.locals.oauth.token.User
  140. await user.destroy()
  141. auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON({})))
  142. return res.sendStatus(204)
  143. }
  144. async function updateMe (req: express.Request, res: express.Response) {
  145. const body: UserUpdateMe = req.body
  146. let sendVerificationEmail = false
  147. const user = res.locals.oauth.token.user
  148. const oldUserAuditView = new UserAuditView(user.toFormattedJSON({}))
  149. if (body.password !== undefined) user.password = body.password
  150. if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
  151. if (body.webTorrentEnabled !== undefined) user.webTorrentEnabled = body.webTorrentEnabled
  152. if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
  153. if (body.videosHistoryEnabled !== undefined) user.videosHistoryEnabled = body.videosHistoryEnabled
  154. if (body.videoLanguages !== undefined) user.videoLanguages = body.videoLanguages
  155. if (body.email !== undefined) {
  156. if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
  157. user.pendingEmail = body.email
  158. sendVerificationEmail = true
  159. } else {
  160. user.email = body.email
  161. }
  162. }
  163. await sequelizeTypescript.transaction(async t => {
  164. const userAccount = await AccountModel.load(user.Account.id)
  165. await user.save({ transaction: t })
  166. if (body.displayName !== undefined) userAccount.name = body.displayName
  167. if (body.description !== undefined) userAccount.description = body.description
  168. await userAccount.save({ transaction: t })
  169. await sendUpdateActor(userAccount, t)
  170. auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON({})), oldUserAuditView)
  171. })
  172. if (sendVerificationEmail === true) {
  173. await sendVerifyUserEmail(user, true)
  174. }
  175. return res.sendStatus(204)
  176. }
  177. async function updateMyAvatar (req: express.Request, res: express.Response) {
  178. const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
  179. const user = res.locals.oauth.token.user
  180. const oldUserAuditView = new UserAuditView(user.toFormattedJSON({}))
  181. const userAccount = await AccountModel.load(user.Account.id)
  182. const avatar = await updateActorAvatarFile(avatarPhysicalFile, userAccount)
  183. auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON({})), oldUserAuditView)
  184. return res.json({ avatar: avatar.toFormattedJSON() })
  185. }