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)
412 @HasOne(() => AccountModel, {
413 foreignKey: 'userId',
417 Account: AccountModel
419 @HasOne(() => UserNotificationSettingModel, {
420 foreignKey: 'userId',
424 NotificationSetting: UserNotificationSettingModel
426 @HasMany(() => VideoImportModel, {
427 foreignKey: 'userId',
430 VideoImports: VideoImportModel[]
432 @HasMany(() => OAuthTokenModel, {
433 foreignKey: 'userId',
436 OAuthTokens: OAuthTokenModel[]
440 static cryptPasswordIfNeeded (instance: UserModel) {
441 if (instance.changed('password') && instance.password) {
442 return cryptPassword(instance.password)
444 instance.password = hash
452 static removeTokenCache (instance: UserModel) {
453 return TokensCache.Instance.clearCacheByUserId(instance.id)
456 static countTotal () {
460 static listForAdminApi (parameters: {
467 const { start, count, sort, search, blocked } = parameters
468 const where: WhereOptions = {}
471 Object.assign(where, {
475 [Op.iLike]: '%' + search + '%'
480 [Op.iLike]: '%' + search + '%'
487 if (blocked !== undefined) {
488 Object.assign(where, { blocked })
491 const query: FindOptions = {
494 order: getAdminUsersSort(sort),
499 UserModel.unscoped().count(query),
500 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
501 ]).then(([ total, data ]) => ({ total, data }))
504 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
505 const roles = Object.keys(USER_ROLE_LABELS)
506 .map(k => parseInt(k, 10) as UserRole)
507 .filter(role => hasUserRight(role, right))
517 return UserModel.findAll(query)
520 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
524 model: UserNotificationSettingModel.unscoped(),
528 attributes: [ 'userId' ],
529 model: AccountModel.unscoped(),
534 model: ActorModel.unscoped(),
542 as: 'ActorFollowings',
543 model: ActorFollowModel.unscoped(),
546 targetActorId: actorId
556 return UserModel.unscoped().findAll(query)
559 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
566 return UserModel.findAll(query)
569 static loadById (id: number): Promise<MUser> {
570 return UserModel.unscoped().findByPk(id)
573 static loadByIdFull (id: number): Promise<MUserDefault> {
574 return UserModel.findByPk(id)
577 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
579 ScopeNames.WITH_VIDEOCHANNELS
583 scopes.push(ScopeNames.WITH_QUOTA)
584 scopes.push(ScopeNames.WITH_STATS)
587 return UserModel.scope(scopes).findByPk(id)
590 static loadByUsername (username: string): Promise<MUserDefault> {
597 return UserModel.findOne(query)
600 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
607 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
610 static loadByEmail (email: string): Promise<MUserDefault> {
617 return UserModel.findOne(query)
620 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
621 if (!email) email = username
626 where(fn('lower', col('username')), fn('lower', username) as any),
633 return UserModel.findOne(query)
636 static loadByVideoId (videoId: number): Promise<MUserDefault> {
641 attributes: [ 'id' ],
642 model: AccountModel.unscoped(),
646 attributes: [ 'id' ],
647 model: VideoChannelModel.unscoped(),
651 attributes: [ 'id' ],
652 model: VideoModel.unscoped(),
664 return UserModel.findOne(query)
667 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
672 attributes: [ 'id' ],
673 model: VideoImportModel.unscoped(),
681 return UserModel.findOne(query)
684 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
689 attributes: [ 'id' ],
690 model: AccountModel.unscoped(),
694 attributes: [ 'id' ],
695 model: VideoChannelModel.unscoped(),
697 actorId: videoChannelActorId
705 return UserModel.findOne(query)
708 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
713 attributes: [ 'id' ],
714 model: AccountModel.unscoped(),
716 actorId: accountActorId
722 return UserModel.findOne(query)
725 static loadByLiveId (liveId: number): Promise<MUser> {
729 attributes: [ 'id' ],
730 model: AccountModel.unscoped(),
734 attributes: [ 'id' ],
735 model: VideoChannelModel.unscoped(),
739 attributes: [ 'id' ],
740 model: VideoModel.unscoped(),
745 model: VideoLiveModel.unscoped(),
760 return UserModel.unscoped().findOne(query)
763 static generateUserQuotaBaseSQL (options: {
764 whereUserId: '$userId' | '"UserModel"."id"'
768 const andWhere = options.daily === true
769 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
772 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
773 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
774 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
776 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
777 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
780 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
781 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
782 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
785 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
787 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
788 'GROUP BY "t1"."videoId"' +
792 static getTotalRawQuery (query: string, userId: number) {
795 type: QueryTypes.SELECT as QueryTypes.SELECT
798 return UserModel.sequelize.query<{ total: string }>(query, options)
799 .then(([ { total } ]) => {
800 if (total === null) return 0
802 return parseInt(total, 10)
806 static async getStats () {
807 function getActiveUsers (days: number) {
811 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
816 return UserModel.unscoped().count(query)
819 const totalUsers = await UserModel.unscoped().count()
820 const totalDailyActiveUsers = await getActiveUsers(1)
821 const totalWeeklyActiveUsers = await getActiveUsers(7)
822 const totalMonthlyActiveUsers = await getActiveUsers(30)
823 const totalHalfYearActiveUsers = await getActiveUsers(180)
827 totalDailyActiveUsers,
828 totalWeeklyActiveUsers,
829 totalMonthlyActiveUsers,
830 totalHalfYearActiveUsers
834 static autoComplete (search: string) {
838 [Op.like]: `%${search}%`
844 return UserModel.findAll(query)
845 .then(u => u.map(u => u.username))
848 hasRight (right: UserRight) {
849 return hasUserRight(this.role, right)
852 hasAdminFlag (flag: UserAdminFlag) {
853 return this.adminFlags & flag
856 isPasswordMatch (password: string) {
857 return comparePassword(password, this.password)
860 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
861 const videoQuotaUsed = this.get('videoQuotaUsed')
862 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
863 const videosCount = this.get('videosCount')
864 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
865 const abusesCreatedCount = this.get('abusesCreatedCount')
866 const videoCommentsCount = this.get('videoCommentsCount')
870 username: this.username,
872 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
874 pendingEmail: this.pendingEmail,
875 emailVerified: this.emailVerified,
877 nsfwPolicy: this.nsfwPolicy,
879 // FIXME: deprecated in 4.1
880 webTorrentEnabled: this.p2pEnabled,
881 p2pEnabled: this.p2pEnabled,
883 videosHistoryEnabled: this.videosHistoryEnabled,
884 autoPlayVideo: this.autoPlayVideo,
885 autoPlayNextVideo: this.autoPlayNextVideo,
886 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
887 videoLanguages: this.videoLanguages,
890 roleLabel: USER_ROLE_LABELS[this.role],
892 videoQuota: this.videoQuota,
893 videoQuotaDaily: this.videoQuotaDaily,
895 videoQuotaUsed: videoQuotaUsed !== undefined
896 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
899 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
900 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
903 videosCount: videosCount !== undefined
904 ? parseInt(videosCount + '', 10)
906 abusesCount: abusesCount
907 ? parseInt(abusesCount, 10)
909 abusesAcceptedCount: abusesAcceptedCount
910 ? parseInt(abusesAcceptedCount, 10)
912 abusesCreatedCount: abusesCreatedCount !== undefined
913 ? parseInt(abusesCreatedCount + '', 10)
915 videoCommentsCount: videoCommentsCount !== undefined
916 ? parseInt(videoCommentsCount + '', 10)
919 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
920 noWelcomeModal: this.noWelcomeModal,
921 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
923 blocked: this.blocked,
924 blockedReason: this.blockedReason,
926 account: this.Account.toFormattedJSON(),
928 notificationSettings: this.NotificationSetting
929 ? this.NotificationSetting.toFormattedJSON()
934 createdAt: this.createdAt,
936 pluginAuth: this.pluginAuth,
938 lastLoginDate: this.lastLoginDate
941 if (parameters.withAdminFlags) {
942 Object.assign(json, { adminFlags: this.adminFlags })
945 if (Array.isArray(this.Account.VideoChannels) === true) {
946 json.videoChannels = this.Account.VideoChannels
947 .map(c => c.toFormattedJSON())
949 if (v1.createdAt < v2.createdAt) return -1
950 if (v1.createdAt === v2.createdAt) return 0
959 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
960 const formatted = this.toFormattedJSON({ withAdminFlags: true })
962 const specialPlaylists = this.Account.VideoPlaylists
963 .map(p => ({ id: p.id, name: p.name, type: p.type }))
965 return Object.assign(formatted, { specialPlaylists })