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 { AttributesOnly } from '@shared/typescript-utils'
34 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
35 import { AbuseState, MyUser, UserRight, VideoPlaylistType } from '../../../shared/models'
36 import { User, UserRole } from '../../../shared/models/users'
37 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
38 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
41 isUserAdminFlagsValid,
42 isUserAutoPlayNextVideoPlaylistValid,
43 isUserAutoPlayNextVideoValid,
44 isUserAutoPlayVideoValid,
45 isUserBlockedReasonValid,
47 isUserEmailVerifiedValid,
49 isUserNSFWPolicyValid,
50 isUserP2PEnabledValid,
54 isUserVideoQuotaDailyValid,
55 isUserVideoQuotaValid,
56 isUserVideosHistoryEnabledValid
57 } from '../../helpers/custom-validators/users'
58 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
59 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
60 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
61 import { AccountModel } from '../account/account'
62 import { ActorModel } from '../actor/actor'
63 import { ActorFollowModel } from '../actor/actor-follow'
64 import { ActorImageModel } from '../actor/actor-image'
65 import { OAuthTokenModel } from '../oauth/oauth-token'
66 import { getAdminUsersSort, throwIfNotValid } from '../utils'
67 import { VideoModel } from '../video/video'
68 import { VideoChannelModel } from '../video/video-channel'
69 import { VideoImportModel } from '../video/video-import'
70 import { VideoLiveModel } from '../video/video-live'
71 import { VideoPlaylistModel } from '../video/video-playlist'
72 import { UserNotificationSettingModel } from './user-notification-setting'
75 FOR_ME_API = 'FOR_ME_API',
76 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
77 WITH_QUOTA = 'WITH_QUOTA',
78 WITH_STATS = 'WITH_STATS'
81 @DefaultScope(() => ({
88 model: UserNotificationSettingModel,
94 [ScopeNames.FOR_ME_API]: {
100 model: VideoChannelModel.unscoped(),
107 model: ActorImageModel,
116 attributes: [ 'id', 'name', 'type' ],
117 model: VideoPlaylistModel.unscoped(),
121 [Op.ne]: VideoPlaylistType.REGULAR
128 model: UserNotificationSettingModel,
133 [ScopeNames.WITH_VIDEOCHANNELS]: {
139 model: VideoChannelModel
142 attributes: [ 'id', 'name', 'type' ],
143 model: VideoPlaylistModel.unscoped(),
147 [Op.ne]: VideoPlaylistType.REGULAR
155 [ScopeNames.WITH_QUOTA]: {
161 UserModel.generateUserQuotaBaseSQL({
163 whereUserId: '"UserModel"."id"',
173 UserModel.generateUserQuotaBaseSQL({
175 whereUserId: '"UserModel"."id"',
180 'videoQuotaUsedDaily'
185 [ScopeNames.WITH_STATS]: {
191 'SELECT COUNT("video"."id") ' +
193 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
194 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
195 'WHERE "account"."userId" = "UserModel"."id"' +
203 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
205 'SELECT COUNT("abuse"."id") AS "abuses", ' +
206 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
208 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
209 'WHERE "account"."userId" = "UserModel"."id"' +
218 'SELECT COUNT("abuse"."id") ' +
220 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
221 'WHERE "account"."userId" = "UserModel"."id"' +
229 'SELECT COUNT("videoComment"."id") ' +
230 'FROM "videoComment" ' +
231 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
232 'WHERE "account"."userId" = "UserModel"."id"' +
245 fields: [ 'username' ],
254 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
257 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
267 @Column(DataType.STRING(400))
272 @Column(DataType.STRING(400))
277 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
279 emailVerified: boolean
282 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
283 @Column(DataType.ENUM(...Object.values(NSFW_POLICY_TYPES)))
284 nsfwPolicy: NSFWPolicyType
287 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
293 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
295 videosHistoryEnabled: boolean
299 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
301 autoPlayVideo: boolean
305 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
307 autoPlayNextVideo: boolean
312 'UserAutoPlayNextVideoPlaylist',
313 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
316 autoPlayNextVideoPlaylist: boolean
320 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
321 @Column(DataType.ARRAY(DataType.STRING))
322 videoLanguages: string[]
325 @Default(UserAdminFlag.NONE)
326 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
328 adminFlags?: UserAdminFlag
332 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
338 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
340 blockedReason: string
343 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
348 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
349 @Column(DataType.BIGINT)
353 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
354 @Column(DataType.BIGINT)
355 videoQuotaDaily: number
358 @Default(DEFAULT_USER_THEME_NAME)
359 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
366 'UserNoInstanceConfigWarningModal',
367 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
370 noInstanceConfigWarningModal: boolean
375 'UserNoWelcomeModal',
376 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
379 noWelcomeModal: boolean
384 'UserNoAccountSetupWarningModal',
385 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
388 noAccountSetupWarningModal: boolean
396 @Default(DataType.UUIDV4)
398 @Column(DataType.UUID)
417 @HasOne(() => AccountModel, {
418 foreignKey: 'userId',
422 Account: AccountModel
424 @HasOne(() => UserNotificationSettingModel, {
425 foreignKey: 'userId',
429 NotificationSetting: UserNotificationSettingModel
431 @HasMany(() => VideoImportModel, {
432 foreignKey: 'userId',
435 VideoImports: VideoImportModel[]
437 @HasMany(() => OAuthTokenModel, {
438 foreignKey: 'userId',
441 OAuthTokens: OAuthTokenModel[]
445 static cryptPasswordIfNeeded (instance: UserModel) {
446 if (instance.changed('password') && instance.password) {
447 return cryptPassword(instance.password)
449 instance.password = hash
457 static removeTokenCache (instance: UserModel) {
458 return TokensCache.Instance.clearCacheByUserId(instance.id)
461 static countTotal () {
465 static listForAdminApi (parameters: {
472 const { start, count, sort, search, blocked } = parameters
473 const where: WhereOptions = {}
476 Object.assign(where, {
480 [Op.iLike]: '%' + search + '%'
485 [Op.iLike]: '%' + search + '%'
492 if (blocked !== undefined) {
493 Object.assign(where, { blocked })
496 const query: FindOptions = {
499 order: getAdminUsersSort(sort),
504 UserModel.unscoped().count(query),
505 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
506 ]).then(([ total, data ]) => ({ total, data }))
509 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
510 const roles = Object.keys(USER_ROLE_LABELS)
511 .map(k => parseInt(k, 10) as UserRole)
512 .filter(role => hasUserRight(role, right))
522 return UserModel.findAll(query)
525 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
529 model: UserNotificationSettingModel.unscoped(),
533 attributes: [ 'userId' ],
534 model: AccountModel.unscoped(),
539 model: ActorModel.unscoped(),
547 as: 'ActorFollowings',
548 model: ActorFollowModel.unscoped(),
551 targetActorId: actorId
561 return UserModel.unscoped().findAll(query)
564 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
571 return UserModel.findAll(query)
574 static loadById (id: number): Promise<MUser> {
575 return UserModel.unscoped().findByPk(id)
578 static loadByIdFull (id: number): Promise<MUserDefault> {
579 return UserModel.findByPk(id)
582 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
584 ScopeNames.WITH_VIDEOCHANNELS
588 scopes.push(ScopeNames.WITH_QUOTA)
589 scopes.push(ScopeNames.WITH_STATS)
592 return UserModel.scope(scopes).findByPk(id)
595 static loadByUsername (username: string): Promise<MUserDefault> {
602 return UserModel.findOne(query)
605 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
612 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
615 static loadByEmail (email: string): Promise<MUserDefault> {
622 return UserModel.findOne(query)
625 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
626 if (!email) email = username
631 where(fn('lower', col('username')), fn('lower', username) as any),
638 return UserModel.findOne(query)
641 static loadByVideoId (videoId: number): Promise<MUserDefault> {
646 attributes: [ 'id' ],
647 model: AccountModel.unscoped(),
651 attributes: [ 'id' ],
652 model: VideoChannelModel.unscoped(),
656 attributes: [ 'id' ],
657 model: VideoModel.unscoped(),
669 return UserModel.findOne(query)
672 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
677 attributes: [ 'id' ],
678 model: VideoImportModel.unscoped(),
686 return UserModel.findOne(query)
689 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
694 attributes: [ 'id' ],
695 model: AccountModel.unscoped(),
699 attributes: [ 'id' ],
700 model: VideoChannelModel.unscoped(),
702 actorId: videoChannelActorId
710 return UserModel.findOne(query)
713 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
718 attributes: [ 'id' ],
719 model: AccountModel.unscoped(),
721 actorId: accountActorId
727 return UserModel.findOne(query)
730 static loadByLiveId (liveId: number): Promise<MUser> {
734 attributes: [ 'id' ],
735 model: AccountModel.unscoped(),
739 attributes: [ 'id' ],
740 model: VideoChannelModel.unscoped(),
744 attributes: [ 'id' ],
745 model: VideoModel.unscoped(),
750 model: VideoLiveModel.unscoped(),
765 return UserModel.unscoped().findOne(query)
768 static generateUserQuotaBaseSQL (options: {
769 whereUserId: '$userId' | '"UserModel"."id"'
773 const andWhere = options.daily === true
774 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
777 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
778 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
779 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
781 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
782 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
785 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
786 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
787 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
790 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
792 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
793 'GROUP BY "t1"."videoId"' +
797 static getTotalRawQuery (query: string, userId: number) {
800 type: QueryTypes.SELECT as QueryTypes.SELECT
803 return UserModel.sequelize.query<{ total: string }>(query, options)
804 .then(([ { total } ]) => {
805 if (total === null) return 0
807 return parseInt(total, 10)
811 static async getStats () {
812 function getActiveUsers (days: number) {
816 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
821 return UserModel.unscoped().count(query)
824 const totalUsers = await UserModel.unscoped().count()
825 const totalDailyActiveUsers = await getActiveUsers(1)
826 const totalWeeklyActiveUsers = await getActiveUsers(7)
827 const totalMonthlyActiveUsers = await getActiveUsers(30)
828 const totalHalfYearActiveUsers = await getActiveUsers(180)
832 totalDailyActiveUsers,
833 totalWeeklyActiveUsers,
834 totalMonthlyActiveUsers,
835 totalHalfYearActiveUsers
839 static autoComplete (search: string) {
843 [Op.like]: `%${search}%`
849 return UserModel.findAll(query)
850 .then(u => u.map(u => u.username))
853 hasRight (right: UserRight) {
854 return hasUserRight(this.role, right)
857 hasAdminFlag (flag: UserAdminFlag) {
858 return this.adminFlags & flag
861 isPasswordMatch (password: string) {
862 return comparePassword(password, this.password)
865 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
866 const videoQuotaUsed = this.get('videoQuotaUsed')
867 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
868 const videosCount = this.get('videosCount')
869 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
870 const abusesCreatedCount = this.get('abusesCreatedCount')
871 const videoCommentsCount = this.get('videoCommentsCount')
875 username: this.username,
877 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
879 pendingEmail: this.pendingEmail,
880 emailVerified: this.emailVerified,
882 nsfwPolicy: this.nsfwPolicy,
884 // FIXME: deprecated in 4.1
885 webTorrentEnabled: this.p2pEnabled,
886 p2pEnabled: this.p2pEnabled,
888 videosHistoryEnabled: this.videosHistoryEnabled,
889 autoPlayVideo: this.autoPlayVideo,
890 autoPlayNextVideo: this.autoPlayNextVideo,
891 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
892 videoLanguages: this.videoLanguages,
896 label: USER_ROLE_LABELS[this.role]
899 videoQuota: this.videoQuota,
900 videoQuotaDaily: this.videoQuotaDaily,
902 videoQuotaUsed: videoQuotaUsed !== undefined
903 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
906 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
907 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
910 videosCount: videosCount !== undefined
911 ? parseInt(videosCount + '', 10)
913 abusesCount: abusesCount
914 ? parseInt(abusesCount, 10)
916 abusesAcceptedCount: abusesAcceptedCount
917 ? parseInt(abusesAcceptedCount, 10)
919 abusesCreatedCount: abusesCreatedCount !== undefined
920 ? parseInt(abusesCreatedCount + '', 10)
922 videoCommentsCount: videoCommentsCount !== undefined
923 ? parseInt(videoCommentsCount + '', 10)
926 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
927 noWelcomeModal: this.noWelcomeModal,
928 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
930 blocked: this.blocked,
931 blockedReason: this.blockedReason,
933 account: this.Account.toFormattedJSON(),
935 notificationSettings: this.NotificationSetting
936 ? this.NotificationSetting.toFormattedJSON()
941 createdAt: this.createdAt,
943 pluginAuth: this.pluginAuth,
945 lastLoginDate: this.lastLoginDate,
947 twoFactorEnabled: !!this.otpSecret
950 if (parameters.withAdminFlags) {
951 Object.assign(json, { adminFlags: this.adminFlags })
954 if (Array.isArray(this.Account.VideoChannels) === true) {
955 json.videoChannels = this.Account.VideoChannels
956 .map(c => c.toFormattedJSON())
958 if (v1.createdAt < v2.createdAt) return -1
959 if (v1.createdAt === v2.createdAt) return 0
968 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
969 const formatted = this.toFormattedJSON({ withAdminFlags: true })
971 const specialPlaylists = this.Account.VideoPlaylists
972 .map(p => ({ id: p.id, name: p.name, type: p.type }))
974 return Object.assign(formatted, { specialPlaylists })