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,
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 '../utils'
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))
263 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
269 @Column(DataType.STRING(400))
274 @Column(DataType.STRING(400))
279 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
281 emailVerified: boolean
284 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
285 @Column(DataType.ENUM(...Object.values(NSFW_POLICY_TYPES)))
286 nsfwPolicy: NSFWPolicyType
289 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
295 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
297 videosHistoryEnabled: boolean
301 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
303 autoPlayVideo: boolean
307 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
309 autoPlayNextVideo: boolean
314 'UserAutoPlayNextVideoPlaylist',
315 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
318 autoPlayNextVideoPlaylist: boolean
322 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
323 @Column(DataType.ARRAY(DataType.STRING))
324 videoLanguages: string[]
327 @Default(UserAdminFlag.NONE)
328 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
330 adminFlags?: UserAdminFlag
334 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
340 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
342 blockedReason: string
345 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
350 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
351 @Column(DataType.BIGINT)
355 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
356 @Column(DataType.BIGINT)
357 videoQuotaDaily: number
360 @Default(DEFAULT_USER_THEME_NAME)
361 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
368 'UserNoInstanceConfigWarningModal',
369 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
372 noInstanceConfigWarningModal: boolean
377 'UserNoWelcomeModal',
378 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
381 noWelcomeModal: boolean
386 'UserNoAccountSetupWarningModal',
387 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
390 noAccountSetupWarningModal: boolean
398 @Default(DataType.UUIDV4)
400 @Column(DataType.UUID)
414 @HasOne(() => AccountModel, {
415 foreignKey: 'userId',
419 Account: AccountModel
421 @HasOne(() => UserNotificationSettingModel, {
422 foreignKey: 'userId',
426 NotificationSetting: UserNotificationSettingModel
428 @HasMany(() => VideoImportModel, {
429 foreignKey: 'userId',
432 VideoImports: VideoImportModel[]
434 @HasMany(() => OAuthTokenModel, {
435 foreignKey: 'userId',
438 OAuthTokens: OAuthTokenModel[]
442 static cryptPasswordIfNeeded (instance: UserModel) {
443 if (instance.changed('password') && instance.password) {
444 return cryptPassword(instance.password)
446 instance.password = hash
454 static removeTokenCache (instance: UserModel) {
455 return TokensCache.Instance.clearCacheByUserId(instance.id)
458 static countTotal () {
462 static listForAdminApi (parameters: {
469 const { start, count, sort, search, blocked } = parameters
470 const where: WhereOptions = {}
473 Object.assign(where, {
477 [Op.iLike]: '%' + search + '%'
482 [Op.iLike]: '%' + search + '%'
489 if (blocked !== undefined) {
490 Object.assign(where, { blocked })
493 const query: FindOptions = {
496 order: getAdminUsersSort(sort),
501 UserModel.unscoped().count(query),
502 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
503 ]).then(([ total, data ]) => ({ total, data }))
506 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
507 const roles = Object.keys(USER_ROLE_LABELS)
508 .map(k => parseInt(k, 10) as UserRole)
509 .filter(role => hasUserRight(role, right))
519 return UserModel.findAll(query)
522 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
526 model: UserNotificationSettingModel.unscoped(),
530 attributes: [ 'userId' ],
531 model: AccountModel.unscoped(),
536 model: ActorModel.unscoped(),
544 as: 'ActorFollowings',
545 model: ActorFollowModel.unscoped(),
548 targetActorId: actorId
558 return UserModel.unscoped().findAll(query)
561 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
568 return UserModel.findAll(query)
571 static loadById (id: number): Promise<MUser> {
572 return UserModel.unscoped().findByPk(id)
575 static loadByIdFull (id: number): Promise<MUserDefault> {
576 return UserModel.findByPk(id)
579 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
581 ScopeNames.WITH_VIDEOCHANNELS
585 scopes.push(ScopeNames.WITH_QUOTA)
586 scopes.push(ScopeNames.WITH_STATS)
589 return UserModel.scope(scopes).findByPk(id)
592 static loadByUsername (username: string): Promise<MUserDefault> {
599 return UserModel.findOne(query)
602 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
609 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
612 static loadByEmail (email: string): Promise<MUserDefault> {
619 return UserModel.findOne(query)
622 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
623 if (!email) email = username
628 where(fn('lower', col('username')), fn('lower', username) as any),
635 return UserModel.findOne(query)
638 static loadByVideoId (videoId: number): Promise<MUserDefault> {
643 attributes: [ 'id' ],
644 model: AccountModel.unscoped(),
648 attributes: [ 'id' ],
649 model: VideoChannelModel.unscoped(),
653 attributes: [ 'id' ],
654 model: VideoModel.unscoped(),
666 return UserModel.findOne(query)
669 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
674 attributes: [ 'id' ],
675 model: VideoImportModel.unscoped(),
683 return UserModel.findOne(query)
686 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
691 attributes: [ 'id' ],
692 model: AccountModel.unscoped(),
696 attributes: [ 'id' ],
697 model: VideoChannelModel.unscoped(),
699 actorId: videoChannelActorId
707 return UserModel.findOne(query)
710 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
715 attributes: [ 'id' ],
716 model: AccountModel.unscoped(),
718 actorId: accountActorId
724 return UserModel.findOne(query)
727 static loadByLiveId (liveId: number): Promise<MUser> {
731 attributes: [ 'id' ],
732 model: AccountModel.unscoped(),
736 attributes: [ 'id' ],
737 model: VideoChannelModel.unscoped(),
741 attributes: [ 'id' ],
742 model: VideoModel.unscoped(),
747 model: VideoLiveModel.unscoped(),
762 return UserModel.unscoped().findOne(query)
765 static generateUserQuotaBaseSQL (options: {
766 whereUserId: '$userId' | '"UserModel"."id"'
770 const andWhere = options.daily === true
771 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
774 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
775 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
776 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
778 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
779 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
782 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
783 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
784 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
787 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
789 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
790 'GROUP BY "t1"."videoId"' +
794 static getTotalRawQuery (query: string, userId: number) {
797 type: QueryTypes.SELECT as QueryTypes.SELECT
800 return UserModel.sequelize.query<{ total: string }>(query, options)
801 .then(([ { total } ]) => {
802 if (total === null) return 0
804 return parseInt(total, 10)
808 static async getStats () {
809 function getActiveUsers (days: number) {
813 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
818 return UserModel.unscoped().count(query)
821 const totalUsers = await UserModel.unscoped().count()
822 const totalDailyActiveUsers = await getActiveUsers(1)
823 const totalWeeklyActiveUsers = await getActiveUsers(7)
824 const totalMonthlyActiveUsers = await getActiveUsers(30)
825 const totalHalfYearActiveUsers = await getActiveUsers(180)
829 totalDailyActiveUsers,
830 totalWeeklyActiveUsers,
831 totalMonthlyActiveUsers,
832 totalHalfYearActiveUsers
836 static autoComplete (search: string) {
840 [Op.like]: `%${search}%`
846 return UserModel.findAll(query)
847 .then(u => u.map(u => u.username))
850 hasRight (right: UserRight) {
851 return hasUserRight(this.role, right)
854 hasAdminFlag (flag: UserAdminFlag) {
855 return this.adminFlags & flag
858 isPasswordMatch (password: string) {
859 return comparePassword(password, this.password)
862 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
863 const videoQuotaUsed = this.get('videoQuotaUsed')
864 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
865 const videosCount = this.get('videosCount')
866 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
867 const abusesCreatedCount = this.get('abusesCreatedCount')
868 const videoCommentsCount = this.get('videoCommentsCount')
872 username: this.username,
874 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
876 pendingEmail: this.pendingEmail,
877 emailVerified: this.emailVerified,
879 nsfwPolicy: this.nsfwPolicy,
881 // FIXME: deprecated in 4.1
882 webTorrentEnabled: this.p2pEnabled,
883 p2pEnabled: this.p2pEnabled,
885 videosHistoryEnabled: this.videosHistoryEnabled,
886 autoPlayVideo: this.autoPlayVideo,
887 autoPlayNextVideo: this.autoPlayNextVideo,
888 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
889 videoLanguages: this.videoLanguages,
892 roleLabel: USER_ROLE_LABELS[this.role],
894 videoQuota: this.videoQuota,
895 videoQuotaDaily: this.videoQuotaDaily,
897 videoQuotaUsed: videoQuotaUsed !== undefined
898 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
901 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
902 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
905 videosCount: videosCount !== undefined
906 ? parseInt(videosCount + '', 10)
908 abusesCount: abusesCount
909 ? parseInt(abusesCount, 10)
911 abusesAcceptedCount: abusesAcceptedCount
912 ? parseInt(abusesAcceptedCount, 10)
914 abusesCreatedCount: abusesCreatedCount !== undefined
915 ? parseInt(abusesCreatedCount + '', 10)
917 videoCommentsCount: videoCommentsCount !== undefined
918 ? parseInt(videoCommentsCount + '', 10)
921 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
922 noWelcomeModal: this.noWelcomeModal,
923 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
925 blocked: this.blocked,
926 blockedReason: this.blockedReason,
928 account: this.Account.toFormattedJSON(),
930 notificationSettings: this.NotificationSetting
931 ? this.NotificationSetting.toFormattedJSON()
936 createdAt: this.createdAt,
938 pluginAuth: this.pluginAuth,
940 lastLoginDate: this.lastLoginDate
943 if (parameters.withAdminFlags) {
944 Object.assign(json, { adminFlags: this.adminFlags })
947 if (Array.isArray(this.Account.VideoChannels) === true) {
948 json.videoChannels = this.Account.VideoChannels
949 .map(c => c.toFormattedJSON())
951 if (v1.createdAt < v2.createdAt) return -1
952 if (v1.createdAt === v2.createdAt) return 0
961 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
962 const formatted = this.toFormattedJSON({ withAdminFlags: true })
964 const specialPlaylists = this.Account.VideoPlaylists
965 .map(p => ({ id: p.id, name: p.name, type: p.type }))
967 return Object.assign(formatted, { specialPlaylists })