1 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
22 } from 'sequelize-typescript'
23 import { TokensCache } from '@server/lib/auth/tokens-cache'
24 import { LiveQuotaStore } from '@server/lib/live'
30 MUserNotifSettingChannelDefault,
31 MUserWithNotificationSetting
32 } from '@server/types/models'
33 import { forceNumber } from '@shared/core-utils'
34 import { AttributesOnly } from '@shared/typescript-utils'
35 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
36 import { AbuseState, MyUser, UserRight, VideoPlaylistType } from '../../../shared/models'
37 import { User, UserRole } from '../../../shared/models/users'
38 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
39 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
40 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
42 isUserAdminFlagsValid,
43 isUserAutoPlayNextVideoPlaylistValid,
44 isUserAutoPlayNextVideoValid,
45 isUserAutoPlayVideoValid,
46 isUserBlockedReasonValid,
48 isUserEmailVerifiedValid,
50 isUserNSFWPolicyValid,
51 isUserP2PEnabledValid,
55 isUserVideoQuotaDailyValid,
56 isUserVideoQuotaValid,
57 isUserVideosHistoryEnabledValid
58 } from '../../helpers/custom-validators/users'
59 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
60 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
61 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
62 import { AccountModel } from '../account/account'
63 import { ActorModel } from '../actor/actor'
64 import { ActorFollowModel } from '../actor/actor-follow'
65 import { ActorImageModel } from '../actor/actor-image'
66 import { OAuthTokenModel } from '../oauth/oauth-token'
67 import { getAdminUsersSort, throwIfNotValid } from '../shared'
68 import { VideoModel } from '../video/video'
69 import { VideoChannelModel } from '../video/video-channel'
70 import { VideoImportModel } from '../video/video-import'
71 import { VideoLiveModel } from '../video/video-live'
72 import { VideoPlaylistModel } from '../video/video-playlist'
73 import { UserNotificationSettingModel } from './user-notification-setting'
76 FOR_ME_API = 'FOR_ME_API',
77 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
78 WITH_QUOTA = 'WITH_QUOTA',
79 WITH_STATS = 'WITH_STATS'
82 @DefaultScope(() => ({
89 model: UserNotificationSettingModel,
95 [ScopeNames.FOR_ME_API]: {
101 model: VideoChannelModel.unscoped(),
108 model: ActorImageModel,
117 attributes: [ 'id', 'name', 'type' ],
118 model: VideoPlaylistModel.unscoped(),
122 [Op.ne]: VideoPlaylistType.REGULAR
129 model: UserNotificationSettingModel,
134 [ScopeNames.WITH_VIDEOCHANNELS]: {
140 model: VideoChannelModel
143 attributes: [ 'id', 'name', 'type' ],
144 model: VideoPlaylistModel.unscoped(),
148 [Op.ne]: VideoPlaylistType.REGULAR
156 [ScopeNames.WITH_QUOTA]: {
162 UserModel.generateUserQuotaBaseSQL({
164 whereUserId: '"UserModel"."id"',
174 UserModel.generateUserQuotaBaseSQL({
176 whereUserId: '"UserModel"."id"',
181 'videoQuotaUsedDaily'
186 [ScopeNames.WITH_STATS]: {
192 'SELECT COUNT("video"."id") ' +
194 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
195 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
196 'WHERE "account"."userId" = "UserModel"."id"' +
204 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
206 'SELECT COUNT("abuse"."id") AS "abuses", ' +
207 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
209 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
210 'WHERE "account"."userId" = "UserModel"."id"' +
219 'SELECT COUNT("abuse"."id") ' +
221 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
222 'WHERE "account"."userId" = "UserModel"."id"' +
230 'SELECT COUNT("videoComment"."id") ' +
231 'FROM "videoComment" ' +
232 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
233 'WHERE "account"."userId" = "UserModel"."id"' +
246 fields: [ 'username' ],
255 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
258 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
268 @Column(DataType.STRING(400))
273 @Column(DataType.STRING(400))
278 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
280 emailVerified: boolean
283 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
284 @Column(DataType.ENUM(...Object.values(NSFW_POLICY_TYPES)))
285 nsfwPolicy: NSFWPolicyType
288 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
294 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
296 videosHistoryEnabled: boolean
300 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
302 autoPlayVideo: boolean
306 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
308 autoPlayNextVideo: boolean
313 'UserAutoPlayNextVideoPlaylist',
314 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
317 autoPlayNextVideoPlaylist: boolean
321 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
322 @Column(DataType.ARRAY(DataType.STRING))
323 videoLanguages: string[]
326 @Default(UserAdminFlag.NONE)
327 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
329 adminFlags?: UserAdminFlag
333 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
339 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
341 blockedReason: string
344 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
349 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
350 @Column(DataType.BIGINT)
354 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
355 @Column(DataType.BIGINT)
356 videoQuotaDaily: number
359 @Default(DEFAULT_USER_THEME_NAME)
360 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
367 'UserNoInstanceConfigWarningModal',
368 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
371 noInstanceConfigWarningModal: boolean
376 'UserNoWelcomeModal',
377 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
380 noWelcomeModal: boolean
385 'UserNoAccountSetupWarningModal',
386 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
389 noAccountSetupWarningModal: boolean
397 @Default(DataType.UUIDV4)
399 @Column(DataType.UUID)
423 @HasOne(() => AccountModel, {
424 foreignKey: 'userId',
428 Account: AccountModel
430 @HasOne(() => UserNotificationSettingModel, {
431 foreignKey: 'userId',
435 NotificationSetting: UserNotificationSettingModel
437 @HasMany(() => VideoImportModel, {
438 foreignKey: 'userId',
441 VideoImports: VideoImportModel[]
443 @HasMany(() => OAuthTokenModel, {
444 foreignKey: 'userId',
447 OAuthTokens: OAuthTokenModel[]
449 // Used if we already set an encrypted password in user model
450 skipPasswordEncryption = false
454 static async cryptPasswordIfNeeded (instance: UserModel) {
455 if (instance.skipPasswordEncryption) return
456 if (!instance.changed('password')) return
457 if (!instance.password) return
459 instance.password = await cryptPassword(instance.password)
464 static removeTokenCache (instance: UserModel) {
465 return TokensCache.Instance.clearCacheByUserId(instance.id)
468 static countTotal () {
469 return UserModel.unscoped().count()
472 static listForAdminApi (parameters: {
479 const { start, count, sort, search, blocked } = parameters
480 const where: WhereOptions = {}
483 Object.assign(where, {
487 [Op.iLike]: '%' + search + '%'
492 [Op.iLike]: '%' + search + '%'
499 if (blocked !== undefined) {
500 Object.assign(where, { blocked })
503 const query: FindOptions = {
506 order: getAdminUsersSort(sort),
511 UserModel.unscoped().count(query),
512 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
513 ]).then(([ total, data ]) => ({ total, data }))
516 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
517 const roles = Object.keys(USER_ROLE_LABELS)
518 .map(k => parseInt(k, 10) as UserRole)
519 .filter(role => hasUserRight(role, right))
529 return UserModel.findAll(query)
532 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
536 model: UserNotificationSettingModel.unscoped(),
540 attributes: [ 'userId' ],
541 model: AccountModel.unscoped(),
546 model: ActorModel.unscoped(),
554 as: 'ActorFollowings',
555 model: ActorFollowModel.unscoped(),
559 targetActorId: actorId
569 return UserModel.unscoped().findAll(query)
572 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
579 return UserModel.findAll(query)
582 static loadById (id: number): Promise<MUser> {
583 return UserModel.unscoped().findByPk(id)
586 static loadByIdFull (id: number): Promise<MUserDefault> {
587 return UserModel.findByPk(id)
590 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
592 ScopeNames.WITH_VIDEOCHANNELS
596 scopes.push(ScopeNames.WITH_QUOTA)
597 scopes.push(ScopeNames.WITH_STATS)
600 return UserModel.scope(scopes).findByPk(id)
603 static loadByUsername (username: string): Promise<MUserDefault> {
610 return UserModel.findOne(query)
613 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
620 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
623 static loadByEmail (email: string): Promise<MUserDefault> {
630 return UserModel.findOne(query)
633 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
634 if (!email) email = username
639 where(fn('lower', col('username')), fn('lower', username) as any),
646 return UserModel.findOne(query)
649 static loadByVideoId (videoId: number): Promise<MUserDefault> {
654 attributes: [ 'id' ],
655 model: AccountModel.unscoped(),
659 attributes: [ 'id' ],
660 model: VideoChannelModel.unscoped(),
664 attributes: [ 'id' ],
665 model: VideoModel.unscoped(),
677 return UserModel.findOne(query)
680 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
685 attributes: [ 'id' ],
686 model: VideoImportModel.unscoped(),
694 return UserModel.findOne(query)
697 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
702 attributes: [ 'id' ],
703 model: AccountModel.unscoped(),
707 attributes: [ 'id' ],
708 model: VideoChannelModel.unscoped(),
710 actorId: videoChannelActorId
718 return UserModel.findOne(query)
721 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
726 attributes: [ 'id' ],
727 model: AccountModel.unscoped(),
729 actorId: accountActorId
735 return UserModel.findOne(query)
738 static loadByLiveId (liveId: number): Promise<MUser> {
742 attributes: [ 'id' ],
743 model: AccountModel.unscoped(),
747 attributes: [ 'id' ],
748 model: VideoChannelModel.unscoped(),
752 attributes: [ 'id' ],
753 model: VideoModel.unscoped(),
758 model: VideoLiveModel.unscoped(),
773 return UserModel.unscoped().findOne(query)
776 static generateUserQuotaBaseSQL (options: {
777 whereUserId: '$userId' | '"UserModel"."id"'
781 const andWhere = options.daily === true
782 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
785 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
786 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
787 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
789 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
790 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" AND "video"."isLive" IS FALSE ' +
793 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
794 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
795 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" AND "video"."isLive" IS FALSE ' +
798 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
800 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
801 'GROUP BY "t1"."videoId"' +
805 static getTotalRawQuery (query: string, userId: number) {
808 type: QueryTypes.SELECT as QueryTypes.SELECT
811 return UserModel.sequelize.query<{ total: string }>(query, options)
812 .then(([ { total } ]) => {
813 if (total === null) return 0
815 return parseInt(total, 10)
819 static async getStats () {
820 function getActiveUsers (days: number) {
824 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
829 return UserModel.unscoped().count(query)
832 const totalUsers = await UserModel.unscoped().count()
833 const totalDailyActiveUsers = await getActiveUsers(1)
834 const totalWeeklyActiveUsers = await getActiveUsers(7)
835 const totalMonthlyActiveUsers = await getActiveUsers(30)
836 const totalHalfYearActiveUsers = await getActiveUsers(180)
840 totalDailyActiveUsers,
841 totalWeeklyActiveUsers,
842 totalMonthlyActiveUsers,
843 totalHalfYearActiveUsers
847 static autoComplete (search: string) {
851 [Op.like]: `%${search}%`
857 return UserModel.findAll(query)
858 .then(u => u.map(u => u.username))
861 hasRight (right: UserRight) {
862 return hasUserRight(this.role, right)
865 hasAdminFlag (flag: UserAdminFlag) {
866 return this.adminFlags & flag
869 isPasswordMatch (password: string) {
870 return comparePassword(password, this.password)
873 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
874 const videoQuotaUsed = this.get('videoQuotaUsed')
875 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
876 const videosCount = this.get('videosCount')
877 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
878 const abusesCreatedCount = this.get('abusesCreatedCount')
879 const videoCommentsCount = this.get('videoCommentsCount')
883 username: this.username,
885 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
887 pendingEmail: this.pendingEmail,
888 emailPublic: this.emailPublic,
889 emailVerified: this.emailVerified,
891 nsfwPolicy: this.nsfwPolicy,
893 // FIXME: deprecated in 4.1
894 webTorrentEnabled: this.p2pEnabled,
895 p2pEnabled: this.p2pEnabled,
897 videosHistoryEnabled: this.videosHistoryEnabled,
898 autoPlayVideo: this.autoPlayVideo,
899 autoPlayNextVideo: this.autoPlayNextVideo,
900 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
901 videoLanguages: this.videoLanguages,
905 label: USER_ROLE_LABELS[this.role]
908 videoQuota: this.videoQuota,
909 videoQuotaDaily: this.videoQuotaDaily,
911 videoQuotaUsed: videoQuotaUsed !== undefined
912 ? forceNumber(videoQuotaUsed) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
915 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
916 ? forceNumber(videoQuotaUsedDaily) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
919 videosCount: videosCount !== undefined
920 ? forceNumber(videosCount)
922 abusesCount: abusesCount
923 ? forceNumber(abusesCount)
925 abusesAcceptedCount: abusesAcceptedCount
926 ? forceNumber(abusesAcceptedCount)
928 abusesCreatedCount: abusesCreatedCount !== undefined
929 ? forceNumber(abusesCreatedCount)
931 videoCommentsCount: videoCommentsCount !== undefined
932 ? forceNumber(videoCommentsCount)
935 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
936 noWelcomeModal: this.noWelcomeModal,
937 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
939 blocked: this.blocked,
940 blockedReason: this.blockedReason,
942 account: this.Account.toFormattedJSON(),
944 notificationSettings: this.NotificationSetting
945 ? this.NotificationSetting.toFormattedJSON()
950 createdAt: this.createdAt,
952 pluginAuth: this.pluginAuth,
954 lastLoginDate: this.lastLoginDate,
956 twoFactorEnabled: !!this.otpSecret
959 if (parameters.withAdminFlags) {
960 Object.assign(json, { adminFlags: this.adminFlags })
963 if (Array.isArray(this.Account.VideoChannels) === true) {
964 json.videoChannels = this.Account.VideoChannels
965 .map(c => c.toFormattedJSON())
967 if (v1.createdAt < v2.createdAt) return -1
968 if (v1.createdAt === v2.createdAt) return 0
977 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
978 const formatted = this.toFormattedJSON({ withAdminFlags: true })
980 const specialPlaylists = this.Account.VideoPlaylists
981 .map(p => ({ id: p.id, name: p.name, type: p.type }))
983 return Object.assign(formatted, { specialPlaylists })