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 if (video.privacy === VideoPrivacy.INTERNAL) return true
588 if (video.privacy === VideoPrivacy.PRIVATE) {
589 return video.VideoChannel && video.VideoChannel.Account.userId === this.id
592 if (video.isBlacklisted()) {
593 return this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
599 hasRight (right: UserRight) {
600 return hasUserRight(this.role, right)
603 hasAdminFlag (flag: UserAdminFlag) {
604 return this.adminFlags & flag
607 isPasswordMatch (password: string) {
608 return comparePassword(password, this.password)
611 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
612 const videoQuotaUsed = this.get('videoQuotaUsed')
613 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
617 username: this.username,
619 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
621 pendingEmail: this.pendingEmail,
622 emailVerified: this.emailVerified,
624 nsfwPolicy: this.nsfwPolicy,
625 webTorrentEnabled: this.webTorrentEnabled,
626 videosHistoryEnabled: this.videosHistoryEnabled,
627 autoPlayVideo: this.autoPlayVideo,
628 autoPlayNextVideo: this.autoPlayNextVideo,
629 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
630 videoLanguages: this.videoLanguages,
633 roleLabel: USER_ROLE_LABELS[ this.role ],
635 videoQuota: this.videoQuota,
636 videoQuotaDaily: this.videoQuotaDaily,
637 videoQuotaUsed: videoQuotaUsed !== undefined
638 ? parseInt(videoQuotaUsed + '', 10)
640 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
641 ? parseInt(videoQuotaUsedDaily + '', 10)
644 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
645 noWelcomeModal: this.noWelcomeModal,
647 blocked: this.blocked,
648 blockedReason: this.blockedReason,
650 account: this.Account.toFormattedJSON(),
652 notificationSettings: this.NotificationSetting
653 ? this.NotificationSetting.toFormattedJSON()
658 createdAt: this.createdAt
661 if (parameters.withAdminFlags) {
662 Object.assign(json, { adminFlags: this.adminFlags })
665 if (Array.isArray(this.Account.VideoChannels) === true) {
666 json.videoChannels = this.Account.VideoChannels
667 .map(c => c.toFormattedJSON())
669 if (v1.createdAt < v2.createdAt) return -1
670 if (v1.createdAt === v2.createdAt) return 0
679 async isAbleToUploadVideo (videoFile: { size: number }) {
680 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
682 const [ totalBytes, totalBytesDaily ] = await Promise.all([
683 UserModel.getOriginalVideoFileTotalFromUser(this),
684 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
687 const uploadedTotal = videoFile.size + totalBytes
688 const uploadedDaily = videoFile.size + totalBytesDaily
690 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
691 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
693 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
696 private static generateUserQuotaBaseSQL (where?: string) {
697 const andWhere = where ? 'AND ' + where : ''
699 return 'SELECT SUM("size") AS "total" ' +
701 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
702 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
703 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
704 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
705 'WHERE "account"."userId" = $userId ' + andWhere +
706 'GROUP BY "video"."id"' +
710 private static getTotalRawQuery (query: string, userId: number) {
713 type: QueryTypes.SELECT as QueryTypes.SELECT
716 return UserModel.sequelize.query<{ total: string }>(query, options)
717 .then(([ { total } ]) => {
718 if (total === null) return 0
720 return parseInt(total, 10)