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, { blocked })
494 const query: FindOptions = {
497 order: getAdminUsersSort(sort),
502 UserModel.unscoped().count(query),
503 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
504 ]).then(([ total, data ]) => ({ total, data }))
507 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
508 const roles = Object.keys(USER_ROLE_LABELS)
509 .map(k => parseInt(k, 10) as UserRole)
510 .filter(role => hasUserRight(role, right))
520 return UserModel.findAll(query)
523 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
527 model: UserNotificationSettingModel.unscoped(),
531 attributes: [ 'userId' ],
532 model: AccountModel.unscoped(),
537 model: ActorModel.unscoped(),
545 as: 'ActorFollowings',
546 model: ActorFollowModel.unscoped(),
549 targetActorId: actorId
559 return UserModel.unscoped().findAll(query)
562 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
569 return UserModel.findAll(query)
572 static loadById (id: number): Promise<MUser> {
573 return UserModel.unscoped().findByPk(id)
576 static loadByIdFull (id: number): Promise<MUserDefault> {
577 return UserModel.findByPk(id)
580 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
582 ScopeNames.WITH_VIDEOCHANNELS
586 scopes.push(ScopeNames.WITH_QUOTA)
587 scopes.push(ScopeNames.WITH_STATS)
590 return UserModel.scope(scopes).findByPk(id)
593 static loadByUsername (username: string): Promise<MUserDefault> {
600 return UserModel.findOne(query)
603 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
610 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
613 static loadByEmail (email: string): Promise<MUserDefault> {
620 return UserModel.findOne(query)
623 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
624 if (!email) email = username
629 where(fn('lower', col('username')), fn('lower', username) as any),
636 return UserModel.findOne(query)
639 static loadByVideoId (videoId: number): Promise<MUserDefault> {
644 attributes: [ 'id' ],
645 model: AccountModel.unscoped(),
649 attributes: [ 'id' ],
650 model: VideoChannelModel.unscoped(),
654 attributes: [ 'id' ],
655 model: VideoModel.unscoped(),
667 return UserModel.findOne(query)
670 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
675 attributes: [ 'id' ],
676 model: VideoImportModel.unscoped(),
684 return UserModel.findOne(query)
687 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
692 attributes: [ 'id' ],
693 model: AccountModel.unscoped(),
697 attributes: [ 'id' ],
698 model: VideoChannelModel.unscoped(),
700 actorId: videoChannelActorId
708 return UserModel.findOne(query)
711 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
716 attributes: [ 'id' ],
717 model: AccountModel.unscoped(),
719 actorId: accountActorId
725 return UserModel.findOne(query)
728 static loadByLiveId (liveId: number): Promise<MUser> {
732 attributes: [ 'id' ],
733 model: AccountModel.unscoped(),
737 attributes: [ 'id' ],
738 model: VideoChannelModel.unscoped(),
742 attributes: [ 'id' ],
743 model: VideoModel.unscoped(),
748 model: VideoLiveModel.unscoped(),
763 return UserModel.unscoped().findOne(query)
766 static generateUserQuotaBaseSQL (options: {
767 whereUserId: '$userId' | '"UserModel"."id"'
771 const andWhere = options.daily === true
772 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
775 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
776 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
777 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
779 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
780 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
783 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
784 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
785 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
788 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
790 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
791 'GROUP BY "t1"."videoId"' +
795 static getTotalRawQuery (query: string, userId: number) {
798 type: QueryTypes.SELECT as QueryTypes.SELECT
801 return UserModel.sequelize.query<{ total: string }>(query, options)
802 .then(([ { total } ]) => {
803 if (total === null) return 0
805 return parseInt(total, 10)
809 static async getStats () {
810 function getActiveUsers (days: number) {
814 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
819 return UserModel.unscoped().count(query)
822 const totalUsers = await UserModel.unscoped().count()
823 const totalDailyActiveUsers = await getActiveUsers(1)
824 const totalWeeklyActiveUsers = await getActiveUsers(7)
825 const totalMonthlyActiveUsers = await getActiveUsers(30)
826 const totalHalfYearActiveUsers = await getActiveUsers(180)
830 totalDailyActiveUsers,
831 totalWeeklyActiveUsers,
832 totalMonthlyActiveUsers,
833 totalHalfYearActiveUsers
837 static autoComplete (search: string) {
841 [Op.like]: `%${search}%`
847 return UserModel.findAll(query)
848 .then(u => u.map(u => u.username))
851 hasRight (right: UserRight) {
852 return hasUserRight(this.role, right)
855 hasAdminFlag (flag: UserAdminFlag) {
856 return this.adminFlags & flag
859 isPasswordMatch (password: string) {
860 return comparePassword(password, this.password)
863 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
864 const videoQuotaUsed = this.get('videoQuotaUsed')
865 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
866 const videosCount = this.get('videosCount')
867 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
868 const abusesCreatedCount = this.get('abusesCreatedCount')
869 const videoCommentsCount = this.get('videoCommentsCount')
873 username: this.username,
875 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
877 pendingEmail: this.pendingEmail,
878 emailVerified: this.emailVerified,
880 nsfwPolicy: this.nsfwPolicy,
882 // FIXME: deprecated in 4.1
883 webTorrentEnabled: this.p2pEnabled,
884 p2pEnabled: this.p2pEnabled,
886 videosHistoryEnabled: this.videosHistoryEnabled,
887 autoPlayVideo: this.autoPlayVideo,
888 autoPlayNextVideo: this.autoPlayNextVideo,
889 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
890 videoLanguages: this.videoLanguages,
893 roleLabel: USER_ROLE_LABELS[this.role],
895 videoQuota: this.videoQuota,
896 videoQuotaDaily: this.videoQuotaDaily,
898 videoQuotaUsed: videoQuotaUsed !== undefined
899 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
902 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
903 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
906 videosCount: videosCount !== undefined
907 ? parseInt(videosCount + '', 10)
909 abusesCount: abusesCount
910 ? parseInt(abusesCount, 10)
912 abusesAcceptedCount: abusesAcceptedCount
913 ? parseInt(abusesAcceptedCount, 10)
915 abusesCreatedCount: abusesCreatedCount !== undefined
916 ? parseInt(abusesCreatedCount + '', 10)
918 videoCommentsCount: videoCommentsCount !== undefined
919 ? parseInt(videoCommentsCount + '', 10)
922 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
923 noWelcomeModal: this.noWelcomeModal,
924 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
926 blocked: this.blocked,
927 blockedReason: this.blockedReason,
929 account: this.Account.toFormattedJSON(),
931 notificationSettings: this.NotificationSetting
932 ? this.NotificationSetting.toFormattedJSON()
937 createdAt: this.createdAt,
939 pluginAuth: this.pluginAuth,
941 lastLoginDate: this.lastLoginDate
944 if (parameters.withAdminFlags) {
945 Object.assign(json, { adminFlags: this.adminFlags })
948 if (Array.isArray(this.Account.VideoChannels) === true) {
949 json.videoChannels = this.Account.VideoChannels
950 .map(c => c.toFormattedJSON())
952 if (v1.createdAt < v2.createdAt) return -1
953 if (v1.createdAt === v2.createdAt) return 0
962 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
963 const formatted = this.toFormattedJSON({ withAdminFlags: true })
965 const specialPlaylists = this.Account.VideoPlaylists
966 .map(p => ({ id: p.id, name: p.name, type: p.type }))
968 return Object.assign(formatted, { specialPlaylists })