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,
34 isUserVideoQuotaDailyValid,
35 isUserVideoQuotaValid,
36 isUserVideosHistoryEnabledValid,
37 isUserWebTorrentEnabledValid
38 } from '../../helpers/custom-validators/users'
39 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
40 import { OAuthTokenModel } from '../oauth/oauth-token'
41 import { getSort, throwIfNotValid } from '../utils'
42 import { VideoChannelModel } from '../video/video-channel'
43 import { AccountModel } from './account'
44 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
45 import { values } from 'lodash'
46 import { NSFW_POLICY_TYPES } from '../../initializers/constants'
47 import { clearCacheByUserId } from '../../lib/oauth-model'
48 import { UserNotificationSettingModel } from './user-notification-setting'
49 import { VideoModel } from '../video/video'
50 import { ActorModel } from '../activitypub/actor'
51 import { ActorFollowModel } from '../activitypub/actor-follow'
52 import { VideoImportModel } from '../video/video-import'
53 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
56 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
59 @DefaultScope(() => ({
66 model: UserNotificationSettingModel,
72 [ScopeNames.WITH_VIDEO_CHANNEL]: {
77 include: [ VideoChannelModel ]
80 model: UserNotificationSettingModel,
90 fields: [ 'username' ],
99 export class UserModel extends Model<UserModel> {
102 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
107 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
113 @Column(DataType.STRING(400))
118 @Column(DataType.STRING(400))
123 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
125 emailVerified: boolean
128 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
129 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
130 nsfwPolicy: NSFWPolicyType
134 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
136 webTorrentEnabled: boolean
140 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
142 videosHistoryEnabled: boolean
146 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
148 autoPlayVideo: boolean
151 @Default(UserAdminFlag.NONE)
152 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
154 adminFlags?: UserAdminFlag
158 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
164 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
166 blockedReason: string
169 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
174 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
175 @Column(DataType.BIGINT)
179 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
180 @Column(DataType.BIGINT)
181 videoQuotaDaily: number
189 @HasOne(() => AccountModel, {
190 foreignKey: 'userId',
194 Account: AccountModel
196 @HasOne(() => UserNotificationSettingModel, {
197 foreignKey: 'userId',
201 NotificationSetting: UserNotificationSettingModel
203 @HasMany(() => VideoImportModel, {
204 foreignKey: 'userId',
207 VideoImports: VideoImportModel[]
209 @HasMany(() => OAuthTokenModel, {
210 foreignKey: 'userId',
213 OAuthTokens: OAuthTokenModel[]
217 static cryptPasswordIfNeeded (instance: UserModel) {
218 if (instance.changed('password')) {
219 return cryptPassword(instance.password)
221 instance.password = hash
229 static removeTokenCache (instance: UserModel) {
230 return clearCacheByUserId(instance.id)
233 static countTotal () {
237 static listForApi (start: number, count: number, sort: string, search?: string) {
238 let where = undefined
244 [Op.iLike]: '%' + search + '%'
249 [ Op.iLike ]: '%' + search + '%'
256 const query: FindOptions = {
262 'SELECT COALESCE(SUM("size"), 0) ' +
264 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
265 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
266 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
267 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
268 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
278 order: getSort(sort),
282 return UserModel.findAndCountAll(query)
283 .then(({ rows, count }) => {
291 static listWithRight (right: UserRight) {
292 const roles = Object.keys(USER_ROLE_LABELS)
293 .map(k => parseInt(k, 10) as UserRole)
294 .filter(role => hasUserRight(role, right))
304 return UserModel.findAll(query)
307 static listUserSubscribersOf (actorId: number) {
311 model: UserNotificationSettingModel.unscoped(),
315 attributes: [ 'userId' ],
316 model: AccountModel.unscoped(),
321 model: ActorModel.unscoped(),
329 as: 'ActorFollowings',
330 model: ActorFollowModel.unscoped(),
333 targetActorId: actorId
343 return UserModel.unscoped().findAll(query)
346 static listByUsernames (usernames: string[]) {
353 return UserModel.findAll(query)
356 static loadById (id: number) {
357 return UserModel.findByPk(id)
360 static loadByUsername (username: string) {
367 return UserModel.findOne(query)
370 static loadByUsernameAndPopulateChannels (username: string) {
377 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
380 static loadByEmail (email: string) {
387 return UserModel.findOne(query)
390 static loadByUsernameOrEmail (username: string, email?: string) {
391 if (!email) email = username
395 [ Op.or ]: [ { username }, { email } ]
399 return UserModel.findOne(query)
402 static loadByVideoId (videoId: number) {
407 attributes: [ 'id' ],
408 model: AccountModel.unscoped(),
412 attributes: [ 'id' ],
413 model: VideoChannelModel.unscoped(),
417 attributes: [ 'id' ],
418 model: VideoModel.unscoped(),
430 return UserModel.findOne(query)
433 static loadByVideoImportId (videoImportId: number) {
438 attributes: [ 'id' ],
439 model: VideoImportModel.unscoped(),
447 return UserModel.findOne(query)
450 static loadByChannelActorId (videoChannelActorId: number) {
455 attributes: [ 'id' ],
456 model: AccountModel.unscoped(),
460 attributes: [ 'id' ],
461 model: VideoChannelModel.unscoped(),
463 actorId: videoChannelActorId
471 return UserModel.findOne(query)
474 static loadByAccountActorId (accountActorId: number) {
479 attributes: [ 'id' ],
480 model: AccountModel.unscoped(),
482 actorId: accountActorId
488 return UserModel.findOne(query)
491 static getOriginalVideoFileTotalFromUser (user: UserModel) {
492 // Don't use sequelize because we need to use a sub query
493 const query = UserModel.generateUserQuotaBaseSQL()
495 return UserModel.getTotalRawQuery(query, user.id)
498 // Returns cumulative size of all video files uploaded in the last 24 hours.
499 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
500 // Don't use sequelize because we need to use a sub query
501 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
503 return UserModel.getTotalRawQuery(query, user.id)
506 static async getStats () {
507 const totalUsers = await UserModel.count()
514 static autoComplete (search: string) {
518 [ Op.like ]: `%${search}%`
524 return UserModel.findAll(query)
525 .then(u => u.map(u => u.username))
528 hasRight (right: UserRight) {
529 return hasUserRight(this.role, right)
532 hasAdminFlag (flag: UserAdminFlag) {
533 return this.adminFlags & flag
536 isPasswordMatch (password: string) {
537 return comparePassword(password, this.password)
540 toFormattedJSON (parameters: { withAdminFlags?: boolean } = {}): User {
541 const videoQuotaUsed = this.get('videoQuotaUsed')
542 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
546 username: this.username,
548 pendingEmail: this.pendingEmail,
549 emailVerified: this.emailVerified,
550 nsfwPolicy: this.nsfwPolicy,
551 webTorrentEnabled: this.webTorrentEnabled,
552 videosHistoryEnabled: this.videosHistoryEnabled,
553 autoPlayVideo: this.autoPlayVideo,
555 roleLabel: USER_ROLE_LABELS[ this.role ],
556 videoQuota: this.videoQuota,
557 videoQuotaDaily: this.videoQuotaDaily,
558 createdAt: this.createdAt,
559 blocked: this.blocked,
560 blockedReason: this.blockedReason,
561 account: this.Account.toFormattedJSON(),
562 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
564 videoQuotaUsed: videoQuotaUsed !== undefined
565 ? parseInt(videoQuotaUsed + '', 10)
567 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
568 ? parseInt(videoQuotaUsedDaily + '', 10)
572 if (parameters.withAdminFlags) {
573 Object.assign(json, { adminFlags: this.adminFlags })
576 if (Array.isArray(this.Account.VideoChannels) === true) {
577 json.videoChannels = this.Account.VideoChannels
578 .map(c => c.toFormattedJSON())
580 if (v1.createdAt < v2.createdAt) return -1
581 if (v1.createdAt === v2.createdAt) return 0
590 async isAbleToUploadVideo (videoFile: { size: number }) {
591 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
593 const [ totalBytes, totalBytesDaily ] = await Promise.all([
594 UserModel.getOriginalVideoFileTotalFromUser(this),
595 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
598 const uploadedTotal = videoFile.size + totalBytes
599 const uploadedDaily = videoFile.size + totalBytesDaily
601 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
602 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
604 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
607 private static generateUserQuotaBaseSQL (where?: string) {
608 const andWhere = where ? 'AND ' + where : ''
610 return 'SELECT SUM("size") AS "total" ' +
612 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
613 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
614 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
615 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
616 'WHERE "account"."userId" = $userId ' + andWhere +
617 'GROUP BY "video"."id"' +
621 private static getTotalRawQuery (query: string, userId: number) {
624 type: QueryTypes.SELECT as QueryTypes.SELECT
627 return UserModel.sequelize.query<{ total: string }>(query, options)
628 .then(([ { total } ]) => {
629 if (total === null) return 0
631 return parseInt(total, 10)