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/core-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,
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 { 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
271 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
273 webTorrentEnabled: boolean
277 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
279 videosHistoryEnabled: boolean
283 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
285 autoPlayVideo: boolean
289 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
291 autoPlayNextVideo: boolean
296 'UserAutoPlayNextVideoPlaylist',
297 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
300 autoPlayNextVideoPlaylist: boolean
304 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
305 @Column(DataType.ARRAY(DataType.STRING))
306 videoLanguages: string[]
309 @Default(UserAdminFlag.NONE)
310 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
312 adminFlags?: UserAdminFlag
316 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
322 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
324 blockedReason: string
327 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
332 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
333 @Column(DataType.BIGINT)
337 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
338 @Column(DataType.BIGINT)
339 videoQuotaDaily: number
342 @Default(DEFAULT_USER_THEME_NAME)
343 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
350 'UserNoInstanceConfigWarningModal',
351 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
354 noInstanceConfigWarningModal: boolean
359 'UserNoWelcomeModal',
360 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
363 noWelcomeModal: boolean
368 'UserNoAccountSetupWarningModal',
369 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
372 noAccountSetupWarningModal: boolean
380 @Default(DataType.UUIDV4)
382 @Column(DataType.UUID)
396 @HasOne(() => AccountModel, {
397 foreignKey: 'userId',
401 Account: AccountModel
403 @HasOne(() => UserNotificationSettingModel, {
404 foreignKey: 'userId',
408 NotificationSetting: UserNotificationSettingModel
410 @HasMany(() => VideoImportModel, {
411 foreignKey: 'userId',
414 VideoImports: VideoImportModel[]
416 @HasMany(() => OAuthTokenModel, {
417 foreignKey: 'userId',
420 OAuthTokens: OAuthTokenModel[]
424 static cryptPasswordIfNeeded (instance: UserModel) {
425 if (instance.changed('password') && instance.password) {
426 return cryptPassword(instance.password)
428 instance.password = hash
436 static removeTokenCache (instance: UserModel) {
437 return TokensCache.Instance.clearCacheByUserId(instance.id)
440 static countTotal () {
444 static listForApi (parameters: {
451 const { start, count, sort, search, blocked } = parameters
452 const where: WhereOptions = {}
455 Object.assign(where, {
459 [Op.iLike]: '%' + search + '%'
464 [Op.iLike]: '%' + search + '%'
471 if (blocked !== undefined) {
472 Object.assign(where, {
477 const query: FindOptions = {
483 UserModel.generateUserQuotaBaseSQL({
485 whereUserId: '"UserModel"."id"'
490 ] as any // FIXME: typings
495 order: getSort(sort),
499 return UserModel.findAndCountAll(query)
500 .then(({ rows, count }) => {
508 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
509 const roles = Object.keys(USER_ROLE_LABELS)
510 .map(k => parseInt(k, 10) as UserRole)
511 .filter(role => hasUserRight(role, right))
521 return UserModel.findAll(query)
524 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
528 model: UserNotificationSettingModel.unscoped(),
532 attributes: [ 'userId' ],
533 model: AccountModel.unscoped(),
538 model: ActorModel.unscoped(),
546 as: 'ActorFollowings',
547 model: ActorFollowModel.unscoped(),
550 targetActorId: actorId
560 return UserModel.unscoped().findAll(query)
563 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
570 return UserModel.findAll(query)
573 static loadById (id: number): Promise<MUser> {
574 return UserModel.unscoped().findByPk(id)
577 static loadByIdFull (id: number): Promise<MUserDefault> {
578 return UserModel.findByPk(id)
581 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
583 ScopeNames.WITH_VIDEOCHANNELS
586 if (withStats) scopes.push(ScopeNames.WITH_STATS)
588 return UserModel.scope(scopes).findByPk(id)
591 static loadByUsername (username: string): Promise<MUserDefault> {
598 return UserModel.findOne(query)
601 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
608 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
611 static loadByEmail (email: string): Promise<MUserDefault> {
618 return UserModel.findOne(query)
621 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
622 if (!email) email = username
627 where(fn('lower', col('username')), fn('lower', username)),
634 return UserModel.findOne(query)
637 static loadByVideoId (videoId: number): Promise<MUserDefault> {
642 attributes: [ 'id' ],
643 model: AccountModel.unscoped(),
647 attributes: [ 'id' ],
648 model: VideoChannelModel.unscoped(),
652 attributes: [ 'id' ],
653 model: VideoModel.unscoped(),
665 return UserModel.findOne(query)
668 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
673 attributes: [ 'id' ],
674 model: VideoImportModel.unscoped(),
682 return UserModel.findOne(query)
685 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
690 attributes: [ 'id' ],
691 model: AccountModel.unscoped(),
695 attributes: [ 'id' ],
696 model: VideoChannelModel.unscoped(),
698 actorId: videoChannelActorId
706 return UserModel.findOne(query)
709 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
714 attributes: [ 'id' ],
715 model: AccountModel.unscoped(),
717 actorId: accountActorId
723 return UserModel.findOne(query)
726 static loadByLiveId (liveId: number): Promise<MUser> {
730 attributes: [ 'id' ],
731 model: AccountModel.unscoped(),
735 attributes: [ 'id' ],
736 model: VideoChannelModel.unscoped(),
740 attributes: [ 'id' ],
741 model: VideoModel.unscoped(),
746 model: VideoLiveModel.unscoped(),
761 return UserModel.unscoped().findOne(query)
764 static generateUserQuotaBaseSQL (options: {
765 whereUserId: '$userId' | '"UserModel"."id"'
769 const andWhere = options.where
770 ? 'AND ' + options.where
773 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
774 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
775 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
777 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
778 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
781 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
782 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
783 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
786 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
788 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
789 'GROUP BY "t1"."videoId"' +
793 static getTotalRawQuery (query: string, userId: number) {
796 type: QueryTypes.SELECT as QueryTypes.SELECT
799 return UserModel.sequelize.query<{ total: string }>(query, options)
800 .then(([ { total } ]) => {
801 if (total === null) return 0
803 return parseInt(total, 10)
807 static async getStats () {
808 function getActiveUsers (days: number) {
812 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
817 return UserModel.count(query)
820 const totalUsers = await UserModel.count()
821 const totalDailyActiveUsers = await getActiveUsers(1)
822 const totalWeeklyActiveUsers = await getActiveUsers(7)
823 const totalMonthlyActiveUsers = await getActiveUsers(30)
824 const totalHalfYearActiveUsers = await getActiveUsers(180)
828 totalDailyActiveUsers,
829 totalWeeklyActiveUsers,
830 totalMonthlyActiveUsers,
831 totalHalfYearActiveUsers
835 static autoComplete (search: string) {
839 [Op.like]: `%${search}%`
845 return UserModel.findAll(query)
846 .then(u => u.map(u => u.username))
849 canGetVideo (video: MVideoWithRights) {
850 const videoUserId = video.VideoChannel.Account.userId
852 if (video.isBlacklisted()) {
853 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
856 if (video.privacy === VideoPrivacy.PRIVATE) {
857 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
860 if (video.privacy === VideoPrivacy.INTERNAL) return true
865 hasRight (right: UserRight) {
866 return hasUserRight(this.role, right)
869 hasAdminFlag (flag: UserAdminFlag) {
870 return this.adminFlags & flag
873 isPasswordMatch (password: string) {
874 return comparePassword(password, this.password)
877 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
878 const videoQuotaUsed = this.get('videoQuotaUsed')
879 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
880 const videosCount = this.get('videosCount')
881 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
882 const abusesCreatedCount = this.get('abusesCreatedCount')
883 const videoCommentsCount = this.get('videoCommentsCount')
887 username: this.username,
889 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
891 pendingEmail: this.pendingEmail,
892 emailVerified: this.emailVerified,
894 nsfwPolicy: this.nsfwPolicy,
895 webTorrentEnabled: this.webTorrentEnabled,
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 })