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 isUserAutoPlayNextVideoValid,
29 isUserBlockedReasonValid,
31 isUserEmailVerifiedValid,
32 isUserNSFWPolicyValid,
37 isUserVideoQuotaDailyValid,
38 isUserVideoQuotaValid,
39 isUserVideosHistoryEnabledValid,
40 isUserWebTorrentEnabledValid,
42 } from '../../helpers/custom-validators/users'
43 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
44 import { OAuthTokenModel } from '../oauth/oauth-token'
45 import { getSort, throwIfNotValid } from '../utils'
46 import { VideoChannelModel } from '../video/video-channel'
47 import { AccountModel } from './account'
48 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
49 import { values } from 'lodash'
50 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
51 import { clearCacheByUserId } from '../../lib/oauth-model'
52 import { UserNotificationSettingModel } from './user-notification-setting'
53 import { VideoModel } from '../video/video'
54 import { ActorModel } from '../activitypub/actor'
55 import { ActorFollowModel } from '../activitypub/actor-follow'
56 import { VideoImportModel } from '../video/video-import'
57 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
58 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
59 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
60 import * as Bluebird from 'bluebird'
65 MUserNotifSettingChannelDefault,
66 MUserWithNotificationSetting
67 } from '@server/typings/models'
70 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
73 @DefaultScope(() => ({
80 model: UserNotificationSettingModel,
86 [ScopeNames.WITH_VIDEO_CHANNEL]: {
91 include: [ VideoChannelModel ]
94 model: UserNotificationSettingModel,
104 fields: [ 'username' ],
113 export class UserModel extends Model<UserModel> {
116 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
121 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
127 @Column(DataType.STRING(400))
132 @Column(DataType.STRING(400))
137 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
139 emailVerified: boolean
142 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
143 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
144 nsfwPolicy: NSFWPolicyType
148 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
150 webTorrentEnabled: boolean
154 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
156 videosHistoryEnabled: boolean
160 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
162 autoPlayVideo: boolean
166 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
168 autoPlayNextVideo: boolean
172 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
173 @Column(DataType.ARRAY(DataType.STRING))
174 videoLanguages: string[]
177 @Default(UserAdminFlag.NONE)
178 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
180 adminFlags?: UserAdminFlag
184 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
190 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
192 blockedReason: string
195 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
200 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
201 @Column(DataType.BIGINT)
205 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
206 @Column(DataType.BIGINT)
207 videoQuotaDaily: number
210 @Default(DEFAULT_THEME_NAME)
211 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
218 'UserNoInstanceConfigWarningModal',
219 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
222 noInstanceConfigWarningModal: boolean
227 'UserNoInstanceConfigWarningModal',
228 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
231 noWelcomeModal: boolean
239 @HasOne(() => AccountModel, {
240 foreignKey: 'userId',
244 Account: AccountModel
246 @HasOne(() => UserNotificationSettingModel, {
247 foreignKey: 'userId',
251 NotificationSetting: UserNotificationSettingModel
253 @HasMany(() => VideoImportModel, {
254 foreignKey: 'userId',
257 VideoImports: VideoImportModel[]
259 @HasMany(() => OAuthTokenModel, {
260 foreignKey: 'userId',
263 OAuthTokens: OAuthTokenModel[]
267 static cryptPasswordIfNeeded (instance: UserModel) {
268 if (instance.changed('password')) {
269 return cryptPassword(instance.password)
271 instance.password = hash
279 static removeTokenCache (instance: UserModel) {
280 return clearCacheByUserId(instance.id)
283 static countTotal () {
287 static listForApi (start: number, count: number, sort: string, search?: string) {
288 let where = undefined
294 [Op.iLike]: '%' + search + '%'
299 [ Op.iLike ]: '%' + search + '%'
306 const query: FindOptions = {
312 'SELECT COALESCE(SUM("size"), 0) ' +
314 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
315 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
316 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
317 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
318 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
328 order: getSort(sort),
332 return UserModel.findAndCountAll(query)
333 .then(({ rows, count }) => {
341 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
342 const roles = Object.keys(USER_ROLE_LABELS)
343 .map(k => parseInt(k, 10) as UserRole)
344 .filter(role => hasUserRight(role, right))
354 return UserModel.findAll(query)
357 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
361 model: UserNotificationSettingModel.unscoped(),
365 attributes: [ 'userId' ],
366 model: AccountModel.unscoped(),
371 model: ActorModel.unscoped(),
379 as: 'ActorFollowings',
380 model: ActorFollowModel.unscoped(),
383 targetActorId: actorId
393 return UserModel.unscoped().findAll(query)
396 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
403 return UserModel.findAll(query)
406 static loadById (id: number): Bluebird<MUserDefault> {
407 return UserModel.findByPk(id)
410 static loadByUsername (username: string): Bluebird<MUserDefault> {
413 username: { [ Op.iLike ]: username }
417 return UserModel.findOne(query)
420 static loadByUsernameAndPopulateChannels (username: string): Bluebird<MUserNotifSettingChannelDefault> {
423 username: { [ Op.iLike ]: username }
427 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
430 static loadByEmail (email: string): Bluebird<MUserDefault> {
437 return UserModel.findOne(query)
440 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
441 if (!email) email = username
445 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
449 return UserModel.findOne(query)
452 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
457 attributes: [ 'id' ],
458 model: AccountModel.unscoped(),
462 attributes: [ 'id' ],
463 model: VideoChannelModel.unscoped(),
467 attributes: [ 'id' ],
468 model: VideoModel.unscoped(),
480 return UserModel.findOne(query)
483 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
488 attributes: [ 'id' ],
489 model: VideoImportModel.unscoped(),
497 return UserModel.findOne(query)
500 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
505 attributes: [ 'id' ],
506 model: AccountModel.unscoped(),
510 attributes: [ 'id' ],
511 model: VideoChannelModel.unscoped(),
513 actorId: videoChannelActorId
521 return UserModel.findOne(query)
524 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
529 attributes: [ 'id' ],
530 model: AccountModel.unscoped(),
532 actorId: accountActorId
538 return UserModel.findOne(query)
541 static getOriginalVideoFileTotalFromUser (user: MUserId) {
542 // Don't use sequelize because we need to use a sub query
543 const query = UserModel.generateUserQuotaBaseSQL()
545 return UserModel.getTotalRawQuery(query, user.id)
548 // Returns cumulative size of all video files uploaded in the last 24 hours.
549 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
550 // Don't use sequelize because we need to use a sub query
551 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
553 return UserModel.getTotalRawQuery(query, user.id)
556 static async getStats () {
557 const totalUsers = await UserModel.count()
564 static autoComplete (search: string) {
568 [ Op.like ]: `%${search}%`
574 return UserModel.findAll(query)
575 .then(u => u.map(u => u.username))
578 hasRight (right: UserRight) {
579 return hasUserRight(this.role, right)
582 hasAdminFlag (flag: UserAdminFlag) {
583 return this.adminFlags & flag
586 isPasswordMatch (password: string) {
587 return comparePassword(password, this.password)
590 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
591 const videoQuotaUsed = this.get('videoQuotaUsed')
592 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
596 username: this.username,
598 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
600 pendingEmail: this.pendingEmail,
601 emailVerified: this.emailVerified,
603 nsfwPolicy: this.nsfwPolicy,
604 webTorrentEnabled: this.webTorrentEnabled,
605 videosHistoryEnabled: this.videosHistoryEnabled,
606 autoPlayVideo: this.autoPlayVideo,
607 autoPlayNextVideo: this.autoPlayNextVideo,
608 videoLanguages: this.videoLanguages,
611 roleLabel: USER_ROLE_LABELS[ this.role ],
613 videoQuota: this.videoQuota,
614 videoQuotaDaily: this.videoQuotaDaily,
615 videoQuotaUsed: videoQuotaUsed !== undefined
616 ? parseInt(videoQuotaUsed + '', 10)
618 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
619 ? parseInt(videoQuotaUsedDaily + '', 10)
622 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
623 noWelcomeModal: this.noWelcomeModal,
625 blocked: this.blocked,
626 blockedReason: this.blockedReason,
628 account: this.Account.toFormattedJSON(),
630 notificationSettings: this.NotificationSetting
631 ? this.NotificationSetting.toFormattedJSON()
636 createdAt: this.createdAt
639 if (parameters.withAdminFlags) {
640 Object.assign(json, { adminFlags: this.adminFlags })
643 if (Array.isArray(this.Account.VideoChannels) === true) {
644 json.videoChannels = this.Account.VideoChannels
645 .map(c => c.toFormattedJSON())
647 if (v1.createdAt < v2.createdAt) return -1
648 if (v1.createdAt === v2.createdAt) return 0
657 async isAbleToUploadVideo (videoFile: { size: number }) {
658 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
660 const [ totalBytes, totalBytesDaily ] = await Promise.all([
661 UserModel.getOriginalVideoFileTotalFromUser(this),
662 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
665 const uploadedTotal = videoFile.size + totalBytes
666 const uploadedDaily = videoFile.size + totalBytesDaily
668 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
669 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
671 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
674 private static generateUserQuotaBaseSQL (where?: string) {
675 const andWhere = where ? 'AND ' + where : ''
677 return 'SELECT SUM("size") AS "total" ' +
679 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
680 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
681 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
682 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
683 'WHERE "account"."userId" = $userId ' + andWhere +
684 'GROUP BY "video"."id"' +
688 private static getTotalRawQuery (query: string, userId: number) {
691 type: QueryTypes.SELECT as QueryTypes.SELECT
694 return UserModel.sequelize.query<{ total: string }>(query, options)
695 .then(([ { total } ]) => {
696 if (total === null) return 0
698 return parseInt(total, 10)