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,
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
270 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
276 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
278 videosHistoryEnabled: boolean
282 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
284 autoPlayVideo: boolean
288 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
290 autoPlayNextVideo: boolean
295 'UserAutoPlayNextVideoPlaylist',
296 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
299 autoPlayNextVideoPlaylist: boolean
303 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
304 @Column(DataType.ARRAY(DataType.STRING))
305 videoLanguages: string[]
308 @Default(UserAdminFlag.NONE)
309 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
311 adminFlags?: UserAdminFlag
315 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
321 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
323 blockedReason: string
326 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
331 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
332 @Column(DataType.BIGINT)
336 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
337 @Column(DataType.BIGINT)
338 videoQuotaDaily: number
341 @Default(DEFAULT_USER_THEME_NAME)
342 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
349 'UserNoInstanceConfigWarningModal',
350 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
353 noInstanceConfigWarningModal: boolean
358 'UserNoWelcomeModal',
359 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
362 noWelcomeModal: boolean
367 'UserNoAccountSetupWarningModal',
368 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
371 noAccountSetupWarningModal: boolean
379 @Default(DataType.UUIDV4)
381 @Column(DataType.UUID)
395 @HasOne(() => AccountModel, {
396 foreignKey: 'userId',
400 Account: AccountModel
402 @HasOne(() => UserNotificationSettingModel, {
403 foreignKey: 'userId',
407 NotificationSetting: UserNotificationSettingModel
409 @HasMany(() => VideoImportModel, {
410 foreignKey: 'userId',
413 VideoImports: VideoImportModel[]
415 @HasMany(() => OAuthTokenModel, {
416 foreignKey: 'userId',
419 OAuthTokens: OAuthTokenModel[]
423 static cryptPasswordIfNeeded (instance: UserModel) {
424 if (instance.changed('password') && instance.password) {
425 return cryptPassword(instance.password)
427 instance.password = hash
435 static removeTokenCache (instance: UserModel) {
436 return TokensCache.Instance.clearCacheByUserId(instance.id)
439 static countTotal () {
443 static listForApi (parameters: {
450 const { start, count, sort, search, blocked } = parameters
451 const where: WhereOptions = {}
454 Object.assign(where, {
458 [Op.iLike]: '%' + search + '%'
463 [Op.iLike]: '%' + search + '%'
470 if (blocked !== undefined) {
471 Object.assign(where, {
476 const query: FindOptions = {
482 UserModel.generateUserQuotaBaseSQL({
484 whereUserId: '"UserModel"."id"'
494 order: getSort(sort),
498 return UserModel.findAndCountAll(query)
499 .then(({ rows, count }) => {
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
585 if (withStats) scopes.push(ScopeNames.WITH_STATS)
587 return UserModel.scope(scopes).findByPk(id)
590 static loadByUsername (username: string): Promise<MUserDefault> {
597 return UserModel.findOne(query)
600 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
607 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
610 static loadByEmail (email: string): Promise<MUserDefault> {
617 return UserModel.findOne(query)
620 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
621 if (!email) email = username
626 where(fn('lower', col('username')), fn('lower', username)),
633 return UserModel.findOne(query)
636 static loadByVideoId (videoId: number): Promise<MUserDefault> {
641 attributes: [ 'id' ],
642 model: AccountModel.unscoped(),
646 attributes: [ 'id' ],
647 model: VideoChannelModel.unscoped(),
651 attributes: [ 'id' ],
652 model: VideoModel.unscoped(),
664 return UserModel.findOne(query)
667 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
672 attributes: [ 'id' ],
673 model: VideoImportModel.unscoped(),
681 return UserModel.findOne(query)
684 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
689 attributes: [ 'id' ],
690 model: AccountModel.unscoped(),
694 attributes: [ 'id' ],
695 model: VideoChannelModel.unscoped(),
697 actorId: videoChannelActorId
705 return UserModel.findOne(query)
708 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
713 attributes: [ 'id' ],
714 model: AccountModel.unscoped(),
716 actorId: accountActorId
722 return UserModel.findOne(query)
725 static loadByLiveId (liveId: number): Promise<MUser> {
729 attributes: [ 'id' ],
730 model: AccountModel.unscoped(),
734 attributes: [ 'id' ],
735 model: VideoChannelModel.unscoped(),
739 attributes: [ 'id' ],
740 model: VideoModel.unscoped(),
745 model: VideoLiveModel.unscoped(),
760 return UserModel.unscoped().findOne(query)
763 static generateUserQuotaBaseSQL (options: {
764 whereUserId: '$userId' | '"UserModel"."id"'
768 const andWhere = options.where
769 ? 'AND ' + options.where
772 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
773 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
774 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
776 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
777 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
780 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
781 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
782 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
785 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
787 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
788 'GROUP BY "t1"."videoId"' +
792 static getTotalRawQuery (query: string, userId: number) {
795 type: QueryTypes.SELECT as QueryTypes.SELECT
798 return UserModel.sequelize.query<{ total: string }>(query, options)
799 .then(([ { total } ]) => {
800 if (total === null) return 0
802 return parseInt(total, 10)
806 static async getStats () {
807 function getActiveUsers (days: number) {
811 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
816 return UserModel.count(query)
819 const totalUsers = await UserModel.count()
820 const totalDailyActiveUsers = await getActiveUsers(1)
821 const totalWeeklyActiveUsers = await getActiveUsers(7)
822 const totalMonthlyActiveUsers = await getActiveUsers(30)
823 const totalHalfYearActiveUsers = await getActiveUsers(180)
827 totalDailyActiveUsers,
828 totalWeeklyActiveUsers,
829 totalMonthlyActiveUsers,
830 totalHalfYearActiveUsers
834 static autoComplete (search: string) {
838 [Op.like]: `%${search}%`
844 return UserModel.findAll(query)
845 .then(u => u.map(u => u.username))
848 canGetVideo (video: MVideoWithRights) {
849 const videoUserId = video.VideoChannel.Account.userId
851 if (video.isBlacklisted()) {
852 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
855 if (video.privacy === VideoPrivacy.PRIVATE) {
856 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
859 if (video.privacy === VideoPrivacy.INTERNAL) return true
864 hasRight (right: UserRight) {
865 return hasUserRight(this.role, right)
868 hasAdminFlag (flag: UserAdminFlag) {
869 return this.adminFlags & flag
872 isPasswordMatch (password: string) {
873 return comparePassword(password, this.password)
876 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
877 const videoQuotaUsed = this.get('videoQuotaUsed')
878 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
879 const videosCount = this.get('videosCount')
880 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
881 const abusesCreatedCount = this.get('abusesCreatedCount')
882 const videoCommentsCount = this.get('videoCommentsCount')
886 username: this.username,
888 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
890 pendingEmail: this.pendingEmail,
891 emailVerified: this.emailVerified,
893 nsfwPolicy: this.nsfwPolicy,
895 // FIXME: deprecated in 4.1
896 webTorrentEnabled: this.p2pEnabled,
897 p2pEnabled: this.p2pEnabled,
899 videosHistoryEnabled: this.videosHistoryEnabled,
900 autoPlayVideo: this.autoPlayVideo,
901 autoPlayNextVideo: this.autoPlayNextVideo,
902 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
903 videoLanguages: this.videoLanguages,
906 roleLabel: USER_ROLE_LABELS[this.role],
908 videoQuota: this.videoQuota,
909 videoQuotaDaily: this.videoQuotaDaily,
910 videoQuotaUsed: videoQuotaUsed !== undefined
911 ? parseInt(videoQuotaUsed + '', 10)
913 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
914 ? parseInt(videoQuotaUsedDaily + '', 10)
916 videosCount: videosCount !== undefined
917 ? parseInt(videosCount + '', 10)
919 abusesCount: abusesCount
920 ? parseInt(abusesCount, 10)
922 abusesAcceptedCount: abusesAcceptedCount
923 ? parseInt(abusesAcceptedCount, 10)
925 abusesCreatedCount: abusesCreatedCount !== undefined
926 ? parseInt(abusesCreatedCount + '', 10)
928 videoCommentsCount: videoCommentsCount !== undefined
929 ? parseInt(videoCommentsCount + '', 10)
932 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
933 noWelcomeModal: this.noWelcomeModal,
934 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
936 blocked: this.blocked,
937 blockedReason: this.blockedReason,
939 account: this.Account.toFormattedJSON(),
941 notificationSettings: this.NotificationSetting
942 ? this.NotificationSetting.toFormattedJSON()
947 createdAt: this.createdAt,
949 pluginAuth: this.pluginAuth,
951 lastLoginDate: this.lastLoginDate
954 if (parameters.withAdminFlags) {
955 Object.assign(json, { adminFlags: this.adminFlags })
958 if (Array.isArray(this.Account.VideoChannels) === true) {
959 json.videoChannels = this.Account.VideoChannels
960 .map(c => c.toFormattedJSON())
962 if (v1.createdAt < v2.createdAt) return -1
963 if (v1.createdAt === v2.createdAt) return 0
972 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
973 const formatted = this.toFormattedJSON({ withAdminFlags: true })
975 const specialPlaylists = this.Account.VideoPlaylists
976 .map(p => ({ id: p.id, name: p.name, type: p.type }))
978 return Object.assign(formatted, { specialPlaylists })