1 import { values } from 'lodash'
2 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
23 } from 'sequelize-typescript'
29 MUserNotifSettingChannelDefault,
30 MUserWithNotificationSetting,
32 } from '@server/types/models'
33 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
34 import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared/models'
35 import { User, UserRole } from '../../../shared/models/users'
36 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
37 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
38 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
40 isNoInstanceConfigWarningModal,
42 isUserAdminFlagsValid,
43 isUserAutoPlayNextVideoPlaylistValid,
44 isUserAutoPlayNextVideoValid,
45 isUserAutoPlayVideoValid,
46 isUserBlockedReasonValid,
48 isUserEmailVerifiedValid,
49 isUserNSFWPolicyValid,
54 isUserVideoQuotaDailyValid,
55 isUserVideoQuotaValid,
56 isUserVideosHistoryEnabledValid,
57 isUserWebTorrentEnabledValid
58 } from '../../helpers/custom-validators/users'
59 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
60 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
61 import { clearCacheByUserId } from '../../lib/oauth-model'
62 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
63 import { ActorModel } from '../activitypub/actor'
64 import { ActorFollowModel } from '../activitypub/actor-follow'
65 import { OAuthTokenModel } from '../oauth/oauth-token'
66 import { getSort, throwIfNotValid } from '../utils'
67 import { VideoModel } from '../video/video'
68 import { VideoChannelModel } from '../video/video-channel'
69 import { VideoImportModel } from '../video/video-import'
70 import { VideoLiveModel } from '../video/video-live'
71 import { VideoPlaylistModel } from '../video/video-playlist'
72 import { AccountModel } from './account'
73 import { UserNotificationSettingModel } from './user-notification-setting'
76 FOR_ME_API = 'FOR_ME_API',
77 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
78 WITH_STATS = 'WITH_STATS'
81 @DefaultScope(() => ({
88 model: UserNotificationSettingModel,
94 [ScopeNames.FOR_ME_API]: {
100 model: VideoChannelModel
103 attributes: [ 'id', 'name', 'type' ],
104 model: VideoPlaylistModel.unscoped(),
108 [Op.ne]: VideoPlaylistType.REGULAR
115 model: UserNotificationSettingModel,
120 [ScopeNames.WITH_VIDEOCHANNELS]: {
126 model: VideoChannelModel
129 attributes: [ 'id', 'name', 'type' ],
130 model: VideoPlaylistModel.unscoped(),
134 [Op.ne]: VideoPlaylistType.REGULAR
142 [ScopeNames.WITH_STATS]: {
148 UserModel.generateUserQuotaBaseSQL({
150 whereUserId: '"UserModel"."id"'
159 'SELECT COUNT("video"."id") ' +
161 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
162 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
163 'WHERE "account"."userId" = "UserModel"."id"' +
171 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
173 'SELECT COUNT("abuse"."id") AS "abuses", ' +
174 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
176 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
177 'WHERE "account"."userId" = "UserModel"."id"' +
186 'SELECT COUNT("abuse"."id") ' +
188 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
189 'WHERE "account"."userId" = "UserModel"."id"' +
197 'SELECT COUNT("videoComment"."id") ' +
198 'FROM "videoComment" ' +
199 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
200 'WHERE "account"."userId" = "UserModel"."id"' +
213 fields: [ 'username' ],
222 export class UserModel extends Model {
225 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
230 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
236 @Column(DataType.STRING(400))
241 @Column(DataType.STRING(400))
246 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
248 emailVerified: boolean
251 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
252 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
253 nsfwPolicy: NSFWPolicyType
257 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
259 webTorrentEnabled: boolean
263 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
265 videosHistoryEnabled: boolean
269 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
271 autoPlayVideo: boolean
275 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
277 autoPlayNextVideo: boolean
282 'UserAutoPlayNextVideoPlaylist',
283 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
286 autoPlayNextVideoPlaylist: boolean
290 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
291 @Column(DataType.ARRAY(DataType.STRING))
292 videoLanguages: string[]
295 @Default(UserAdminFlag.NONE)
296 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
298 adminFlags?: UserAdminFlag
302 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
308 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
310 blockedReason: string
313 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
318 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
319 @Column(DataType.BIGINT)
323 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
324 @Column(DataType.BIGINT)
325 videoQuotaDaily: number
328 @Default(DEFAULT_USER_THEME_NAME)
329 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
336 'UserNoInstanceConfigWarningModal',
337 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
340 noInstanceConfigWarningModal: boolean
345 'UserNoInstanceConfigWarningModal',
346 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
349 noWelcomeModal: boolean
357 @Default(DataType.UUIDV4)
359 @Column(DataType.UUID)
373 @HasOne(() => AccountModel, {
374 foreignKey: 'userId',
378 Account: AccountModel
380 @HasOne(() => UserNotificationSettingModel, {
381 foreignKey: 'userId',
385 NotificationSetting: UserNotificationSettingModel
387 @HasMany(() => VideoImportModel, {
388 foreignKey: 'userId',
391 VideoImports: VideoImportModel[]
393 @HasMany(() => OAuthTokenModel, {
394 foreignKey: 'userId',
397 OAuthTokens: OAuthTokenModel[]
401 static cryptPasswordIfNeeded (instance: UserModel) {
402 if (instance.changed('password') && instance.password) {
403 return cryptPassword(instance.password)
405 instance.password = hash
413 static removeTokenCache (instance: UserModel) {
414 return clearCacheByUserId(instance.id)
417 static countTotal () {
421 static listForApi (parameters: {
428 const { start, count, sort, search, blocked } = parameters
429 const where: WhereOptions = {}
432 Object.assign(where, {
436 [Op.iLike]: '%' + search + '%'
441 [Op.iLike]: '%' + search + '%'
448 if (blocked !== undefined) {
449 Object.assign(where, {
454 const query: FindOptions = {
460 UserModel.generateUserQuotaBaseSQL({
462 whereUserId: '"UserModel"."id"'
467 ] as any // FIXME: typings
472 order: getSort(sort),
476 return UserModel.findAndCountAll(query)
477 .then(({ rows, count }) => {
485 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
486 const roles = Object.keys(USER_ROLE_LABELS)
487 .map(k => parseInt(k, 10) as UserRole)
488 .filter(role => hasUserRight(role, right))
498 return UserModel.findAll(query)
501 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
505 model: UserNotificationSettingModel.unscoped(),
509 attributes: [ 'userId' ],
510 model: AccountModel.unscoped(),
515 model: ActorModel.unscoped(),
523 as: 'ActorFollowings',
524 model: ActorFollowModel.unscoped(),
527 targetActorId: actorId
537 return UserModel.unscoped().findAll(query)
540 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
547 return UserModel.findAll(query)
550 static loadById (id: number): Promise<MUser> {
551 return UserModel.unscoped().findByPk(id)
554 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
556 ScopeNames.WITH_VIDEOCHANNELS
559 if (withStats) scopes.push(ScopeNames.WITH_STATS)
561 return UserModel.scope(scopes).findByPk(id)
564 static loadByUsername (username: string): Promise<MUserDefault> {
571 return UserModel.findOne(query)
574 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
581 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
584 static loadByEmail (email: string): Promise<MUserDefault> {
591 return UserModel.findOne(query)
594 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
595 if (!email) email = username
600 where(fn('lower', col('username')), fn('lower', username)),
607 return UserModel.findOne(query)
610 static loadByVideoId (videoId: number): Promise<MUserDefault> {
615 attributes: [ 'id' ],
616 model: AccountModel.unscoped(),
620 attributes: [ 'id' ],
621 model: VideoChannelModel.unscoped(),
625 attributes: [ 'id' ],
626 model: VideoModel.unscoped(),
638 return UserModel.findOne(query)
641 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
646 attributes: [ 'id' ],
647 model: VideoImportModel.unscoped(),
655 return UserModel.findOne(query)
658 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
663 attributes: [ 'id' ],
664 model: AccountModel.unscoped(),
668 attributes: [ 'id' ],
669 model: VideoChannelModel.unscoped(),
671 actorId: videoChannelActorId
679 return UserModel.findOne(query)
682 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
687 attributes: [ 'id' ],
688 model: AccountModel.unscoped(),
690 actorId: accountActorId
696 return UserModel.findOne(query)
699 static loadByLiveId (liveId: number): Promise<MUser> {
703 attributes: [ 'id' ],
704 model: AccountModel.unscoped(),
708 attributes: [ 'id' ],
709 model: VideoChannelModel.unscoped(),
713 attributes: [ 'id' ],
714 model: VideoModel.unscoped(),
719 model: VideoLiveModel.unscoped(),
734 return UserModel.unscoped().findOne(query)
737 static generateUserQuotaBaseSQL (options: {
738 whereUserId: '$userId' | '"UserModel"."id"'
742 const andWhere = options.where
743 ? 'AND ' + options.where
746 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
747 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
748 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
750 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
751 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
754 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
755 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
756 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
759 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
761 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
762 'GROUP BY "t1"."videoId"' +
766 static getTotalRawQuery (query: string, userId: number) {
769 type: QueryTypes.SELECT as QueryTypes.SELECT
772 return UserModel.sequelize.query<{ total: string }>(query, options)
773 .then(([ { total } ]) => {
774 if (total === null) return 0
776 return parseInt(total, 10)
780 static async getStats () {
781 function getActiveUsers (days: number) {
785 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
790 return UserModel.count(query)
793 const totalUsers = await UserModel.count()
794 const totalDailyActiveUsers = await getActiveUsers(1)
795 const totalWeeklyActiveUsers = await getActiveUsers(7)
796 const totalMonthlyActiveUsers = await getActiveUsers(30)
797 const totalHalfYearActiveUsers = await getActiveUsers(180)
801 totalDailyActiveUsers,
802 totalWeeklyActiveUsers,
803 totalMonthlyActiveUsers,
804 totalHalfYearActiveUsers
808 static autoComplete (search: string) {
812 [Op.like]: `%${search}%`
818 return UserModel.findAll(query)
819 .then(u => u.map(u => u.username))
822 canGetVideo (video: MVideoWithRights) {
823 const videoUserId = video.VideoChannel.Account.userId
825 if (video.isBlacklisted()) {
826 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
829 if (video.privacy === VideoPrivacy.PRIVATE) {
830 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
833 if (video.privacy === VideoPrivacy.INTERNAL) return true
838 hasRight (right: UserRight) {
839 return hasUserRight(this.role, right)
842 hasAdminFlag (flag: UserAdminFlag) {
843 return this.adminFlags & flag
846 isPasswordMatch (password: string) {
847 return comparePassword(password, this.password)
850 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
851 const videoQuotaUsed = this.get('videoQuotaUsed')
852 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
853 const videosCount = this.get('videosCount')
854 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
855 const abusesCreatedCount = this.get('abusesCreatedCount')
856 const videoCommentsCount = this.get('videoCommentsCount')
860 username: this.username,
862 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
864 pendingEmail: this.pendingEmail,
865 emailVerified: this.emailVerified,
867 nsfwPolicy: this.nsfwPolicy,
868 webTorrentEnabled: this.webTorrentEnabled,
869 videosHistoryEnabled: this.videosHistoryEnabled,
870 autoPlayVideo: this.autoPlayVideo,
871 autoPlayNextVideo: this.autoPlayNextVideo,
872 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
873 videoLanguages: this.videoLanguages,
876 roleLabel: USER_ROLE_LABELS[this.role],
878 videoQuota: this.videoQuota,
879 videoQuotaDaily: this.videoQuotaDaily,
880 videoQuotaUsed: videoQuotaUsed !== undefined
881 ? parseInt(videoQuotaUsed + '', 10)
883 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
884 ? parseInt(videoQuotaUsedDaily + '', 10)
886 videosCount: videosCount !== undefined
887 ? parseInt(videosCount + '', 10)
889 abusesCount: abusesCount
890 ? parseInt(abusesCount, 10)
892 abusesAcceptedCount: abusesAcceptedCount
893 ? parseInt(abusesAcceptedCount, 10)
895 abusesCreatedCount: abusesCreatedCount !== undefined
896 ? parseInt(abusesCreatedCount + '', 10)
898 videoCommentsCount: videoCommentsCount !== undefined
899 ? parseInt(videoCommentsCount + '', 10)
902 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
903 noWelcomeModal: this.noWelcomeModal,
905 blocked: this.blocked,
906 blockedReason: this.blockedReason,
908 account: this.Account.toFormattedJSON(),
910 notificationSettings: this.NotificationSetting
911 ? this.NotificationSetting.toFormattedJSON()
916 createdAt: this.createdAt,
918 pluginAuth: this.pluginAuth,
920 lastLoginDate: this.lastLoginDate
923 if (parameters.withAdminFlags) {
924 Object.assign(json, { adminFlags: this.adminFlags })
927 if (Array.isArray(this.Account.VideoChannels) === true) {
928 json.videoChannels = this.Account.VideoChannels
929 .map(c => c.toFormattedJSON())
931 if (v1.createdAt < v2.createdAt) return -1
932 if (v1.createdAt === v2.createdAt) return 0
941 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
942 const formatted = this.toFormattedJSON()
944 const specialPlaylists = this.Account.VideoPlaylists
945 .map(p => ({ id: p.id, name: p.name, type: p.type }))
947 return Object.assign(formatted, { specialPlaylists })