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 isUserAdminFlagsValid,
26 isUserAutoPlayVideoValid,
27 isUserBlockedReasonValid,
29 isUserEmailVerifiedValid,
30 isUserNSFWPolicyValid,
35 isUserVideoQuotaDailyValid,
36 isUserVideoQuotaValid,
37 isUserVideosHistoryEnabledValid,
38 isUserWebTorrentEnabledValid
39 } from '../../helpers/custom-validators/users'
40 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
41 import { OAuthTokenModel } from '../oauth/oauth-token'
42 import { getSort, throwIfNotValid } from '../utils'
43 import { VideoChannelModel } from '../video/video-channel'
44 import { AccountModel } from './account'
45 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
46 import { values } from 'lodash'
47 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
48 import { clearCacheByUserId } from '../../lib/oauth-model'
49 import { UserNotificationSettingModel } from './user-notification-setting'
50 import { VideoModel } from '../video/video'
51 import { ActorModel } from '../activitypub/actor'
52 import { ActorFollowModel } from '../activitypub/actor-follow'
53 import { VideoImportModel } from '../video/video-import'
54 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
55 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
56 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
59 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
62 @DefaultScope(() => ({
69 model: UserNotificationSettingModel,
75 [ScopeNames.WITH_VIDEO_CHANNEL]: {
80 include: [ VideoChannelModel ]
83 model: UserNotificationSettingModel,
93 fields: [ 'username' ],
102 export class UserModel extends Model<UserModel> {
105 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
110 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
116 @Column(DataType.STRING(400))
121 @Column(DataType.STRING(400))
126 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
128 emailVerified: boolean
131 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
132 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
133 nsfwPolicy: NSFWPolicyType
137 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
139 webTorrentEnabled: boolean
143 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
145 videosHistoryEnabled: boolean
149 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
151 autoPlayVideo: boolean
155 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
156 @Column(DataType.ARRAY(DataType.STRING))
157 videoLanguages: string[]
160 @Default(UserAdminFlag.NONE)
161 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
163 adminFlags?: UserAdminFlag
167 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
173 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
175 blockedReason: string
178 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
183 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
184 @Column(DataType.BIGINT)
188 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
189 @Column(DataType.BIGINT)
190 videoQuotaDaily: number
193 @Default(DEFAULT_THEME_NAME)
194 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
204 @HasOne(() => AccountModel, {
205 foreignKey: 'userId',
209 Account: AccountModel
211 @HasOne(() => UserNotificationSettingModel, {
212 foreignKey: 'userId',
216 NotificationSetting: UserNotificationSettingModel
218 @HasMany(() => VideoImportModel, {
219 foreignKey: 'userId',
222 VideoImports: VideoImportModel[]
224 @HasMany(() => OAuthTokenModel, {
225 foreignKey: 'userId',
228 OAuthTokens: OAuthTokenModel[]
232 static cryptPasswordIfNeeded (instance: UserModel) {
233 if (instance.changed('password')) {
234 return cryptPassword(instance.password)
236 instance.password = hash
244 static removeTokenCache (instance: UserModel) {
245 return clearCacheByUserId(instance.id)
248 static countTotal () {
252 static listForApi (start: number, count: number, sort: string, search?: string) {
253 let where = undefined
259 [Op.iLike]: '%' + search + '%'
264 [ Op.iLike ]: '%' + search + '%'
271 const query: FindOptions = {
277 'SELECT COALESCE(SUM("size"), 0) ' +
279 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
280 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
281 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
282 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
283 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
293 order: getSort(sort),
297 return UserModel.findAndCountAll(query)
298 .then(({ rows, count }) => {
306 static listWithRight (right: UserRight) {
307 const roles = Object.keys(USER_ROLE_LABELS)
308 .map(k => parseInt(k, 10) as UserRole)
309 .filter(role => hasUserRight(role, right))
319 return UserModel.findAll(query)
322 static listUserSubscribersOf (actorId: number) {
326 model: UserNotificationSettingModel.unscoped(),
330 attributes: [ 'userId' ],
331 model: AccountModel.unscoped(),
336 model: ActorModel.unscoped(),
344 as: 'ActorFollowings',
345 model: ActorFollowModel.unscoped(),
348 targetActorId: actorId
358 return UserModel.unscoped().findAll(query)
361 static listByUsernames (usernames: string[]) {
368 return UserModel.findAll(query)
371 static loadById (id: number) {
372 return UserModel.findByPk(id)
375 static loadByUsername (username: string) {
378 username: { [ Op.iLike ]: username }
382 return UserModel.findOne(query)
385 static loadByUsernameAndPopulateChannels (username: string) {
388 username: { [ Op.iLike ]: username }
392 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
395 static loadByEmail (email: string) {
402 return UserModel.findOne(query)
405 static loadByUsernameOrEmail (username: string, email?: string) {
406 if (!email) email = username
410 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
414 return UserModel.findOne(query)
417 static loadByVideoId (videoId: number) {
422 attributes: [ 'id' ],
423 model: AccountModel.unscoped(),
427 attributes: [ 'id' ],
428 model: VideoChannelModel.unscoped(),
432 attributes: [ 'id' ],
433 model: VideoModel.unscoped(),
445 return UserModel.findOne(query)
448 static loadByVideoImportId (videoImportId: number) {
453 attributes: [ 'id' ],
454 model: VideoImportModel.unscoped(),
462 return UserModel.findOne(query)
465 static loadByChannelActorId (videoChannelActorId: number) {
470 attributes: [ 'id' ],
471 model: AccountModel.unscoped(),
475 attributes: [ 'id' ],
476 model: VideoChannelModel.unscoped(),
478 actorId: videoChannelActorId
486 return UserModel.findOne(query)
489 static loadByAccountActorId (accountActorId: number) {
494 attributes: [ 'id' ],
495 model: AccountModel.unscoped(),
497 actorId: accountActorId
503 return UserModel.findOne(query)
506 static getOriginalVideoFileTotalFromUser (user: UserModel) {
507 // Don't use sequelize because we need to use a sub query
508 const query = UserModel.generateUserQuotaBaseSQL()
510 return UserModel.getTotalRawQuery(query, user.id)
513 // Returns cumulative size of all video files uploaded in the last 24 hours.
514 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
515 // Don't use sequelize because we need to use a sub query
516 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
518 return UserModel.getTotalRawQuery(query, user.id)
521 static async getStats () {
522 const totalUsers = await UserModel.count()
529 static autoComplete (search: string) {
533 [ Op.like ]: `%${search}%`
539 return UserModel.findAll(query)
540 .then(u => u.map(u => u.username))
543 hasRight (right: UserRight) {
544 return hasUserRight(this.role, right)
547 hasAdminFlag (flag: UserAdminFlag) {
548 return this.adminFlags & flag
551 isPasswordMatch (password: string) {
552 return comparePassword(password, this.password)
555 toFormattedJSON (parameters: { withAdminFlags?: boolean } = {}): User {
556 const videoQuotaUsed = this.get('videoQuotaUsed')
557 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
561 username: this.username,
563 pendingEmail: this.pendingEmail,
564 emailVerified: this.emailVerified,
565 nsfwPolicy: this.nsfwPolicy,
566 webTorrentEnabled: this.webTorrentEnabled,
567 videosHistoryEnabled: this.videosHistoryEnabled,
568 autoPlayVideo: this.autoPlayVideo,
569 videoLanguages: this.videoLanguages,
571 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
572 roleLabel: USER_ROLE_LABELS[ this.role ],
573 videoQuota: this.videoQuota,
574 videoQuotaDaily: this.videoQuotaDaily,
575 createdAt: this.createdAt,
576 blocked: this.blocked,
577 blockedReason: this.blockedReason,
578 account: this.Account.toFormattedJSON(),
579 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
581 videoQuotaUsed: videoQuotaUsed !== undefined
582 ? parseInt(videoQuotaUsed + '', 10)
584 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
585 ? parseInt(videoQuotaUsedDaily + '', 10)
589 if (parameters.withAdminFlags) {
590 Object.assign(json, { adminFlags: this.adminFlags })
593 if (Array.isArray(this.Account.VideoChannels) === true) {
594 json.videoChannels = this.Account.VideoChannels
595 .map(c => c.toFormattedJSON())
597 if (v1.createdAt < v2.createdAt) return -1
598 if (v1.createdAt === v2.createdAt) return 0
607 async isAbleToUploadVideo (videoFile: { size: number }) {
608 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
610 const [ totalBytes, totalBytesDaily ] = await Promise.all([
611 UserModel.getOriginalVideoFileTotalFromUser(this),
612 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
615 const uploadedTotal = videoFile.size + totalBytes
616 const uploadedDaily = videoFile.size + totalBytesDaily
618 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
619 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
621 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
624 private static generateUserQuotaBaseSQL (where?: string) {
625 const andWhere = where ? 'AND ' + where : ''
627 return 'SELECT SUM("size") AS "total" ' +
629 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
630 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
631 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
632 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
633 'WHERE "account"."userId" = $userId ' + andWhere +
634 'GROUP BY "video"."id"' +
638 private static getTotalRawQuery (query: string, userId: number) {
641 type: QueryTypes.SELECT as QueryTypes.SELECT
644 return UserModel.sequelize.query<{ total: string }>(query, options)
645 .then(([ { total } ]) => {
646 if (total === null) return 0
648 return parseInt(total, 10)