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 isNoInstanceConfigWarningModal,
44 isUserAdminFlagsValid,
45 isUserAutoPlayNextVideoPlaylistValid,
46 isUserAutoPlayNextVideoValid,
47 isUserAutoPlayVideoValid,
48 isUserBlockedReasonValid,
50 isUserEmailVerifiedValid,
51 isUserNSFWPolicyValid,
56 isUserVideoQuotaDailyValid,
57 isUserVideoQuotaValid,
58 isUserVideosHistoryEnabledValid,
59 isUserWebTorrentEnabledValid
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_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_STATS]: {
163 UserModel.generateUserQuotaBaseSQL({
165 whereUserId: '"UserModel"."id"'
174 'SELECT COUNT("video"."id") ' +
176 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
177 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
178 'WHERE "account"."userId" = "UserModel"."id"' +
186 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
188 'SELECT COUNT("abuse"."id") AS "abuses", ' +
189 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
191 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
192 'WHERE "account"."userId" = "UserModel"."id"' +
201 'SELECT COUNT("abuse"."id") ' +
203 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
204 'WHERE "account"."userId" = "UserModel"."id"' +
212 'SELECT COUNT("videoComment"."id") ' +
213 'FROM "videoComment" ' +
214 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
215 'WHERE "account"."userId" = "UserModel"."id"' +
228 fields: [ 'username' ],
237 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
240 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
245 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
251 @Column(DataType.STRING(400))
256 @Column(DataType.STRING(400))
261 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
263 emailVerified: boolean
266 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
267 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
268 nsfwPolicy: NSFWPolicyType
272 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
274 webTorrentEnabled: boolean
278 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
280 videosHistoryEnabled: boolean
284 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
286 autoPlayVideo: boolean
290 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
292 autoPlayNextVideo: boolean
297 'UserAutoPlayNextVideoPlaylist',
298 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
301 autoPlayNextVideoPlaylist: boolean
305 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
306 @Column(DataType.ARRAY(DataType.STRING))
307 videoLanguages: string[]
310 @Default(UserAdminFlag.NONE)
311 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
313 adminFlags?: UserAdminFlag
317 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
323 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
325 blockedReason: string
328 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
333 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
334 @Column(DataType.BIGINT)
338 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
339 @Column(DataType.BIGINT)
340 videoQuotaDaily: number
343 @Default(DEFAULT_USER_THEME_NAME)
344 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
351 'UserNoInstanceConfigWarningModal',
352 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
355 noInstanceConfigWarningModal: boolean
360 'UserNoInstanceConfigWarningModal',
361 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
364 noWelcomeModal: boolean
372 @Default(DataType.UUIDV4)
374 @Column(DataType.UUID)
388 @HasOne(() => AccountModel, {
389 foreignKey: 'userId',
393 Account: AccountModel
395 @HasOne(() => UserNotificationSettingModel, {
396 foreignKey: 'userId',
400 NotificationSetting: UserNotificationSettingModel
402 @HasMany(() => VideoImportModel, {
403 foreignKey: 'userId',
406 VideoImports: VideoImportModel[]
408 @HasMany(() => OAuthTokenModel, {
409 foreignKey: 'userId',
412 OAuthTokens: OAuthTokenModel[]
416 static cryptPasswordIfNeeded (instance: UserModel) {
417 if (instance.changed('password') && instance.password) {
418 return cryptPassword(instance.password)
420 instance.password = hash
428 static removeTokenCache (instance: UserModel) {
429 return TokensCache.Instance.clearCacheByUserId(instance.id)
432 static countTotal () {
436 static listForApi (parameters: {
443 const { start, count, sort, search, blocked } = parameters
444 const where: WhereOptions = {}
447 Object.assign(where, {
451 [Op.iLike]: '%' + search + '%'
456 [Op.iLike]: '%' + search + '%'
463 if (blocked !== undefined) {
464 Object.assign(where, {
469 const query: FindOptions = {
475 UserModel.generateUserQuotaBaseSQL({
477 whereUserId: '"UserModel"."id"'
482 ] as any // FIXME: typings
487 order: getSort(sort),
491 return UserModel.findAndCountAll(query)
492 .then(({ rows, count }) => {
500 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
501 const roles = Object.keys(USER_ROLE_LABELS)
502 .map(k => parseInt(k, 10) as UserRole)
503 .filter(role => hasUserRight(role, right))
513 return UserModel.findAll(query)
516 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
520 model: UserNotificationSettingModel.unscoped(),
524 attributes: [ 'userId' ],
525 model: AccountModel.unscoped(),
530 model: ActorModel.unscoped(),
538 as: 'ActorFollowings',
539 model: ActorFollowModel.unscoped(),
542 targetActorId: actorId
552 return UserModel.unscoped().findAll(query)
555 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
562 return UserModel.findAll(query)
565 static loadById (id: number): Promise<MUser> {
566 return UserModel.unscoped().findByPk(id)
569 static loadByIdFull (id: number): Promise<MUserDefault> {
570 return UserModel.findByPk(id)
573 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
575 ScopeNames.WITH_VIDEOCHANNELS
578 if (withStats) scopes.push(ScopeNames.WITH_STATS)
580 return UserModel.scope(scopes).findByPk(id)
583 static loadByUsername (username: string): Promise<MUserDefault> {
590 return UserModel.findOne(query)
593 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
600 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
603 static loadByEmail (email: string): Promise<MUserDefault> {
610 return UserModel.findOne(query)
613 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
614 if (!email) email = username
619 where(fn('lower', col('username')), fn('lower', username)),
626 return UserModel.findOne(query)
629 static loadByVideoId (videoId: number): Promise<MUserDefault> {
634 attributes: [ 'id' ],
635 model: AccountModel.unscoped(),
639 attributes: [ 'id' ],
640 model: VideoChannelModel.unscoped(),
644 attributes: [ 'id' ],
645 model: VideoModel.unscoped(),
657 return UserModel.findOne(query)
660 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
665 attributes: [ 'id' ],
666 model: VideoImportModel.unscoped(),
674 return UserModel.findOne(query)
677 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
682 attributes: [ 'id' ],
683 model: AccountModel.unscoped(),
687 attributes: [ 'id' ],
688 model: VideoChannelModel.unscoped(),
690 actorId: videoChannelActorId
698 return UserModel.findOne(query)
701 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
706 attributes: [ 'id' ],
707 model: AccountModel.unscoped(),
709 actorId: accountActorId
715 return UserModel.findOne(query)
718 static loadByLiveId (liveId: number): Promise<MUser> {
722 attributes: [ 'id' ],
723 model: AccountModel.unscoped(),
727 attributes: [ 'id' ],
728 model: VideoChannelModel.unscoped(),
732 attributes: [ 'id' ],
733 model: VideoModel.unscoped(),
738 model: VideoLiveModel.unscoped(),
753 return UserModel.unscoped().findOne(query)
756 static generateUserQuotaBaseSQL (options: {
757 whereUserId: '$userId' | '"UserModel"."id"'
761 const andWhere = options.where
762 ? 'AND ' + options.where
765 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
766 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
767 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
769 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
770 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
773 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
774 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
775 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
778 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
780 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
781 'GROUP BY "t1"."videoId"' +
785 static getTotalRawQuery (query: string, userId: number) {
788 type: QueryTypes.SELECT as QueryTypes.SELECT
791 return UserModel.sequelize.query<{ total: string }>(query, options)
792 .then(([ { total } ]) => {
793 if (total === null) return 0
795 return parseInt(total, 10)
799 static async getStats () {
800 function getActiveUsers (days: number) {
804 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
809 return UserModel.count(query)
812 const totalUsers = await UserModel.count()
813 const totalDailyActiveUsers = await getActiveUsers(1)
814 const totalWeeklyActiveUsers = await getActiveUsers(7)
815 const totalMonthlyActiveUsers = await getActiveUsers(30)
816 const totalHalfYearActiveUsers = await getActiveUsers(180)
820 totalDailyActiveUsers,
821 totalWeeklyActiveUsers,
822 totalMonthlyActiveUsers,
823 totalHalfYearActiveUsers
827 static autoComplete (search: string) {
831 [Op.like]: `%${search}%`
837 return UserModel.findAll(query)
838 .then(u => u.map(u => u.username))
841 canGetVideo (video: MVideoWithRights) {
842 const videoUserId = video.VideoChannel.Account.userId
844 if (video.isBlacklisted()) {
845 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
848 if (video.privacy === VideoPrivacy.PRIVATE) {
849 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
852 if (video.privacy === VideoPrivacy.INTERNAL) return true
857 hasRight (right: UserRight) {
858 return hasUserRight(this.role, right)
861 hasAdminFlag (flag: UserAdminFlag) {
862 return this.adminFlags & flag
865 isPasswordMatch (password: string) {
866 return comparePassword(password, this.password)
869 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
870 const videoQuotaUsed = this.get('videoQuotaUsed')
871 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
872 const videosCount = this.get('videosCount')
873 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
874 const abusesCreatedCount = this.get('abusesCreatedCount')
875 const videoCommentsCount = this.get('videoCommentsCount')
879 username: this.username,
881 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
883 pendingEmail: this.pendingEmail,
884 emailVerified: this.emailVerified,
886 nsfwPolicy: this.nsfwPolicy,
887 webTorrentEnabled: this.webTorrentEnabled,
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,
899 videoQuotaUsed: videoQuotaUsed !== undefined
900 ? parseInt(videoQuotaUsed + '', 10)
902 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
903 ? parseInt(videoQuotaUsedDaily + '', 10)
905 videosCount: videosCount !== undefined
906 ? parseInt(videosCount + '', 10)
908 abusesCount: abusesCount
909 ? parseInt(abusesCount, 10)
911 abusesAcceptedCount: abusesAcceptedCount
912 ? parseInt(abusesAcceptedCount, 10)
914 abusesCreatedCount: abusesCreatedCount !== undefined
915 ? parseInt(abusesCreatedCount + '', 10)
917 videoCommentsCount: videoCommentsCount !== undefined
918 ? parseInt(videoCommentsCount + '', 10)
921 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
922 noWelcomeModal: this.noWelcomeModal,
924 blocked: this.blocked,
925 blockedReason: this.blockedReason,
927 account: this.Account.toFormattedJSON(),
929 notificationSettings: this.NotificationSetting
930 ? this.NotificationSetting.toFormattedJSON()
935 createdAt: this.createdAt,
937 pluginAuth: this.pluginAuth,
939 lastLoginDate: this.lastLoginDate
942 if (parameters.withAdminFlags) {
943 Object.assign(json, { adminFlags: this.adminFlags })
946 if (Array.isArray(this.Account.VideoChannels) === true) {
947 json.videoChannels = this.Account.VideoChannels
948 .map(c => c.toFormattedJSON())
950 if (v1.createdAt < v2.createdAt) return -1
951 if (v1.createdAt === v2.createdAt) return 0
960 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
961 const formatted = this.toFormattedJSON()
963 const specialPlaylists = this.Account.VideoPlaylists
964 .map(p => ({ id: p.id, name: p.name, type: p.type }))
966 return Object.assign(formatted, { specialPlaylists })