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'
75 import { LiveQuotaStore } from '@server/lib/live'
76 import { logger } from '@server/helpers/logger'
79 FOR_ME_API = 'FOR_ME_API',
80 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
81 WITH_QUOTA = 'WITH_QUOTA',
82 WITH_STATS = 'WITH_STATS'
85 @DefaultScope(() => ({
92 model: UserNotificationSettingModel,
98 [ScopeNames.FOR_ME_API]: {
104 model: VideoChannelModel.unscoped(),
111 model: ActorImageModel,
120 attributes: [ 'id', 'name', 'type' ],
121 model: VideoPlaylistModel.unscoped(),
125 [Op.ne]: VideoPlaylistType.REGULAR
132 model: UserNotificationSettingModel,
137 [ScopeNames.WITH_VIDEOCHANNELS]: {
143 model: VideoChannelModel
146 attributes: [ 'id', 'name', 'type' ],
147 model: VideoPlaylistModel.unscoped(),
151 [Op.ne]: VideoPlaylistType.REGULAR
159 [ScopeNames.WITH_QUOTA]: {
165 UserModel.generateUserQuotaBaseSQL({
167 whereUserId: '"UserModel"."id"',
177 UserModel.generateUserQuotaBaseSQL({
179 whereUserId: '"UserModel"."id"',
184 'videoQuotaUsedDaily'
189 [ScopeNames.WITH_STATS]: {
195 'SELECT COUNT("video"."id") ' +
197 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
198 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
199 'WHERE "account"."userId" = "UserModel"."id"' +
207 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
209 'SELECT COUNT("abuse"."id") AS "abuses", ' +
210 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
212 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
213 'WHERE "account"."userId" = "UserModel"."id"' +
222 'SELECT COUNT("abuse"."id") ' +
224 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
225 'WHERE "account"."userId" = "UserModel"."id"' +
233 'SELECT COUNT("videoComment"."id") ' +
234 'FROM "videoComment" ' +
235 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
236 'WHERE "account"."userId" = "UserModel"."id"' +
249 fields: [ 'username' ],
258 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
261 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
266 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
272 @Column(DataType.STRING(400))
277 @Column(DataType.STRING(400))
282 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
284 emailVerified: boolean
287 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
288 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
289 nsfwPolicy: NSFWPolicyType
292 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
298 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
300 videosHistoryEnabled: boolean
304 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
306 autoPlayVideo: boolean
310 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
312 autoPlayNextVideo: boolean
317 'UserAutoPlayNextVideoPlaylist',
318 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
321 autoPlayNextVideoPlaylist: boolean
325 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
326 @Column(DataType.ARRAY(DataType.STRING))
327 videoLanguages: string[]
330 @Default(UserAdminFlag.NONE)
331 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
333 adminFlags?: UserAdminFlag
337 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
343 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
345 blockedReason: string
348 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
353 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
354 @Column(DataType.BIGINT)
358 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
359 @Column(DataType.BIGINT)
360 videoQuotaDaily: number
363 @Default(DEFAULT_USER_THEME_NAME)
364 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
371 'UserNoInstanceConfigWarningModal',
372 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
375 noInstanceConfigWarningModal: boolean
380 'UserNoWelcomeModal',
381 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
384 noWelcomeModal: boolean
389 'UserNoAccountSetupWarningModal',
390 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
393 noAccountSetupWarningModal: boolean
401 @Default(DataType.UUIDV4)
403 @Column(DataType.UUID)
417 @HasOne(() => AccountModel, {
418 foreignKey: 'userId',
422 Account: AccountModel
424 @HasOne(() => UserNotificationSettingModel, {
425 foreignKey: 'userId',
429 NotificationSetting: UserNotificationSettingModel
431 @HasMany(() => VideoImportModel, {
432 foreignKey: 'userId',
435 VideoImports: VideoImportModel[]
437 @HasMany(() => OAuthTokenModel, {
438 foreignKey: 'userId',
441 OAuthTokens: OAuthTokenModel[]
445 static cryptPasswordIfNeeded (instance: UserModel) {
446 if (instance.changed('password') && instance.password) {
447 return cryptPassword(instance.password)
449 instance.password = hash
457 static removeTokenCache (instance: UserModel) {
458 return TokensCache.Instance.clearCacheByUserId(instance.id)
461 static countTotal () {
465 static listForApi (parameters: {
472 const { start, count, sort, search, blocked } = parameters
473 const where: WhereOptions = {}
476 Object.assign(where, {
480 [Op.iLike]: '%' + search + '%'
485 [Op.iLike]: '%' + search + '%'
492 if (blocked !== undefined) {
493 Object.assign(where, {
498 const query: FindOptions = {
501 order: getSort(sort),
506 UserModel.unscoped().count(query),
507 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
508 ]).then(([ total, data ]) => ({ total, data }))
511 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
512 const roles = Object.keys(USER_ROLE_LABELS)
513 .map(k => parseInt(k, 10) as UserRole)
514 .filter(role => hasUserRight(role, right))
524 return UserModel.findAll(query)
527 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
531 model: UserNotificationSettingModel.unscoped(),
535 attributes: [ 'userId' ],
536 model: AccountModel.unscoped(),
541 model: ActorModel.unscoped(),
549 as: 'ActorFollowings',
550 model: ActorFollowModel.unscoped(),
553 targetActorId: actorId
563 return UserModel.unscoped().findAll(query)
566 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
573 return UserModel.findAll(query)
576 static loadById (id: number): Promise<MUser> {
577 return UserModel.unscoped().findByPk(id)
580 static loadByIdFull (id: number): Promise<MUserDefault> {
581 return UserModel.findByPk(id)
584 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
586 ScopeNames.WITH_VIDEOCHANNELS
590 scopes.push(ScopeNames.WITH_QUOTA)
591 scopes.push(ScopeNames.WITH_STATS)
594 return UserModel.scope(scopes).findByPk(id)
597 static loadByUsername (username: string): Promise<MUserDefault> {
604 return UserModel.findOne(query)
607 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
614 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
617 static loadByEmail (email: string): Promise<MUserDefault> {
624 return UserModel.findOne(query)
627 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
628 if (!email) email = username
633 where(fn('lower', col('username')), fn('lower', username) as any),
640 return UserModel.findOne(query)
643 static loadByVideoId (videoId: number): Promise<MUserDefault> {
648 attributes: [ 'id' ],
649 model: AccountModel.unscoped(),
653 attributes: [ 'id' ],
654 model: VideoChannelModel.unscoped(),
658 attributes: [ 'id' ],
659 model: VideoModel.unscoped(),
671 return UserModel.findOne(query)
674 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
679 attributes: [ 'id' ],
680 model: VideoImportModel.unscoped(),
688 return UserModel.findOne(query)
691 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
696 attributes: [ 'id' ],
697 model: AccountModel.unscoped(),
701 attributes: [ 'id' ],
702 model: VideoChannelModel.unscoped(),
704 actorId: videoChannelActorId
712 return UserModel.findOne(query)
715 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
720 attributes: [ 'id' ],
721 model: AccountModel.unscoped(),
723 actorId: accountActorId
729 return UserModel.findOne(query)
732 static loadByLiveId (liveId: number): Promise<MUser> {
736 attributes: [ 'id' ],
737 model: AccountModel.unscoped(),
741 attributes: [ 'id' ],
742 model: VideoChannelModel.unscoped(),
746 attributes: [ 'id' ],
747 model: VideoModel.unscoped(),
752 model: VideoLiveModel.unscoped(),
767 return UserModel.unscoped().findOne(query)
770 static generateUserQuotaBaseSQL (options: {
771 whereUserId: '$userId' | '"UserModel"."id"'
775 const andWhere = options.daily === true
776 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
779 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
780 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
781 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
783 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
784 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
787 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
788 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
789 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
792 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
794 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
795 'GROUP BY "t1"."videoId"' +
799 static getTotalRawQuery (query: string, userId: number) {
802 type: QueryTypes.SELECT as QueryTypes.SELECT
805 return UserModel.sequelize.query<{ total: string }>(query, options)
806 .then(([ { total } ]) => {
807 if (total === null) return 0
809 return parseInt(total, 10)
813 static async getStats () {
814 function getActiveUsers (days: number) {
818 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
823 return UserModel.count(query)
826 const totalUsers = await UserModel.count()
827 const totalDailyActiveUsers = await getActiveUsers(1)
828 const totalWeeklyActiveUsers = await getActiveUsers(7)
829 const totalMonthlyActiveUsers = await getActiveUsers(30)
830 const totalHalfYearActiveUsers = await getActiveUsers(180)
834 totalDailyActiveUsers,
835 totalWeeklyActiveUsers,
836 totalMonthlyActiveUsers,
837 totalHalfYearActiveUsers
841 static autoComplete (search: string) {
845 [Op.like]: `%${search}%`
851 return UserModel.findAll(query)
852 .then(u => u.map(u => u.username))
855 canGetVideo (video: MVideoWithRights) {
856 const videoUserId = video.VideoChannel.Account.userId
858 if (video.isBlacklisted()) {
859 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
862 if (video.privacy === VideoPrivacy.PRIVATE) {
863 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
866 if (video.privacy === VideoPrivacy.INTERNAL) return true
871 hasRight (right: UserRight) {
872 return hasUserRight(this.role, right)
875 hasAdminFlag (flag: UserAdminFlag) {
876 return this.adminFlags & flag
879 isPasswordMatch (password: string) {
880 return comparePassword(password, this.password)
883 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
884 const videoQuotaUsed = this.get('videoQuotaUsed')
885 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
886 const videosCount = this.get('videosCount')
887 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
888 const abusesCreatedCount = this.get('abusesCreatedCount')
889 const videoCommentsCount = this.get('videoCommentsCount')
893 username: this.username,
895 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
897 pendingEmail: this.pendingEmail,
898 emailVerified: this.emailVerified,
900 nsfwPolicy: this.nsfwPolicy,
902 // FIXME: deprecated in 4.1
903 webTorrentEnabled: this.p2pEnabled,
904 p2pEnabled: this.p2pEnabled,
906 videosHistoryEnabled: this.videosHistoryEnabled,
907 autoPlayVideo: this.autoPlayVideo,
908 autoPlayNextVideo: this.autoPlayNextVideo,
909 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
910 videoLanguages: this.videoLanguages,
913 roleLabel: USER_ROLE_LABELS[this.role],
915 videoQuota: this.videoQuota,
916 videoQuotaDaily: this.videoQuotaDaily,
918 videoQuotaUsed: videoQuotaUsed !== undefined
919 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
922 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
923 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
926 videosCount: videosCount !== undefined
927 ? parseInt(videosCount + '', 10)
929 abusesCount: abusesCount
930 ? parseInt(abusesCount, 10)
932 abusesAcceptedCount: abusesAcceptedCount
933 ? parseInt(abusesAcceptedCount, 10)
935 abusesCreatedCount: abusesCreatedCount !== undefined
936 ? parseInt(abusesCreatedCount + '', 10)
938 videoCommentsCount: videoCommentsCount !== undefined
939 ? parseInt(videoCommentsCount + '', 10)
942 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
943 noWelcomeModal: this.noWelcomeModal,
944 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
946 blocked: this.blocked,
947 blockedReason: this.blockedReason,
949 account: this.Account.toFormattedJSON(),
951 notificationSettings: this.NotificationSetting
952 ? this.NotificationSetting.toFormattedJSON()
957 createdAt: this.createdAt,
959 pluginAuth: this.pluginAuth,
961 lastLoginDate: this.lastLoginDate
964 if (parameters.withAdminFlags) {
965 Object.assign(json, { adminFlags: this.adminFlags })
968 if (Array.isArray(this.Account.VideoChannels) === true) {
969 json.videoChannels = this.Account.VideoChannels
970 .map(c => c.toFormattedJSON())
972 if (v1.createdAt < v2.createdAt) return -1
973 if (v1.createdAt === v2.createdAt) return 0
982 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
983 const formatted = this.toFormattedJSON({ withAdminFlags: true })
985 const specialPlaylists = this.Account.VideoPlaylists
986 .map(p => ({ id: p.id, name: p.name, type: p.type }))
988 return Object.assign(formatted, { specialPlaylists })