1 import { FindOptions, literal, Op, QueryTypes } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isNoInstanceConfigWarningModal,
26 isUserAdminFlagsValid,
27 isUserAutoPlayVideoValid,
28 isUserBlockedReasonValid,
30 isUserEmailVerifiedValid,
31 isUserNSFWPolicyValid,
36 isUserVideoQuotaDailyValid,
37 isUserVideoQuotaValid,
38 isUserVideosHistoryEnabledValid,
39 isUserWebTorrentEnabledValid,
41 } from '../../helpers/custom-validators/users'
42 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
43 import { OAuthTokenModel } from '../oauth/oauth-token'
44 import { getSort, throwIfNotValid } from '../utils'
45 import { VideoChannelModel } from '../video/video-channel'
46 import { AccountModel } from './account'
47 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
48 import { values } from 'lodash'
49 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
50 import { clearCacheByUserId } from '../../lib/oauth-model'
51 import { UserNotificationSettingModel } from './user-notification-setting'
52 import { VideoModel } from '../video/video'
53 import { ActorModel } from '../activitypub/actor'
54 import { ActorFollowModel } from '../activitypub/actor-follow'
55 import { VideoImportModel } from '../video/video-import'
56 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
57 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
58 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
59 import * as Bluebird from 'bluebird'
64 MUserNotifSettingChannelDefault,
65 MUserWithNotificationSetting
66 } from '@server/typings/models'
69 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
72 @DefaultScope(() => ({
79 model: UserNotificationSettingModel,
85 [ScopeNames.WITH_VIDEO_CHANNEL]: {
90 include: [ VideoChannelModel ]
93 model: UserNotificationSettingModel,
103 fields: [ 'username' ],
112 export class UserModel extends Model<UserModel> {
115 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
120 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
126 @Column(DataType.STRING(400))
131 @Column(DataType.STRING(400))
136 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
138 emailVerified: boolean
141 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
142 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
143 nsfwPolicy: NSFWPolicyType
147 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
149 webTorrentEnabled: boolean
153 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
155 videosHistoryEnabled: boolean
159 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
161 autoPlayVideo: boolean
165 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
166 @Column(DataType.ARRAY(DataType.STRING))
167 videoLanguages: string[]
170 @Default(UserAdminFlag.NONE)
171 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
173 adminFlags?: UserAdminFlag
177 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
183 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
185 blockedReason: string
188 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
193 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
194 @Column(DataType.BIGINT)
198 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
199 @Column(DataType.BIGINT)
200 videoQuotaDaily: number
203 @Default(DEFAULT_THEME_NAME)
204 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
211 'UserNoInstanceConfigWarningModal',
212 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
215 noInstanceConfigWarningModal: boolean
220 'UserNoInstanceConfigWarningModal',
221 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
224 noWelcomeModal: boolean
232 @HasOne(() => AccountModel, {
233 foreignKey: 'userId',
237 Account: AccountModel
239 @HasOne(() => UserNotificationSettingModel, {
240 foreignKey: 'userId',
244 NotificationSetting: UserNotificationSettingModel
246 @HasMany(() => VideoImportModel, {
247 foreignKey: 'userId',
250 VideoImports: VideoImportModel[]
252 @HasMany(() => OAuthTokenModel, {
253 foreignKey: 'userId',
256 OAuthTokens: OAuthTokenModel[]
260 static cryptPasswordIfNeeded (instance: UserModel) {
261 if (instance.changed('password')) {
262 return cryptPassword(instance.password)
264 instance.password = hash
272 static removeTokenCache (instance: UserModel) {
273 return clearCacheByUserId(instance.id)
276 static countTotal () {
280 static listForApi (start: number, count: number, sort: string, search?: string) {
281 let where = undefined
287 [Op.iLike]: '%' + search + '%'
292 [ Op.iLike ]: '%' + search + '%'
299 const query: FindOptions = {
305 'SELECT COALESCE(SUM("size"), 0) ' +
307 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
308 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
309 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
310 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
311 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
321 order: getSort(sort),
325 return UserModel.findAndCountAll(query)
326 .then(({ rows, count }) => {
334 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
335 const roles = Object.keys(USER_ROLE_LABELS)
336 .map(k => parseInt(k, 10) as UserRole)
337 .filter(role => hasUserRight(role, right))
347 return UserModel.findAll(query)
350 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
354 model: UserNotificationSettingModel.unscoped(),
358 attributes: [ 'userId' ],
359 model: AccountModel.unscoped(),
364 model: ActorModel.unscoped(),
372 as: 'ActorFollowings',
373 model: ActorFollowModel.unscoped(),
376 targetActorId: actorId
386 return UserModel.unscoped().findAll(query)
389 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
396 return UserModel.findAll(query)
399 static loadById (id: number): Bluebird<MUserDefault> {
400 return UserModel.findByPk(id)
403 static loadByUsername (username: string): Bluebird<MUserDefault> {
406 username: { [ Op.iLike ]: username }
410 return UserModel.findOne(query)
413 static loadByUsernameAndPopulateChannels (username: string): Bluebird<MUserNotifSettingChannelDefault> {
416 username: { [ Op.iLike ]: username }
420 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
423 static loadByEmail (email: string): Bluebird<MUserDefault> {
430 return UserModel.findOne(query)
433 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
434 if (!email) email = username
438 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
442 return UserModel.findOne(query)
445 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
450 attributes: [ 'id' ],
451 model: AccountModel.unscoped(),
455 attributes: [ 'id' ],
456 model: VideoChannelModel.unscoped(),
460 attributes: [ 'id' ],
461 model: VideoModel.unscoped(),
473 return UserModel.findOne(query)
476 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
481 attributes: [ 'id' ],
482 model: VideoImportModel.unscoped(),
490 return UserModel.findOne(query)
493 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
498 attributes: [ 'id' ],
499 model: AccountModel.unscoped(),
503 attributes: [ 'id' ],
504 model: VideoChannelModel.unscoped(),
506 actorId: videoChannelActorId
514 return UserModel.findOne(query)
517 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
522 attributes: [ 'id' ],
523 model: AccountModel.unscoped(),
525 actorId: accountActorId
531 return UserModel.findOne(query)
534 static getOriginalVideoFileTotalFromUser (user: MUserId) {
535 // Don't use sequelize because we need to use a sub query
536 const query = UserModel.generateUserQuotaBaseSQL()
538 return UserModel.getTotalRawQuery(query, user.id)
541 // Returns cumulative size of all video files uploaded in the last 24 hours.
542 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
543 // Don't use sequelize because we need to use a sub query
544 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
546 return UserModel.getTotalRawQuery(query, user.id)
549 static async getStats () {
550 const totalUsers = await UserModel.count()
557 static autoComplete (search: string) {
561 [ Op.like ]: `%${search}%`
567 return UserModel.findAll(query)
568 .then(u => u.map(u => u.username))
571 hasRight (right: UserRight) {
572 return hasUserRight(this.role, right)
575 hasAdminFlag (flag: UserAdminFlag) {
576 return this.adminFlags & flag
579 isPasswordMatch (password: string) {
580 return comparePassword(password, this.password)
583 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
584 const videoQuotaUsed = this.get('videoQuotaUsed')
585 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
589 username: this.username,
591 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
593 pendingEmail: this.pendingEmail,
594 emailVerified: this.emailVerified,
596 nsfwPolicy: this.nsfwPolicy,
597 webTorrentEnabled: this.webTorrentEnabled,
598 videosHistoryEnabled: this.videosHistoryEnabled,
599 autoPlayVideo: this.autoPlayVideo,
600 videoLanguages: this.videoLanguages,
603 roleLabel: USER_ROLE_LABELS[ this.role ],
605 videoQuota: this.videoQuota,
606 videoQuotaDaily: this.videoQuotaDaily,
607 videoQuotaUsed: videoQuotaUsed !== undefined
608 ? parseInt(videoQuotaUsed + '', 10)
610 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
611 ? parseInt(videoQuotaUsedDaily + '', 10)
614 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
615 noWelcomeModal: this.noWelcomeModal,
617 blocked: this.blocked,
618 blockedReason: this.blockedReason,
620 account: this.Account.toFormattedJSON(),
622 notificationSettings: this.NotificationSetting
623 ? this.NotificationSetting.toFormattedJSON()
628 createdAt: this.createdAt
631 if (parameters.withAdminFlags) {
632 Object.assign(json, { adminFlags: this.adminFlags })
635 if (Array.isArray(this.Account.VideoChannels) === true) {
636 json.videoChannels = this.Account.VideoChannels
637 .map(c => c.toFormattedJSON())
639 if (v1.createdAt < v2.createdAt) return -1
640 if (v1.createdAt === v2.createdAt) return 0
649 async isAbleToUploadVideo (videoFile: { size: number }) {
650 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
652 const [ totalBytes, totalBytesDaily ] = await Promise.all([
653 UserModel.getOriginalVideoFileTotalFromUser(this),
654 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
657 const uploadedTotal = videoFile.size + totalBytes
658 const uploadedDaily = videoFile.size + totalBytesDaily
660 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
661 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
663 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
666 private static generateUserQuotaBaseSQL (where?: string) {
667 const andWhere = where ? 'AND ' + where : ''
669 return 'SELECT SUM("size") AS "total" ' +
671 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
672 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
673 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
674 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
675 'WHERE "account"."userId" = $userId ' + andWhere +
676 'GROUP BY "video"."id"' +
680 private static getTotalRawQuery (query: string, userId: number) {
683 type: QueryTypes.SELECT as QueryTypes.SELECT
686 return UserModel.sequelize.query<{ total: string }>(query, options)
687 .then(([ { total } ]) => {
688 if (total === null) return 0
690 return parseInt(total, 10)