1 import { values } from 'lodash'
2 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
23 } from 'sequelize-typescript'
29 MUserNotifSettingChannelDefault,
30 MUserWithNotificationSetting,
33 } from '@server/types/models'
34 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
35 import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } 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 isNoInstanceConfigWarningModal,
43 isUserAdminFlagsValid,
44 isUserAutoPlayNextVideoPlaylistValid,
45 isUserAutoPlayNextVideoValid,
46 isUserAutoPlayVideoValid,
47 isUserBlockedReasonValid,
49 isUserEmailVerifiedValid,
50 isUserNSFWPolicyValid,
55 isUserVideoQuotaDailyValid,
56 isUserVideoQuotaValid,
57 isUserVideosHistoryEnabledValid,
58 isUserWebTorrentEnabledValid
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 { clearCacheByUserId } from '../../lib/oauth-model'
63 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
64 import { ActorModel } from '../activitypub/actor'
65 import { ActorFollowModel } from '../activitypub/actor-follow'
66 import { OAuthTokenModel } from '../oauth/oauth-token'
67 import { getSort, 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 { AccountModel } from './account'
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
104 attributes: [ 'id', 'name', 'type' ],
105 model: VideoPlaylistModel.unscoped(),
109 [Op.ne]: VideoPlaylistType.REGULAR
116 model: UserNotificationSettingModel,
121 [ScopeNames.WITH_VIDEOCHANNELS]: {
127 model: VideoChannelModel
130 attributes: [ 'id', 'name', 'type' ],
131 model: VideoPlaylistModel.unscoped(),
135 [Op.ne]: VideoPlaylistType.REGULAR
143 [ScopeNames.WITH_STATS]: {
149 UserModel.generateUserQuotaBaseSQL({
151 whereUserId: '"UserModel"."id"'
160 'SELECT COUNT("video"."id") ' +
162 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
163 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
164 'WHERE "account"."userId" = "UserModel"."id"' +
172 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
174 'SELECT COUNT("abuse"."id") AS "abuses", ' +
175 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
177 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
178 'WHERE "account"."userId" = "UserModel"."id"' +
187 'SELECT COUNT("abuse"."id") ' +
189 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
190 'WHERE "account"."userId" = "UserModel"."id"' +
198 'SELECT COUNT("videoComment"."id") ' +
199 'FROM "videoComment" ' +
200 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
201 'WHERE "account"."userId" = "UserModel"."id"' +
214 fields: [ 'username' ],
223 export class UserModel extends Model {
226 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
231 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
237 @Column(DataType.STRING(400))
242 @Column(DataType.STRING(400))
247 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
249 emailVerified: boolean
252 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
253 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
254 nsfwPolicy: NSFWPolicyType
258 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
260 webTorrentEnabled: boolean
264 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
266 videosHistoryEnabled: boolean
270 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
272 autoPlayVideo: boolean
276 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
278 autoPlayNextVideo: boolean
283 'UserAutoPlayNextVideoPlaylist',
284 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
287 autoPlayNextVideoPlaylist: boolean
291 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
292 @Column(DataType.ARRAY(DataType.STRING))
293 videoLanguages: string[]
296 @Default(UserAdminFlag.NONE)
297 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
299 adminFlags?: UserAdminFlag
303 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
309 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
311 blockedReason: string
314 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
319 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
320 @Column(DataType.BIGINT)
324 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
325 @Column(DataType.BIGINT)
326 videoQuotaDaily: number
329 @Default(DEFAULT_USER_THEME_NAME)
330 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
337 'UserNoInstanceConfigWarningModal',
338 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
341 noInstanceConfigWarningModal: boolean
346 'UserNoInstanceConfigWarningModal',
347 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
350 noWelcomeModal: boolean
358 @Default(DataType.UUIDV4)
360 @Column(DataType.UUID)
374 @HasOne(() => AccountModel, {
375 foreignKey: 'userId',
379 Account: AccountModel
381 @HasOne(() => UserNotificationSettingModel, {
382 foreignKey: 'userId',
386 NotificationSetting: UserNotificationSettingModel
388 @HasMany(() => VideoImportModel, {
389 foreignKey: 'userId',
392 VideoImports: VideoImportModel[]
394 @HasMany(() => OAuthTokenModel, {
395 foreignKey: 'userId',
398 OAuthTokens: OAuthTokenModel[]
402 static cryptPasswordIfNeeded (instance: UserModel) {
403 if (instance.changed('password') && instance.password) {
404 return cryptPassword(instance.password)
406 instance.password = hash
414 static removeTokenCache (instance: UserModel) {
415 return clearCacheByUserId(instance.id)
418 static countTotal () {
422 static listForApi (parameters: {
429 const { start, count, sort, search, blocked } = parameters
430 const where: WhereOptions = {}
433 Object.assign(where, {
437 [Op.iLike]: '%' + search + '%'
442 [Op.iLike]: '%' + search + '%'
449 if (blocked !== undefined) {
450 Object.assign(where, {
455 const query: FindOptions = {
461 UserModel.generateUserQuotaBaseSQL({
463 whereUserId: '"UserModel"."id"'
468 ] as any // FIXME: typings
473 order: getSort(sort),
477 return UserModel.findAndCountAll(query)
478 .then(({ rows, count }) => {
486 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
487 const roles = Object.keys(USER_ROLE_LABELS)
488 .map(k => parseInt(k, 10) as UserRole)
489 .filter(role => hasUserRight(role, right))
499 return UserModel.findAll(query)
502 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
506 model: UserNotificationSettingModel.unscoped(),
510 attributes: [ 'userId' ],
511 model: AccountModel.unscoped(),
516 model: ActorModel.unscoped(),
524 as: 'ActorFollowings',
525 model: ActorFollowModel.unscoped(),
528 targetActorId: actorId
538 return UserModel.unscoped().findAll(query)
541 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
548 return UserModel.findAll(query)
551 static loadById (id: number): Promise<MUser> {
552 return UserModel.unscoped().findByPk(id)
555 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
557 ScopeNames.WITH_VIDEOCHANNELS
560 if (withStats) scopes.push(ScopeNames.WITH_STATS)
562 return UserModel.scope(scopes).findByPk(id)
565 static loadByUsername (username: string): Promise<MUserDefault> {
572 return UserModel.findOne(query)
575 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
582 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
585 static loadByEmail (email: string): Promise<MUserDefault> {
592 return UserModel.findOne(query)
595 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
596 if (!email) email = username
601 where(fn('lower', col('username')), fn('lower', username)),
608 return UserModel.findOne(query)
611 static loadByVideoId (videoId: number): Promise<MUserDefault> {
616 attributes: [ 'id' ],
617 model: AccountModel.unscoped(),
621 attributes: [ 'id' ],
622 model: VideoChannelModel.unscoped(),
626 attributes: [ 'id' ],
627 model: VideoModel.unscoped(),
639 return UserModel.findOne(query)
642 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
647 attributes: [ 'id' ],
648 model: VideoImportModel.unscoped(),
656 return UserModel.findOne(query)
659 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
664 attributes: [ 'id' ],
665 model: AccountModel.unscoped(),
669 attributes: [ 'id' ],
670 model: VideoChannelModel.unscoped(),
672 actorId: videoChannelActorId
680 return UserModel.findOne(query)
683 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
688 attributes: [ 'id' ],
689 model: AccountModel.unscoped(),
691 actorId: accountActorId
697 return UserModel.findOne(query)
700 static loadByLiveId (liveId: number): Promise<MUser> {
704 attributes: [ 'id' ],
705 model: AccountModel.unscoped(),
709 attributes: [ 'id' ],
710 model: VideoChannelModel.unscoped(),
714 attributes: [ 'id' ],
715 model: VideoModel.unscoped(),
720 model: VideoLiveModel.unscoped(),
735 return UserModel.unscoped().findOne(query)
738 static generateUserQuotaBaseSQL (options: {
739 whereUserId: '$userId' | '"UserModel"."id"'
743 const andWhere = options.where
744 ? 'AND ' + options.where
747 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
748 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
749 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
751 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
752 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
755 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
756 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
757 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
760 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
762 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
763 'GROUP BY "t1"."videoId"' +
767 static getTotalRawQuery (query: string, userId: number) {
770 type: QueryTypes.SELECT as QueryTypes.SELECT
773 return UserModel.sequelize.query<{ total: string }>(query, options)
774 .then(([ { total } ]) => {
775 if (total === null) return 0
777 return parseInt(total, 10)
781 static async getStats () {
782 function getActiveUsers (days: number) {
786 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
791 return UserModel.count(query)
794 const totalUsers = await UserModel.count()
795 const totalDailyActiveUsers = await getActiveUsers(1)
796 const totalWeeklyActiveUsers = await getActiveUsers(7)
797 const totalMonthlyActiveUsers = await getActiveUsers(30)
798 const totalHalfYearActiveUsers = await getActiveUsers(180)
802 totalDailyActiveUsers,
803 totalWeeklyActiveUsers,
804 totalMonthlyActiveUsers,
805 totalHalfYearActiveUsers
809 static autoComplete (search: string) {
813 [Op.like]: `%${search}%`
819 return UserModel.findAll(query)
820 .then(u => u.map(u => u.username))
823 canGetVideo (video: MVideoWithRights) {
824 const videoUserId = video.VideoChannel.Account.userId
826 if (video.isBlacklisted()) {
827 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
830 if (video.privacy === VideoPrivacy.PRIVATE) {
831 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
834 if (video.privacy === VideoPrivacy.INTERNAL) return true
839 hasRight (right: UserRight) {
840 return hasUserRight(this.role, right)
843 hasAdminFlag (flag: UserAdminFlag) {
844 return this.adminFlags & flag
847 isPasswordMatch (password: string) {
848 return comparePassword(password, this.password)
851 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
852 const videoQuotaUsed = this.get('videoQuotaUsed')
853 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
854 const videosCount = this.get('videosCount')
855 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
856 const abusesCreatedCount = this.get('abusesCreatedCount')
857 const videoCommentsCount = this.get('videoCommentsCount')
861 username: this.username,
863 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
865 pendingEmail: this.pendingEmail,
866 emailVerified: this.emailVerified,
868 nsfwPolicy: this.nsfwPolicy,
869 webTorrentEnabled: this.webTorrentEnabled,
870 videosHistoryEnabled: this.videosHistoryEnabled,
871 autoPlayVideo: this.autoPlayVideo,
872 autoPlayNextVideo: this.autoPlayNextVideo,
873 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
874 videoLanguages: this.videoLanguages,
877 roleLabel: USER_ROLE_LABELS[this.role],
879 videoQuota: this.videoQuota,
880 videoQuotaDaily: this.videoQuotaDaily,
881 videoQuotaUsed: videoQuotaUsed !== undefined
882 ? parseInt(videoQuotaUsed + '', 10)
884 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
885 ? parseInt(videoQuotaUsedDaily + '', 10)
887 videosCount: videosCount !== undefined
888 ? parseInt(videosCount + '', 10)
890 abusesCount: abusesCount
891 ? parseInt(abusesCount, 10)
893 abusesAcceptedCount: abusesAcceptedCount
894 ? parseInt(abusesAcceptedCount, 10)
896 abusesCreatedCount: abusesCreatedCount !== undefined
897 ? parseInt(abusesCreatedCount + '', 10)
899 videoCommentsCount: videoCommentsCount !== undefined
900 ? parseInt(videoCommentsCount + '', 10)
903 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
904 noWelcomeModal: this.noWelcomeModal,
906 blocked: this.blocked,
907 blockedReason: this.blockedReason,
909 account: this.Account.toFormattedJSON(),
911 notificationSettings: this.NotificationSetting
912 ? this.NotificationSetting.toFormattedJSON()
917 createdAt: this.createdAt,
919 pluginAuth: this.pluginAuth,
921 lastLoginDate: this.lastLoginDate
924 if (parameters.withAdminFlags) {
925 Object.assign(json, { adminFlags: this.adminFlags })
928 if (Array.isArray(this.Account.VideoChannels) === true) {
929 json.videoChannels = this.Account.VideoChannels
930 .map(c => c.toFormattedJSON())
932 if (v1.createdAt < v2.createdAt) return -1
933 if (v1.createdAt === v2.createdAt) return 0
942 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
943 const formatted = this.toFormattedJSON()
945 const specialPlaylists = this.Account.VideoPlaylists
946 .map(p => ({ id: p.id, name: p.name, type: p.type }))
948 return Object.assign(formatted, { specialPlaylists })