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 { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
35 import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared/models'
36 import { User, UserRole } from '../../../shared/models/users'
37 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
38 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
41 isNoInstanceConfigWarningModal,
43 isUserAdminFlagsValid,
44 isUserAutoPlayNextVideoPlaylistValid,
45 isUserAutoPlayNextVideoValid,
46 isUserAutoPlayVideoValid,
47 isUserBlockedReasonValid,
49 isUserEmailVerifiedValid,
50 isUserNSFWPolicyValid,
55 isUserVideoQuotaDailyValid,
56 isUserVideoQuotaValid,
57 isUserVideosHistoryEnabledValid,
58 isUserWebTorrentEnabledValid
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 { 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'
74 import { ActorImageModel } from './actor-image'
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 {
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
271 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
273 webTorrentEnabled: boolean
277 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
279 videosHistoryEnabled: boolean
283 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
285 autoPlayVideo: boolean
289 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
291 autoPlayNextVideo: boolean
296 'UserAutoPlayNextVideoPlaylist',
297 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
300 autoPlayNextVideoPlaylist: boolean
304 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
305 @Column(DataType.ARRAY(DataType.STRING))
306 videoLanguages: string[]
309 @Default(UserAdminFlag.NONE)
310 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
312 adminFlags?: UserAdminFlag
316 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
322 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
324 blockedReason: string
327 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
332 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
333 @Column(DataType.BIGINT)
337 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
338 @Column(DataType.BIGINT)
339 videoQuotaDaily: number
342 @Default(DEFAULT_USER_THEME_NAME)
343 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
350 'UserNoInstanceConfigWarningModal',
351 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
354 noInstanceConfigWarningModal: boolean
359 'UserNoInstanceConfigWarningModal',
360 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
363 noWelcomeModal: boolean
371 @Default(DataType.UUIDV4)
373 @Column(DataType.UUID)
387 @HasOne(() => AccountModel, {
388 foreignKey: 'userId',
392 Account: AccountModel
394 @HasOne(() => UserNotificationSettingModel, {
395 foreignKey: 'userId',
399 NotificationSetting: UserNotificationSettingModel
401 @HasMany(() => VideoImportModel, {
402 foreignKey: 'userId',
405 VideoImports: VideoImportModel[]
407 @HasMany(() => OAuthTokenModel, {
408 foreignKey: 'userId',
411 OAuthTokens: OAuthTokenModel[]
415 static cryptPasswordIfNeeded (instance: UserModel) {
416 if (instance.changed('password') && instance.password) {
417 return cryptPassword(instance.password)
419 instance.password = hash
427 static removeTokenCache (instance: UserModel) {
428 return TokensCache.Instance.clearCacheByUserId(instance.id)
431 static countTotal () {
435 static listForApi (parameters: {
442 const { start, count, sort, search, blocked } = parameters
443 const where: WhereOptions = {}
446 Object.assign(where, {
450 [Op.iLike]: '%' + search + '%'
455 [Op.iLike]: '%' + search + '%'
462 if (blocked !== undefined) {
463 Object.assign(where, {
468 const query: FindOptions = {
474 UserModel.generateUserQuotaBaseSQL({
476 whereUserId: '"UserModel"."id"'
481 ] as any // FIXME: typings
486 order: getSort(sort),
490 return UserModel.findAndCountAll(query)
491 .then(({ rows, count }) => {
499 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
500 const roles = Object.keys(USER_ROLE_LABELS)
501 .map(k => parseInt(k, 10) as UserRole)
502 .filter(role => hasUserRight(role, right))
512 return UserModel.findAll(query)
515 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
519 model: UserNotificationSettingModel.unscoped(),
523 attributes: [ 'userId' ],
524 model: AccountModel.unscoped(),
529 model: ActorModel.unscoped(),
537 as: 'ActorFollowings',
538 model: ActorFollowModel.unscoped(),
541 targetActorId: actorId
551 return UserModel.unscoped().findAll(query)
554 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
561 return UserModel.findAll(query)
564 static loadById (id: number): Promise<MUser> {
565 return UserModel.unscoped().findByPk(id)
568 static loadByIdFull (id: number): Promise<MUserDefault> {
569 return UserModel.findByPk(id)
572 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
574 ScopeNames.WITH_VIDEOCHANNELS
577 if (withStats) scopes.push(ScopeNames.WITH_STATS)
579 return UserModel.scope(scopes).findByPk(id)
582 static loadByUsername (username: string): Promise<MUserDefault> {
589 return UserModel.findOne(query)
592 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
599 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
602 static loadByEmail (email: string): Promise<MUserDefault> {
609 return UserModel.findOne(query)
612 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
613 if (!email) email = username
618 where(fn('lower', col('username')), fn('lower', username)),
625 return UserModel.findOne(query)
628 static loadByVideoId (videoId: number): Promise<MUserDefault> {
633 attributes: [ 'id' ],
634 model: AccountModel.unscoped(),
638 attributes: [ 'id' ],
639 model: VideoChannelModel.unscoped(),
643 attributes: [ 'id' ],
644 model: VideoModel.unscoped(),
656 return UserModel.findOne(query)
659 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
664 attributes: [ 'id' ],
665 model: VideoImportModel.unscoped(),
673 return UserModel.findOne(query)
676 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
681 attributes: [ 'id' ],
682 model: AccountModel.unscoped(),
686 attributes: [ 'id' ],
687 model: VideoChannelModel.unscoped(),
689 actorId: videoChannelActorId
697 return UserModel.findOne(query)
700 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
705 attributes: [ 'id' ],
706 model: AccountModel.unscoped(),
708 actorId: accountActorId
714 return UserModel.findOne(query)
717 static loadByLiveId (liveId: number): Promise<MUser> {
721 attributes: [ 'id' ],
722 model: AccountModel.unscoped(),
726 attributes: [ 'id' ],
727 model: VideoChannelModel.unscoped(),
731 attributes: [ 'id' ],
732 model: VideoModel.unscoped(),
737 model: VideoLiveModel.unscoped(),
752 return UserModel.unscoped().findOne(query)
755 static generateUserQuotaBaseSQL (options: {
756 whereUserId: '$userId' | '"UserModel"."id"'
760 const andWhere = options.where
761 ? 'AND ' + options.where
764 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
765 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
766 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
768 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
769 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
772 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
773 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
774 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
777 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
779 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
780 'GROUP BY "t1"."videoId"' +
784 static getTotalRawQuery (query: string, userId: number) {
787 type: QueryTypes.SELECT as QueryTypes.SELECT
790 return UserModel.sequelize.query<{ total: string }>(query, options)
791 .then(([ { total } ]) => {
792 if (total === null) return 0
794 return parseInt(total, 10)
798 static async getStats () {
799 function getActiveUsers (days: number) {
803 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
808 return UserModel.count(query)
811 const totalUsers = await UserModel.count()
812 const totalDailyActiveUsers = await getActiveUsers(1)
813 const totalWeeklyActiveUsers = await getActiveUsers(7)
814 const totalMonthlyActiveUsers = await getActiveUsers(30)
815 const totalHalfYearActiveUsers = await getActiveUsers(180)
819 totalDailyActiveUsers,
820 totalWeeklyActiveUsers,
821 totalMonthlyActiveUsers,
822 totalHalfYearActiveUsers
826 static autoComplete (search: string) {
830 [Op.like]: `%${search}%`
836 return UserModel.findAll(query)
837 .then(u => u.map(u => u.username))
840 canGetVideo (video: MVideoWithRights) {
841 const videoUserId = video.VideoChannel.Account.userId
843 if (video.isBlacklisted()) {
844 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
847 if (video.privacy === VideoPrivacy.PRIVATE) {
848 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
851 if (video.privacy === VideoPrivacy.INTERNAL) return true
856 hasRight (right: UserRight) {
857 return hasUserRight(this.role, right)
860 hasAdminFlag (flag: UserAdminFlag) {
861 return this.adminFlags & flag
864 isPasswordMatch (password: string) {
865 return comparePassword(password, this.password)
868 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
869 const videoQuotaUsed = this.get('videoQuotaUsed')
870 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
871 const videosCount = this.get('videosCount')
872 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
873 const abusesCreatedCount = this.get('abusesCreatedCount')
874 const videoCommentsCount = this.get('videoCommentsCount')
878 username: this.username,
880 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
882 pendingEmail: this.pendingEmail,
883 emailVerified: this.emailVerified,
885 nsfwPolicy: this.nsfwPolicy,
886 webTorrentEnabled: this.webTorrentEnabled,
887 videosHistoryEnabled: this.videosHistoryEnabled,
888 autoPlayVideo: this.autoPlayVideo,
889 autoPlayNextVideo: this.autoPlayNextVideo,
890 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
891 videoLanguages: this.videoLanguages,
894 roleLabel: USER_ROLE_LABELS[this.role],
896 videoQuota: this.videoQuota,
897 videoQuotaDaily: this.videoQuotaDaily,
898 videoQuotaUsed: videoQuotaUsed !== undefined
899 ? parseInt(videoQuotaUsed + '', 10)
901 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
902 ? parseInt(videoQuotaUsedDaily + '', 10)
904 videosCount: videosCount !== undefined
905 ? parseInt(videosCount + '', 10)
907 abusesCount: abusesCount
908 ? parseInt(abusesCount, 10)
910 abusesAcceptedCount: abusesAcceptedCount
911 ? parseInt(abusesAcceptedCount, 10)
913 abusesCreatedCount: abusesCreatedCount !== undefined
914 ? parseInt(abusesCreatedCount + '', 10)
916 videoCommentsCount: videoCommentsCount !== undefined
917 ? parseInt(videoCommentsCount + '', 10)
920 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
921 noWelcomeModal: this.noWelcomeModal,
923 blocked: this.blocked,
924 blockedReason: this.blockedReason,
926 account: this.Account.toFormattedJSON(),
928 notificationSettings: this.NotificationSetting
929 ? this.NotificationSetting.toFormattedJSON()
934 createdAt: this.createdAt,
936 pluginAuth: this.pluginAuth,
938 lastLoginDate: this.lastLoginDate
941 if (parameters.withAdminFlags) {
942 Object.assign(json, { adminFlags: this.adminFlags })
945 if (Array.isArray(this.Account.VideoChannels) === true) {
946 json.videoChannels = this.Account.VideoChannels
947 .map(c => c.toFormattedJSON())
949 if (v1.createdAt < v2.createdAt) return -1
950 if (v1.createdAt === v2.createdAt) return 0
959 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
960 const formatted = this.toFormattedJSON()
962 const specialPlaylists = this.Account.VideoPlaylists
963 .map(p => ({ id: p.id, name: p.name, type: p.type }))
965 return Object.assign(formatted, { specialPlaylists })