1 import { values } from 'lodash'
2 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
23 } from 'sequelize-typescript'
24 import { TokensCache } from '@server/lib/auth/tokens-cache'
30 MUserNotifSettingChannelDefault,
31 MUserWithNotificationSetting,
33 } from '@server/types/models'
34 import { AttributesOnly } from '@shared/typescript-utils'
35 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
36 import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } 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,
56 isUserVideoQuotaDailyValid,
57 isUserVideoQuotaValid,
58 isUserVideosHistoryEnabledValid
59 } from '../../helpers/custom-validators/users'
60 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
61 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
62 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
63 import { AccountModel } from '../account/account'
64 import { ActorModel } from '../actor/actor'
65 import { ActorFollowModel } from '../actor/actor-follow'
66 import { ActorImageModel } from '../actor/actor-image'
67 import { OAuthTokenModel } from '../oauth/oauth-token'
68 import { getSort, throwIfNotValid } from '../utils'
69 import { VideoModel } from '../video/video'
70 import { VideoChannelModel } from '../video/video-channel'
71 import { VideoImportModel } from '../video/video-import'
72 import { VideoLiveModel } from '../video/video-live'
73 import { VideoPlaylistModel } from '../video/video-playlist'
74 import { UserNotificationSettingModel } from './user-notification-setting'
77 FOR_ME_API = 'FOR_ME_API',
78 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
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_STATS]: {
162 UserModel.generateUserQuotaBaseSQL({
164 whereUserId: '"UserModel"."id"'
173 'SELECT COUNT("video"."id") ' +
175 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
176 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
177 'WHERE "account"."userId" = "UserModel"."id"' +
185 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
187 'SELECT COUNT("abuse"."id") AS "abuses", ' +
188 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
190 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
191 'WHERE "account"."userId" = "UserModel"."id"' +
200 'SELECT COUNT("abuse"."id") ' +
202 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
203 'WHERE "account"."userId" = "UserModel"."id"' +
211 'SELECT COUNT("videoComment"."id") ' +
212 'FROM "videoComment" ' +
213 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
214 'WHERE "account"."userId" = "UserModel"."id"' +
227 fields: [ 'username' ],
236 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
239 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
244 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
250 @Column(DataType.STRING(400))
255 @Column(DataType.STRING(400))
260 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
262 emailVerified: boolean
265 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
266 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
267 nsfwPolicy: NSFWPolicyType
270 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
276 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
278 videosHistoryEnabled: boolean
282 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
284 autoPlayVideo: boolean
288 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
290 autoPlayNextVideo: boolean
295 'UserAutoPlayNextVideoPlaylist',
296 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
299 autoPlayNextVideoPlaylist: boolean
303 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
304 @Column(DataType.ARRAY(DataType.STRING))
305 videoLanguages: string[]
308 @Default(UserAdminFlag.NONE)
309 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
311 adminFlags?: UserAdminFlag
315 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
321 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
323 blockedReason: string
326 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
331 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
332 @Column(DataType.BIGINT)
336 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
337 @Column(DataType.BIGINT)
338 videoQuotaDaily: number
341 @Default(DEFAULT_USER_THEME_NAME)
342 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
349 'UserNoInstanceConfigWarningModal',
350 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
353 noInstanceConfigWarningModal: boolean
358 'UserNoWelcomeModal',
359 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
362 noWelcomeModal: boolean
367 'UserNoAccountSetupWarningModal',
368 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
371 noAccountSetupWarningModal: boolean
379 @Default(DataType.UUIDV4)
381 @Column(DataType.UUID)
395 @HasOne(() => AccountModel, {
396 foreignKey: 'userId',
400 Account: AccountModel
402 @HasOne(() => UserNotificationSettingModel, {
403 foreignKey: 'userId',
407 NotificationSetting: UserNotificationSettingModel
409 @HasMany(() => VideoImportModel, {
410 foreignKey: 'userId',
413 VideoImports: VideoImportModel[]
415 @HasMany(() => OAuthTokenModel, {
416 foreignKey: 'userId',
419 OAuthTokens: OAuthTokenModel[]
423 static cryptPasswordIfNeeded (instance: UserModel) {
424 if (instance.changed('password') && instance.password) {
425 return cryptPassword(instance.password)
427 instance.password = hash
435 static removeTokenCache (instance: UserModel) {
436 return TokensCache.Instance.clearCacheByUserId(instance.id)
439 static countTotal () {
443 static listForApi (parameters: {
450 const { start, count, sort, search, blocked } = parameters
451 const where: WhereOptions = {}
454 Object.assign(where, {
458 [Op.iLike]: '%' + search + '%'
463 [Op.iLike]: '%' + search + '%'
470 if (blocked !== undefined) {
471 Object.assign(where, {
476 const query: FindOptions = {
482 UserModel.generateUserQuotaBaseSQL({
484 whereUserId: '"UserModel"."id"'
494 order: getSort(sort),
499 UserModel.unscoped().count(query),
500 UserModel.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
582 if (withStats) scopes.push(ScopeNames.WITH_STATS)
584 return UserModel.scope(scopes).findByPk(id)
587 static loadByUsername (username: string): Promise<MUserDefault> {
594 return UserModel.findOne(query)
597 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
604 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
607 static loadByEmail (email: string): Promise<MUserDefault> {
614 return UserModel.findOne(query)
617 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
618 if (!email) email = username
623 where(fn('lower', col('username')), fn('lower', username) as any),
630 return UserModel.findOne(query)
633 static loadByVideoId (videoId: number): Promise<MUserDefault> {
638 attributes: [ 'id' ],
639 model: AccountModel.unscoped(),
643 attributes: [ 'id' ],
644 model: VideoChannelModel.unscoped(),
648 attributes: [ 'id' ],
649 model: VideoModel.unscoped(),
661 return UserModel.findOne(query)
664 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
669 attributes: [ 'id' ],
670 model: VideoImportModel.unscoped(),
678 return UserModel.findOne(query)
681 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
686 attributes: [ 'id' ],
687 model: AccountModel.unscoped(),
691 attributes: [ 'id' ],
692 model: VideoChannelModel.unscoped(),
694 actorId: videoChannelActorId
702 return UserModel.findOne(query)
705 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
710 attributes: [ 'id' ],
711 model: AccountModel.unscoped(),
713 actorId: accountActorId
719 return UserModel.findOne(query)
722 static loadByLiveId (liveId: number): Promise<MUser> {
726 attributes: [ 'id' ],
727 model: AccountModel.unscoped(),
731 attributes: [ 'id' ],
732 model: VideoChannelModel.unscoped(),
736 attributes: [ 'id' ],
737 model: VideoModel.unscoped(),
742 model: VideoLiveModel.unscoped(),
757 return UserModel.unscoped().findOne(query)
760 static generateUserQuotaBaseSQL (options: {
761 whereUserId: '$userId' | '"UserModel"."id"'
765 const andWhere = options.where
766 ? 'AND ' + options.where
769 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
770 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
771 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
773 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
774 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
777 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
778 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
779 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
782 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
784 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
785 'GROUP BY "t1"."videoId"' +
789 static getTotalRawQuery (query: string, userId: number) {
792 type: QueryTypes.SELECT as QueryTypes.SELECT
795 return UserModel.sequelize.query<{ total: string }>(query, options)
796 .then(([ { total } ]) => {
797 if (total === null) return 0
799 return parseInt(total, 10)
803 static async getStats () {
804 function getActiveUsers (days: number) {
808 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
813 return UserModel.count(query)
816 const totalUsers = await UserModel.count()
817 const totalDailyActiveUsers = await getActiveUsers(1)
818 const totalWeeklyActiveUsers = await getActiveUsers(7)
819 const totalMonthlyActiveUsers = await getActiveUsers(30)
820 const totalHalfYearActiveUsers = await getActiveUsers(180)
824 totalDailyActiveUsers,
825 totalWeeklyActiveUsers,
826 totalMonthlyActiveUsers,
827 totalHalfYearActiveUsers
831 static autoComplete (search: string) {
835 [Op.like]: `%${search}%`
841 return UserModel.findAll(query)
842 .then(u => u.map(u => u.username))
845 canGetVideo (video: MVideoWithRights) {
846 const videoUserId = video.VideoChannel.Account.userId
848 if (video.isBlacklisted()) {
849 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
852 if (video.privacy === VideoPrivacy.PRIVATE) {
853 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
856 if (video.privacy === VideoPrivacy.INTERNAL) return true
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 emailVerified: this.emailVerified,
890 nsfwPolicy: this.nsfwPolicy,
892 // FIXME: deprecated in 4.1
893 webTorrentEnabled: this.p2pEnabled,
894 p2pEnabled: this.p2pEnabled,
896 videosHistoryEnabled: this.videosHistoryEnabled,
897 autoPlayVideo: this.autoPlayVideo,
898 autoPlayNextVideo: this.autoPlayNextVideo,
899 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
900 videoLanguages: this.videoLanguages,
903 roleLabel: USER_ROLE_LABELS[this.role],
905 videoQuota: this.videoQuota,
906 videoQuotaDaily: this.videoQuotaDaily,
907 videoQuotaUsed: videoQuotaUsed !== undefined
908 ? parseInt(videoQuotaUsed + '', 10)
910 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
911 ? parseInt(videoQuotaUsedDaily + '', 10)
913 videosCount: videosCount !== undefined
914 ? parseInt(videosCount + '', 10)
916 abusesCount: abusesCount
917 ? parseInt(abusesCount, 10)
919 abusesAcceptedCount: abusesAcceptedCount
920 ? parseInt(abusesAcceptedCount, 10)
922 abusesCreatedCount: abusesCreatedCount !== undefined
923 ? parseInt(abusesCreatedCount + '', 10)
925 videoCommentsCount: videoCommentsCount !== undefined
926 ? parseInt(videoCommentsCount + '', 10)
929 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
930 noWelcomeModal: this.noWelcomeModal,
931 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
933 blocked: this.blocked,
934 blockedReason: this.blockedReason,
936 account: this.Account.toFormattedJSON(),
938 notificationSettings: this.NotificationSetting
939 ? this.NotificationSetting.toFormattedJSON()
944 createdAt: this.createdAt,
946 pluginAuth: this.pluginAuth,
948 lastLoginDate: this.lastLoginDate
951 if (parameters.withAdminFlags) {
952 Object.assign(json, { adminFlags: this.adminFlags })
955 if (Array.isArray(this.Account.VideoChannels) === true) {
956 json.videoChannels = this.Account.VideoChannels
957 .map(c => c.toFormattedJSON())
959 if (v1.createdAt < v2.createdAt) return -1
960 if (v1.createdAt === v2.createdAt) return 0
969 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
970 const formatted = this.toFormattedJSON({ withAdminFlags: true })
972 const specialPlaylists = this.Account.VideoPlaylists
973 .map(p => ({ id: p.id, name: p.name, type: p.type }))
975 return Object.assign(formatted, { specialPlaylists })