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,
34 } from '@server/types/models'
35 import { AttributesOnly } from '@shared/typescript-utils'
36 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
37 import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared/models'
38 import { User, UserRole } from '../../../shared/models/users'
39 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
40 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
41 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
43 isUserAdminFlagsValid,
44 isUserAutoPlayNextVideoPlaylistValid,
45 isUserAutoPlayNextVideoValid,
46 isUserAutoPlayVideoValid,
47 isUserBlockedReasonValid,
49 isUserEmailVerifiedValid,
51 isUserNSFWPolicyValid,
52 isUserP2PEnabledValid,
57 isUserVideoQuotaDailyValid,
58 isUserVideoQuotaValid,
59 isUserVideosHistoryEnabledValid
60 } from '../../helpers/custom-validators/users'
61 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
62 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
63 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
64 import { AccountModel } from '../account/account'
65 import { ActorModel } from '../actor/actor'
66 import { ActorFollowModel } from '../actor/actor-follow'
67 import { ActorImageModel } from '../actor/actor-image'
68 import { OAuthTokenModel } from '../oauth/oauth-token'
69 import { getSort, throwIfNotValid } from '../utils'
70 import { VideoModel } from '../video/video'
71 import { VideoChannelModel } from '../video/video-channel'
72 import { VideoImportModel } from '../video/video-import'
73 import { VideoLiveModel } from '../video/video-live'
74 import { VideoPlaylistModel } from '../video/video-playlist'
75 import { UserNotificationSettingModel } from './user-notification-setting'
78 FOR_ME_API = 'FOR_ME_API',
79 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
80 WITH_QUOTA = 'WITH_QUOTA',
81 WITH_STATS = 'WITH_STATS'
84 @DefaultScope(() => ({
91 model: UserNotificationSettingModel,
97 [ScopeNames.FOR_ME_API]: {
103 model: VideoChannelModel.unscoped(),
110 model: ActorImageModel,
119 attributes: [ 'id', 'name', 'type' ],
120 model: VideoPlaylistModel.unscoped(),
124 [Op.ne]: VideoPlaylistType.REGULAR
131 model: UserNotificationSettingModel,
136 [ScopeNames.WITH_VIDEOCHANNELS]: {
142 model: VideoChannelModel
145 attributes: [ 'id', 'name', 'type' ],
146 model: VideoPlaylistModel.unscoped(),
150 [Op.ne]: VideoPlaylistType.REGULAR
158 [ScopeNames.WITH_QUOTA]: {
164 UserModel.generateUserQuotaBaseSQL({
166 whereUserId: '"UserModel"."id"',
176 UserModel.generateUserQuotaBaseSQL({
178 whereUserId: '"UserModel"."id"',
183 'videoQuotaUsedDaily'
188 [ScopeNames.WITH_STATS]: {
194 'SELECT COUNT("video"."id") ' +
196 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
197 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
198 'WHERE "account"."userId" = "UserModel"."id"' +
206 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
208 'SELECT COUNT("abuse"."id") AS "abuses", ' +
209 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
211 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
212 'WHERE "account"."userId" = "UserModel"."id"' +
221 'SELECT COUNT("abuse"."id") ' +
223 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
224 'WHERE "account"."userId" = "UserModel"."id"' +
232 'SELECT COUNT("videoComment"."id") ' +
233 'FROM "videoComment" ' +
234 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
235 'WHERE "account"."userId" = "UserModel"."id"' +
248 fields: [ 'username' ],
257 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
260 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
265 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
271 @Column(DataType.STRING(400))
276 @Column(DataType.STRING(400))
281 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
283 emailVerified: boolean
286 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
287 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
288 nsfwPolicy: NSFWPolicyType
291 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
297 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
299 videosHistoryEnabled: boolean
303 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
305 autoPlayVideo: boolean
309 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
311 autoPlayNextVideo: boolean
316 'UserAutoPlayNextVideoPlaylist',
317 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
320 autoPlayNextVideoPlaylist: boolean
324 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
325 @Column(DataType.ARRAY(DataType.STRING))
326 videoLanguages: string[]
329 @Default(UserAdminFlag.NONE)
330 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
332 adminFlags?: UserAdminFlag
336 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
342 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
344 blockedReason: string
347 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
352 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
353 @Column(DataType.BIGINT)
357 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
358 @Column(DataType.BIGINT)
359 videoQuotaDaily: number
362 @Default(DEFAULT_USER_THEME_NAME)
363 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
370 'UserNoInstanceConfigWarningModal',
371 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
374 noInstanceConfigWarningModal: boolean
379 'UserNoWelcomeModal',
380 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
383 noWelcomeModal: boolean
388 'UserNoAccountSetupWarningModal',
389 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
392 noAccountSetupWarningModal: boolean
400 @Default(DataType.UUIDV4)
402 @Column(DataType.UUID)
416 @HasOne(() => AccountModel, {
417 foreignKey: 'userId',
421 Account: AccountModel
423 @HasOne(() => UserNotificationSettingModel, {
424 foreignKey: 'userId',
428 NotificationSetting: UserNotificationSettingModel
430 @HasMany(() => VideoImportModel, {
431 foreignKey: 'userId',
434 VideoImports: VideoImportModel[]
436 @HasMany(() => OAuthTokenModel, {
437 foreignKey: 'userId',
440 OAuthTokens: OAuthTokenModel[]
444 static cryptPasswordIfNeeded (instance: UserModel) {
445 if (instance.changed('password') && instance.password) {
446 return cryptPassword(instance.password)
448 instance.password = hash
456 static removeTokenCache (instance: UserModel) {
457 return TokensCache.Instance.clearCacheByUserId(instance.id)
460 static countTotal () {
464 static listForApi (parameters: {
471 const { start, count, sort, search, blocked } = parameters
472 const where: WhereOptions = {}
475 Object.assign(where, {
479 [Op.iLike]: '%' + search + '%'
484 [Op.iLike]: '%' + search + '%'
491 if (blocked !== undefined) {
492 Object.assign(where, {
497 const query: FindOptions = {
500 order: getSort(sort),
505 UserModel.unscoped().count(query),
506 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
507 ]).then(([ total, data ]) => ({ total, data }))
510 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
511 const roles = Object.keys(USER_ROLE_LABELS)
512 .map(k => parseInt(k, 10) as UserRole)
513 .filter(role => hasUserRight(role, right))
523 return UserModel.findAll(query)
526 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
530 model: UserNotificationSettingModel.unscoped(),
534 attributes: [ 'userId' ],
535 model: AccountModel.unscoped(),
540 model: ActorModel.unscoped(),
548 as: 'ActorFollowings',
549 model: ActorFollowModel.unscoped(),
552 targetActorId: actorId
562 return UserModel.unscoped().findAll(query)
565 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
572 return UserModel.findAll(query)
575 static loadById (id: number): Promise<MUser> {
576 return UserModel.unscoped().findByPk(id)
579 static loadByIdFull (id: number): Promise<MUserDefault> {
580 return UserModel.findByPk(id)
583 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
585 ScopeNames.WITH_VIDEOCHANNELS
589 scopes.push(ScopeNames.WITH_QUOTA)
590 scopes.push(ScopeNames.WITH_STATS)
593 return UserModel.scope(scopes).findByPk(id)
596 static loadByUsername (username: string): Promise<MUserDefault> {
603 return UserModel.findOne(query)
606 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
613 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
616 static loadByEmail (email: string): Promise<MUserDefault> {
623 return UserModel.findOne(query)
626 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
627 if (!email) email = username
632 where(fn('lower', col('username')), fn('lower', username) as any),
639 return UserModel.findOne(query)
642 static loadByVideoId (videoId: number): Promise<MUserDefault> {
647 attributes: [ 'id' ],
648 model: AccountModel.unscoped(),
652 attributes: [ 'id' ],
653 model: VideoChannelModel.unscoped(),
657 attributes: [ 'id' ],
658 model: VideoModel.unscoped(),
670 return UserModel.findOne(query)
673 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
678 attributes: [ 'id' ],
679 model: VideoImportModel.unscoped(),
687 return UserModel.findOne(query)
690 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
695 attributes: [ 'id' ],
696 model: AccountModel.unscoped(),
700 attributes: [ 'id' ],
701 model: VideoChannelModel.unscoped(),
703 actorId: videoChannelActorId
711 return UserModel.findOne(query)
714 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
719 attributes: [ 'id' ],
720 model: AccountModel.unscoped(),
722 actorId: accountActorId
728 return UserModel.findOne(query)
731 static loadByLiveId (liveId: number): Promise<MUser> {
735 attributes: [ 'id' ],
736 model: AccountModel.unscoped(),
740 attributes: [ 'id' ],
741 model: VideoChannelModel.unscoped(),
745 attributes: [ 'id' ],
746 model: VideoModel.unscoped(),
751 model: VideoLiveModel.unscoped(),
766 return UserModel.unscoped().findOne(query)
769 static generateUserQuotaBaseSQL (options: {
770 whereUserId: '$userId' | '"UserModel"."id"'
774 const andWhere = options.daily === true
775 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
778 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
779 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
780 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
782 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
783 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
786 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
787 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
788 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
791 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
793 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
794 'GROUP BY "t1"."videoId"' +
798 static getTotalRawQuery (query: string, userId: number) {
801 type: QueryTypes.SELECT as QueryTypes.SELECT
804 return UserModel.sequelize.query<{ total: string }>(query, options)
805 .then(([ { total } ]) => {
806 if (total === null) return 0
808 return parseInt(total, 10)
812 static async getStats () {
813 function getActiveUsers (days: number) {
817 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
822 return UserModel.count(query)
825 const totalUsers = await UserModel.count()
826 const totalDailyActiveUsers = await getActiveUsers(1)
827 const totalWeeklyActiveUsers = await getActiveUsers(7)
828 const totalMonthlyActiveUsers = await getActiveUsers(30)
829 const totalHalfYearActiveUsers = await getActiveUsers(180)
833 totalDailyActiveUsers,
834 totalWeeklyActiveUsers,
835 totalMonthlyActiveUsers,
836 totalHalfYearActiveUsers
840 static autoComplete (search: string) {
844 [Op.like]: `%${search}%`
850 return UserModel.findAll(query)
851 .then(u => u.map(u => u.username))
854 canGetVideo (video: MVideoWithRights) {
855 const videoUserId = video.VideoChannel.Account.userId
857 if (video.isBlacklisted()) {
858 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
861 if (video.privacy === VideoPrivacy.PRIVATE) {
862 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
865 if (video.privacy === VideoPrivacy.INTERNAL) return true
870 hasRight (right: UserRight) {
871 return hasUserRight(this.role, right)
874 hasAdminFlag (flag: UserAdminFlag) {
875 return this.adminFlags & flag
878 isPasswordMatch (password: string) {
879 return comparePassword(password, this.password)
882 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
883 const videoQuotaUsed = this.get('videoQuotaUsed')
884 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
885 const videosCount = this.get('videosCount')
886 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
887 const abusesCreatedCount = this.get('abusesCreatedCount')
888 const videoCommentsCount = this.get('videoCommentsCount')
892 username: this.username,
894 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
896 pendingEmail: this.pendingEmail,
897 emailVerified: this.emailVerified,
899 nsfwPolicy: this.nsfwPolicy,
901 // FIXME: deprecated in 4.1
902 webTorrentEnabled: this.p2pEnabled,
903 p2pEnabled: this.p2pEnabled,
905 videosHistoryEnabled: this.videosHistoryEnabled,
906 autoPlayVideo: this.autoPlayVideo,
907 autoPlayNextVideo: this.autoPlayNextVideo,
908 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
909 videoLanguages: this.videoLanguages,
912 roleLabel: USER_ROLE_LABELS[this.role],
914 videoQuota: this.videoQuota,
915 videoQuotaDaily: this.videoQuotaDaily,
917 videoQuotaUsed: videoQuotaUsed !== undefined
918 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
921 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
922 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
925 videosCount: videosCount !== undefined
926 ? parseInt(videosCount + '', 10)
928 abusesCount: abusesCount
929 ? parseInt(abusesCount, 10)
931 abusesAcceptedCount: abusesAcceptedCount
932 ? parseInt(abusesAcceptedCount, 10)
934 abusesCreatedCount: abusesCreatedCount !== undefined
935 ? parseInt(abusesCreatedCount + '', 10)
937 videoCommentsCount: videoCommentsCount !== undefined
938 ? parseInt(videoCommentsCount + '', 10)
941 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
942 noWelcomeModal: this.noWelcomeModal,
943 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
945 blocked: this.blocked,
946 blockedReason: this.blockedReason,
948 account: this.Account.toFormattedJSON(),
950 notificationSettings: this.NotificationSetting
951 ? this.NotificationSetting.toFormattedJSON()
956 createdAt: this.createdAt,
958 pluginAuth: this.pluginAuth,
960 lastLoginDate: this.lastLoginDate
963 if (parameters.withAdminFlags) {
964 Object.assign(json, { adminFlags: this.adminFlags })
967 if (Array.isArray(this.Account.VideoChannels) === true) {
968 json.videoChannels = this.Account.VideoChannels
969 .map(c => c.toFormattedJSON())
971 if (v1.createdAt < v2.createdAt) return -1
972 if (v1.createdAt === v2.createdAt) return 0
981 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
982 const formatted = this.toFormattedJSON({ withAdminFlags: true })
984 const specialPlaylists = this.Account.VideoPlaylists
985 .map(p => ({ id: p.id, name: p.name, type: p.type }))
987 return Object.assign(formatted, { specialPlaylists })