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'
25 import { LiveQuotaStore } from '@server/lib/live'
31 MUserNotifSettingChannelDefault,
32 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 } 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 { getAdminUsersSort, 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_QUOTA = 'WITH_QUOTA',
80 WITH_STATS = 'WITH_STATS'
83 @DefaultScope(() => ({
90 model: UserNotificationSettingModel,
96 [ScopeNames.FOR_ME_API]: {
102 model: VideoChannelModel.unscoped(),
109 model: ActorImageModel,
118 attributes: [ 'id', 'name', 'type' ],
119 model: VideoPlaylistModel.unscoped(),
123 [Op.ne]: VideoPlaylistType.REGULAR
130 model: UserNotificationSettingModel,
135 [ScopeNames.WITH_VIDEOCHANNELS]: {
141 model: VideoChannelModel
144 attributes: [ 'id', 'name', 'type' ],
145 model: VideoPlaylistModel.unscoped(),
149 [Op.ne]: VideoPlaylistType.REGULAR
157 [ScopeNames.WITH_QUOTA]: {
163 UserModel.generateUserQuotaBaseSQL({
165 whereUserId: '"UserModel"."id"',
175 UserModel.generateUserQuotaBaseSQL({
177 whereUserId: '"UserModel"."id"',
182 'videoQuotaUsedDaily'
187 [ScopeNames.WITH_STATS]: {
193 'SELECT COUNT("video"."id") ' +
195 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
196 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
197 'WHERE "account"."userId" = "UserModel"."id"' +
205 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
207 'SELECT COUNT("abuse"."id") AS "abuses", ' +
208 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
210 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
211 'WHERE "account"."userId" = "UserModel"."id"' +
220 'SELECT COUNT("abuse"."id") ' +
222 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
223 'WHERE "account"."userId" = "UserModel"."id"' +
231 'SELECT COUNT("videoComment"."id") ' +
232 'FROM "videoComment" ' +
233 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
234 'WHERE "account"."userId" = "UserModel"."id"' +
247 fields: [ 'username' ],
256 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
259 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
264 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
270 @Column(DataType.STRING(400))
275 @Column(DataType.STRING(400))
280 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
282 emailVerified: boolean
285 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
286 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
287 nsfwPolicy: NSFWPolicyType
290 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
296 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
298 videosHistoryEnabled: boolean
302 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
304 autoPlayVideo: boolean
308 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
310 autoPlayNextVideo: boolean
315 'UserAutoPlayNextVideoPlaylist',
316 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
319 autoPlayNextVideoPlaylist: boolean
323 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
324 @Column(DataType.ARRAY(DataType.STRING))
325 videoLanguages: string[]
328 @Default(UserAdminFlag.NONE)
329 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
331 adminFlags?: UserAdminFlag
335 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
341 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
343 blockedReason: string
346 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
351 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
352 @Column(DataType.BIGINT)
356 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
357 @Column(DataType.BIGINT)
358 videoQuotaDaily: number
361 @Default(DEFAULT_USER_THEME_NAME)
362 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
369 'UserNoInstanceConfigWarningModal',
370 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
373 noInstanceConfigWarningModal: boolean
378 'UserNoWelcomeModal',
379 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
382 noWelcomeModal: boolean
387 'UserNoAccountSetupWarningModal',
388 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
391 noAccountSetupWarningModal: boolean
399 @Default(DataType.UUIDV4)
401 @Column(DataType.UUID)
415 @HasOne(() => AccountModel, {
416 foreignKey: 'userId',
420 Account: AccountModel
422 @HasOne(() => UserNotificationSettingModel, {
423 foreignKey: 'userId',
427 NotificationSetting: UserNotificationSettingModel
429 @HasMany(() => VideoImportModel, {
430 foreignKey: 'userId',
433 VideoImports: VideoImportModel[]
435 @HasMany(() => OAuthTokenModel, {
436 foreignKey: 'userId',
439 OAuthTokens: OAuthTokenModel[]
443 static cryptPasswordIfNeeded (instance: UserModel) {
444 if (instance.changed('password') && instance.password) {
445 return cryptPassword(instance.password)
447 instance.password = hash
455 static removeTokenCache (instance: UserModel) {
456 return TokensCache.Instance.clearCacheByUserId(instance.id)
459 static countTotal () {
463 static listForAdminApi (parameters: {
470 const { start, count, sort, search, blocked } = parameters
471 const where: WhereOptions = {}
474 Object.assign(where, {
478 [Op.iLike]: '%' + search + '%'
483 [Op.iLike]: '%' + search + '%'
490 if (blocked !== undefined) {
491 Object.assign(where, {
496 const query: FindOptions = {
499 order: getAdminUsersSort(sort),
504 UserModel.unscoped().count(query),
505 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
506 ]).then(([ total, data ]) => ({ total, data }))
509 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
510 const roles = Object.keys(USER_ROLE_LABELS)
511 .map(k => parseInt(k, 10) as UserRole)
512 .filter(role => hasUserRight(role, right))
522 return UserModel.findAll(query)
525 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
529 model: UserNotificationSettingModel.unscoped(),
533 attributes: [ 'userId' ],
534 model: AccountModel.unscoped(),
539 model: ActorModel.unscoped(),
547 as: 'ActorFollowings',
548 model: ActorFollowModel.unscoped(),
551 targetActorId: actorId
561 return UserModel.unscoped().findAll(query)
564 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
571 return UserModel.findAll(query)
574 static loadById (id: number): Promise<MUser> {
575 return UserModel.unscoped().findByPk(id)
578 static loadByIdFull (id: number): Promise<MUserDefault> {
579 return UserModel.findByPk(id)
582 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
584 ScopeNames.WITH_VIDEOCHANNELS
588 scopes.push(ScopeNames.WITH_QUOTA)
589 scopes.push(ScopeNames.WITH_STATS)
592 return UserModel.scope(scopes).findByPk(id)
595 static loadByUsername (username: string): Promise<MUserDefault> {
602 return UserModel.findOne(query)
605 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
612 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
615 static loadByEmail (email: string): Promise<MUserDefault> {
622 return UserModel.findOne(query)
625 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
626 if (!email) email = username
631 where(fn('lower', col('username')), fn('lower', username) as any),
638 return UserModel.findOne(query)
641 static loadByVideoId (videoId: number): Promise<MUserDefault> {
646 attributes: [ 'id' ],
647 model: AccountModel.unscoped(),
651 attributes: [ 'id' ],
652 model: VideoChannelModel.unscoped(),
656 attributes: [ 'id' ],
657 model: VideoModel.unscoped(),
669 return UserModel.findOne(query)
672 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
677 attributes: [ 'id' ],
678 model: VideoImportModel.unscoped(),
686 return UserModel.findOne(query)
689 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
694 attributes: [ 'id' ],
695 model: AccountModel.unscoped(),
699 attributes: [ 'id' ],
700 model: VideoChannelModel.unscoped(),
702 actorId: videoChannelActorId
710 return UserModel.findOne(query)
713 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
718 attributes: [ 'id' ],
719 model: AccountModel.unscoped(),
721 actorId: accountActorId
727 return UserModel.findOne(query)
730 static loadByLiveId (liveId: number): Promise<MUser> {
734 attributes: [ 'id' ],
735 model: AccountModel.unscoped(),
739 attributes: [ 'id' ],
740 model: VideoChannelModel.unscoped(),
744 attributes: [ 'id' ],
745 model: VideoModel.unscoped(),
750 model: VideoLiveModel.unscoped(),
765 return UserModel.unscoped().findOne(query)
768 static generateUserQuotaBaseSQL (options: {
769 whereUserId: '$userId' | '"UserModel"."id"'
773 const andWhere = options.daily === true
774 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
777 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
778 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
779 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
781 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
782 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
785 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
786 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
787 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
790 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
792 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
793 'GROUP BY "t1"."videoId"' +
797 static getTotalRawQuery (query: string, userId: number) {
800 type: QueryTypes.SELECT as QueryTypes.SELECT
803 return UserModel.sequelize.query<{ total: string }>(query, options)
804 .then(([ { total } ]) => {
805 if (total === null) return 0
807 return parseInt(total, 10)
811 static async getStats () {
812 function getActiveUsers (days: number) {
816 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
821 return UserModel.unscoped().count(query)
824 const totalUsers = await UserModel.unscoped().count()
825 const totalDailyActiveUsers = await getActiveUsers(1)
826 const totalWeeklyActiveUsers = await getActiveUsers(7)
827 const totalMonthlyActiveUsers = await getActiveUsers(30)
828 const totalHalfYearActiveUsers = await getActiveUsers(180)
832 totalDailyActiveUsers,
833 totalWeeklyActiveUsers,
834 totalMonthlyActiveUsers,
835 totalHalfYearActiveUsers
839 static autoComplete (search: string) {
843 [Op.like]: `%${search}%`
849 return UserModel.findAll(query)
850 .then(u => u.map(u => u.username))
853 hasRight (right: UserRight) {
854 return hasUserRight(this.role, right)
857 hasAdminFlag (flag: UserAdminFlag) {
858 return this.adminFlags & flag
861 isPasswordMatch (password: string) {
862 return comparePassword(password, this.password)
865 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
866 const videoQuotaUsed = this.get('videoQuotaUsed')
867 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
868 const videosCount = this.get('videosCount')
869 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
870 const abusesCreatedCount = this.get('abusesCreatedCount')
871 const videoCommentsCount = this.get('videoCommentsCount')
875 username: this.username,
877 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
879 pendingEmail: this.pendingEmail,
880 emailVerified: this.emailVerified,
882 nsfwPolicy: this.nsfwPolicy,
884 // FIXME: deprecated in 4.1
885 webTorrentEnabled: this.p2pEnabled,
886 p2pEnabled: this.p2pEnabled,
888 videosHistoryEnabled: this.videosHistoryEnabled,
889 autoPlayVideo: this.autoPlayVideo,
890 autoPlayNextVideo: this.autoPlayNextVideo,
891 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
892 videoLanguages: this.videoLanguages,
895 roleLabel: USER_ROLE_LABELS[this.role],
897 videoQuota: this.videoQuota,
898 videoQuotaDaily: this.videoQuotaDaily,
900 videoQuotaUsed: videoQuotaUsed !== undefined
901 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
904 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
905 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
908 videosCount: videosCount !== undefined
909 ? parseInt(videosCount + '', 10)
911 abusesCount: abusesCount
912 ? parseInt(abusesCount, 10)
914 abusesAcceptedCount: abusesAcceptedCount
915 ? parseInt(abusesAcceptedCount, 10)
917 abusesCreatedCount: abusesCreatedCount !== undefined
918 ? parseInt(abusesCreatedCount + '', 10)
920 videoCommentsCount: videoCommentsCount !== undefined
921 ? parseInt(videoCommentsCount + '', 10)
924 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
925 noWelcomeModal: this.noWelcomeModal,
926 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
928 blocked: this.blocked,
929 blockedReason: this.blockedReason,
931 account: this.Account.toFormattedJSON(),
933 notificationSettings: this.NotificationSetting
934 ? this.NotificationSetting.toFormattedJSON()
939 createdAt: this.createdAt,
941 pluginAuth: this.pluginAuth,
943 lastLoginDate: this.lastLoginDate
946 if (parameters.withAdminFlags) {
947 Object.assign(json, { adminFlags: this.adminFlags })
950 if (Array.isArray(this.Account.VideoChannels) === true) {
951 json.videoChannels = this.Account.VideoChannels
952 .map(c => c.toFormattedJSON())
954 if (v1.createdAt < v2.createdAt) return -1
955 if (v1.createdAt === v2.createdAt) return 0
964 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
965 const formatted = this.toFormattedJSON({ withAdminFlags: true })
967 const specialPlaylists = this.Account.VideoPlaylists
968 .map(p => ({ id: p.id, name: p.name, type: p.type }))
970 return Object.assign(formatted, { specialPlaylists })