1 import { FindOptions, literal, Op, QueryTypes } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight, VideoPrivacy } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isNoInstanceConfigWarningModal,
26 isUserAdminFlagsValid,
27 isUserAutoPlayVideoValid,
28 isUserAutoPlayNextVideoValid,
29 isUserAutoPlayNextVideoPlaylistValid,
30 isUserBlockedReasonValid,
32 isUserEmailVerifiedValid,
33 isUserNSFWPolicyValid,
38 isUserVideoQuotaDailyValid,
39 isUserVideoQuotaValid,
40 isUserVideosHistoryEnabledValid,
41 isUserWebTorrentEnabledValid,
43 } from '../../helpers/custom-validators/users'
44 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
45 import { OAuthTokenModel } from '../oauth/oauth-token'
46 import { getSort, throwIfNotValid } from '../utils'
47 import { VideoChannelModel } from '../video/video-channel'
48 import { AccountModel } from './account'
49 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
50 import { values } from 'lodash'
51 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
52 import { clearCacheByUserId } from '../../lib/oauth-model'
53 import { UserNotificationSettingModel } from './user-notification-setting'
54 import { VideoModel } from '../video/video'
55 import { ActorModel } from '../activitypub/actor'
56 import { ActorFollowModel } from '../activitypub/actor-follow'
57 import { VideoImportModel } from '../video/video-import'
58 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
59 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
60 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
61 import * as Bluebird from 'bluebird'
66 MUserNotifSettingChannelDefault,
67 MUserWithNotificationSetting, MVideoFullLight
68 } from '@server/typings/models'
71 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
74 @DefaultScope(() => ({
81 model: UserNotificationSettingModel,
87 [ScopeNames.WITH_VIDEO_CHANNEL]: {
92 include: [ VideoChannelModel ]
95 model: UserNotificationSettingModel,
105 fields: [ 'username' ],
114 export class UserModel extends Model<UserModel> {
117 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
122 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
128 @Column(DataType.STRING(400))
133 @Column(DataType.STRING(400))
138 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
140 emailVerified: boolean
143 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
144 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
145 nsfwPolicy: NSFWPolicyType
149 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
151 webTorrentEnabled: boolean
155 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
157 videosHistoryEnabled: boolean
161 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
163 autoPlayVideo: boolean
167 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
169 autoPlayNextVideo: boolean
173 @Is('UserAutoPlayNextVideoPlaylist', value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean'))
175 autoPlayNextVideoPlaylist: boolean
179 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
180 @Column(DataType.ARRAY(DataType.STRING))
181 videoLanguages: string[]
184 @Default(UserAdminFlag.NONE)
185 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
187 adminFlags?: UserAdminFlag
191 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
197 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
199 blockedReason: string
202 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
207 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
208 @Column(DataType.BIGINT)
212 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
213 @Column(DataType.BIGINT)
214 videoQuotaDaily: number
217 @Default(DEFAULT_THEME_NAME)
218 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
225 'UserNoInstanceConfigWarningModal',
226 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
229 noInstanceConfigWarningModal: boolean
234 'UserNoInstanceConfigWarningModal',
235 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
238 noWelcomeModal: boolean
246 @HasOne(() => AccountModel, {
247 foreignKey: 'userId',
251 Account: AccountModel
253 @HasOne(() => UserNotificationSettingModel, {
254 foreignKey: 'userId',
258 NotificationSetting: UserNotificationSettingModel
260 @HasMany(() => VideoImportModel, {
261 foreignKey: 'userId',
264 VideoImports: VideoImportModel[]
266 @HasMany(() => OAuthTokenModel, {
267 foreignKey: 'userId',
270 OAuthTokens: OAuthTokenModel[]
274 static cryptPasswordIfNeeded (instance: UserModel) {
275 if (instance.changed('password')) {
276 return cryptPassword(instance.password)
278 instance.password = hash
286 static removeTokenCache (instance: UserModel) {
287 return clearCacheByUserId(instance.id)
290 static countTotal () {
294 static listForApi (start: number, count: number, sort: string, search?: string) {
295 let where = undefined
301 [Op.iLike]: '%' + search + '%'
306 [ Op.iLike ]: '%' + search + '%'
313 const query: FindOptions = {
319 'SELECT COALESCE(SUM("size"), 0) ' +
321 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
322 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
323 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
324 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
325 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
335 order: getSort(sort),
339 return UserModel.findAndCountAll(query)
340 .then(({ rows, count }) => {
348 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
349 const roles = Object.keys(USER_ROLE_LABELS)
350 .map(k => parseInt(k, 10) as UserRole)
351 .filter(role => hasUserRight(role, right))
361 return UserModel.findAll(query)
364 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
368 model: UserNotificationSettingModel.unscoped(),
372 attributes: [ 'userId' ],
373 model: AccountModel.unscoped(),
378 model: ActorModel.unscoped(),
386 as: 'ActorFollowings',
387 model: ActorFollowModel.unscoped(),
390 targetActorId: actorId
400 return UserModel.unscoped().findAll(query)
403 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
410 return UserModel.findAll(query)
413 static loadById (id: number): Bluebird<MUserDefault> {
414 return UserModel.findByPk(id)
417 static loadByUsername (username: string): Bluebird<MUserDefault> {
420 username: { [ Op.iLike ]: username }
424 return UserModel.findOne(query)
427 static loadByUsernameAndPopulateChannels (username: string): Bluebird<MUserNotifSettingChannelDefault> {
430 username: { [ Op.iLike ]: username }
434 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
437 static loadByEmail (email: string): Bluebird<MUserDefault> {
444 return UserModel.findOne(query)
447 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
448 if (!email) email = username
452 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
456 return UserModel.findOne(query)
459 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
464 attributes: [ 'id' ],
465 model: AccountModel.unscoped(),
469 attributes: [ 'id' ],
470 model: VideoChannelModel.unscoped(),
474 attributes: [ 'id' ],
475 model: VideoModel.unscoped(),
487 return UserModel.findOne(query)
490 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
495 attributes: [ 'id' ],
496 model: VideoImportModel.unscoped(),
504 return UserModel.findOne(query)
507 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
512 attributes: [ 'id' ],
513 model: AccountModel.unscoped(),
517 attributes: [ 'id' ],
518 model: VideoChannelModel.unscoped(),
520 actorId: videoChannelActorId
528 return UserModel.findOne(query)
531 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
536 attributes: [ 'id' ],
537 model: AccountModel.unscoped(),
539 actorId: accountActorId
545 return UserModel.findOne(query)
548 static getOriginalVideoFileTotalFromUser (user: MUserId) {
549 // Don't use sequelize because we need to use a sub query
550 const query = UserModel.generateUserQuotaBaseSQL()
552 return UserModel.getTotalRawQuery(query, user.id)
555 // Returns cumulative size of all video files uploaded in the last 24 hours.
556 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
557 // Don't use sequelize because we need to use a sub query
558 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
560 return UserModel.getTotalRawQuery(query, user.id)
563 static async getStats () {
564 const totalUsers = await UserModel.count()
571 static autoComplete (search: string) {
575 [ Op.like ]: `%${search}%`
581 return UserModel.findAll(query)
582 .then(u => u.map(u => u.username))
585 canGetVideo (video: MVideoFullLight) {
586 const videoUserId = video.VideoChannel.Account.userId
588 if (video.isBlacklisted()) {
589 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
592 if (video.privacy === VideoPrivacy.PRIVATE) {
593 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
596 if (video.privacy === VideoPrivacy.INTERNAL) return true
601 hasRight (right: UserRight) {
602 return hasUserRight(this.role, right)
605 hasAdminFlag (flag: UserAdminFlag) {
606 return this.adminFlags & flag
609 isPasswordMatch (password: string) {
610 return comparePassword(password, this.password)
613 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
614 const videoQuotaUsed = this.get('videoQuotaUsed')
615 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
619 username: this.username,
621 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
623 pendingEmail: this.pendingEmail,
624 emailVerified: this.emailVerified,
626 nsfwPolicy: this.nsfwPolicy,
627 webTorrentEnabled: this.webTorrentEnabled,
628 videosHistoryEnabled: this.videosHistoryEnabled,
629 autoPlayVideo: this.autoPlayVideo,
630 autoPlayNextVideo: this.autoPlayNextVideo,
631 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
632 videoLanguages: this.videoLanguages,
635 roleLabel: USER_ROLE_LABELS[ this.role ],
637 videoQuota: this.videoQuota,
638 videoQuotaDaily: this.videoQuotaDaily,
639 videoQuotaUsed: videoQuotaUsed !== undefined
640 ? parseInt(videoQuotaUsed + '', 10)
642 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
643 ? parseInt(videoQuotaUsedDaily + '', 10)
646 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
647 noWelcomeModal: this.noWelcomeModal,
649 blocked: this.blocked,
650 blockedReason: this.blockedReason,
652 account: this.Account.toFormattedJSON(),
654 notificationSettings: this.NotificationSetting
655 ? this.NotificationSetting.toFormattedJSON()
660 createdAt: this.createdAt
663 if (parameters.withAdminFlags) {
664 Object.assign(json, { adminFlags: this.adminFlags })
667 if (Array.isArray(this.Account.VideoChannels) === true) {
668 json.videoChannels = this.Account.VideoChannels
669 .map(c => c.toFormattedJSON())
671 if (v1.createdAt < v2.createdAt) return -1
672 if (v1.createdAt === v2.createdAt) return 0
681 async isAbleToUploadVideo (videoFile: { size: number }) {
682 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
684 const [ totalBytes, totalBytesDaily ] = await Promise.all([
685 UserModel.getOriginalVideoFileTotalFromUser(this),
686 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
689 const uploadedTotal = videoFile.size + totalBytes
690 const uploadedDaily = videoFile.size + totalBytesDaily
692 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
693 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
695 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
698 private static generateUserQuotaBaseSQL (where?: string) {
699 const andWhere = where ? 'AND ' + where : ''
701 return 'SELECT SUM("size") AS "total" ' +
703 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
704 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
705 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
706 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
707 'WHERE "account"."userId" = $userId ' + andWhere +
708 'GROUP BY "video"."id"' +
712 private static getTotalRawQuery (query: string, userId: number) {
715 type: QueryTypes.SELECT as QueryTypes.SELECT
718 return UserModel.sequelize.query<{ total: string }>(query, options)
719 .then(([ { total } ]) => {
720 if (total === null) return 0
722 return parseInt(total, 10)