1 import * as Bluebird from 'bluebird'
2 import { values } from 'lodash'
3 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<UserModel> {
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
367 @HasOne(() => AccountModel, {
368 foreignKey: 'userId',
372 Account: AccountModel
374 @HasOne(() => UserNotificationSettingModel, {
375 foreignKey: 'userId',
379 NotificationSetting: UserNotificationSettingModel
381 @HasMany(() => VideoImportModel, {
382 foreignKey: 'userId',
385 VideoImports: VideoImportModel[]
387 @HasMany(() => OAuthTokenModel, {
388 foreignKey: 'userId',
391 OAuthTokens: OAuthTokenModel[]
395 static cryptPasswordIfNeeded (instance: UserModel) {
396 if (instance.changed('password') && instance.password) {
397 return cryptPassword(instance.password)
399 instance.password = hash
407 static removeTokenCache (instance: UserModel) {
408 return clearCacheByUserId(instance.id)
411 static countTotal () {
415 static listForApi (parameters: {
422 const { start, count, sort, search, blocked } = parameters
423 const where: WhereOptions = {}
426 Object.assign(where, {
430 [Op.iLike]: '%' + search + '%'
435 [Op.iLike]: '%' + search + '%'
442 if (blocked !== undefined) {
443 Object.assign(where, {
448 const query: FindOptions = {
454 UserModel.generateUserQuotaBaseSQL({
456 whereUserId: '"UserModel"."id"'
461 ] as any // FIXME: typings
466 order: getSort(sort),
470 return UserModel.findAndCountAll(query)
471 .then(({ rows, count }) => {
479 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
480 const roles = Object.keys(USER_ROLE_LABELS)
481 .map(k => parseInt(k, 10) as UserRole)
482 .filter(role => hasUserRight(role, right))
492 return UserModel.findAll(query)
495 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
499 model: UserNotificationSettingModel.unscoped(),
503 attributes: [ 'userId' ],
504 model: AccountModel.unscoped(),
509 model: ActorModel.unscoped(),
517 as: 'ActorFollowings',
518 model: ActorFollowModel.unscoped(),
521 targetActorId: actorId
531 return UserModel.unscoped().findAll(query)
534 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
541 return UserModel.findAll(query)
544 static loadById (id: number): Bluebird<MUser> {
545 return UserModel.unscoped().findByPk(id)
548 static loadByIdWithChannels (id: number, withStats = false): Bluebird<MUserDefault> {
550 ScopeNames.WITH_VIDEOCHANNELS
553 if (withStats) scopes.push(ScopeNames.WITH_STATS)
555 return UserModel.scope(scopes).findByPk(id)
558 static loadByUsername (username: string): Bluebird<MUserDefault> {
561 username: { [Op.iLike]: username }
565 return UserModel.findOne(query)
568 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
571 username: { [Op.iLike]: username }
575 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
578 static loadByEmail (email: string): Bluebird<MUserDefault> {
585 return UserModel.findOne(query)
588 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
589 if (!email) email = username
594 where(fn('lower', col('username')), fn('lower', username)),
601 return UserModel.findOne(query)
604 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
609 attributes: [ 'id' ],
610 model: AccountModel.unscoped(),
614 attributes: [ 'id' ],
615 model: VideoChannelModel.unscoped(),
619 attributes: [ 'id' ],
620 model: VideoModel.unscoped(),
632 return UserModel.findOne(query)
635 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
640 attributes: [ 'id' ],
641 model: VideoImportModel.unscoped(),
649 return UserModel.findOne(query)
652 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
657 attributes: [ 'id' ],
658 model: AccountModel.unscoped(),
662 attributes: [ 'id' ],
663 model: VideoChannelModel.unscoped(),
665 actorId: videoChannelActorId
673 return UserModel.findOne(query)
676 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
681 attributes: [ 'id' ],
682 model: AccountModel.unscoped(),
684 actorId: accountActorId
690 return UserModel.findOne(query)
693 static loadByLiveId (liveId: number): Bluebird<MUser> {
697 attributes: [ 'id' ],
698 model: AccountModel.unscoped(),
702 attributes: [ 'id' ],
703 model: VideoChannelModel.unscoped(),
707 attributes: [ 'id' ],
708 model: VideoModel.unscoped(),
713 model: VideoLiveModel.unscoped(),
728 return UserModel.unscoped().findOne(query)
731 static generateUserQuotaBaseSQL (options: {
732 whereUserId: '$userId' | '"UserModel"."id"'
736 const andWhere = options.where
737 ? 'AND ' + options.where
740 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
741 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
742 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
744 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
745 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
748 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
749 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
750 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
753 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
755 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
756 'GROUP BY "t1"."videoId"' +
760 static getTotalRawQuery (query: string, userId: number) {
763 type: QueryTypes.SELECT as QueryTypes.SELECT
766 return UserModel.sequelize.query<{ total: string }>(query, options)
767 .then(([ { total } ]) => {
768 if (total === null) return 0
770 return parseInt(total, 10)
774 static async getStats () {
775 function getActiveUsers (days: number) {
779 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
784 return UserModel.count(query)
787 const totalUsers = await UserModel.count()
788 const totalDailyActiveUsers = await getActiveUsers(1)
789 const totalWeeklyActiveUsers = await getActiveUsers(7)
790 const totalMonthlyActiveUsers = await getActiveUsers(30)
794 totalDailyActiveUsers,
795 totalWeeklyActiveUsers,
796 totalMonthlyActiveUsers
800 static autoComplete (search: string) {
804 [Op.like]: `%${search}%`
810 return UserModel.findAll(query)
811 .then(u => u.map(u => u.username))
814 canGetVideo (video: MVideoFullLight) {
815 const videoUserId = video.VideoChannel.Account.userId
817 if (video.isBlacklisted()) {
818 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
821 if (video.privacy === VideoPrivacy.PRIVATE) {
822 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
825 if (video.privacy === VideoPrivacy.INTERNAL) return true
830 hasRight (right: UserRight) {
831 return hasUserRight(this.role, right)
834 hasAdminFlag (flag: UserAdminFlag) {
835 return this.adminFlags & flag
838 isPasswordMatch (password: string) {
839 return comparePassword(password, this.password)
842 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
843 const videoQuotaUsed = this.get('videoQuotaUsed')
844 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
845 const videosCount = this.get('videosCount')
846 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
847 const abusesCreatedCount = this.get('abusesCreatedCount')
848 const videoCommentsCount = this.get('videoCommentsCount')
852 username: this.username,
854 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
856 pendingEmail: this.pendingEmail,
857 emailVerified: this.emailVerified,
859 nsfwPolicy: this.nsfwPolicy,
860 webTorrentEnabled: this.webTorrentEnabled,
861 videosHistoryEnabled: this.videosHistoryEnabled,
862 autoPlayVideo: this.autoPlayVideo,
863 autoPlayNextVideo: this.autoPlayNextVideo,
864 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
865 videoLanguages: this.videoLanguages,
868 roleLabel: USER_ROLE_LABELS[this.role],
870 videoQuota: this.videoQuota,
871 videoQuotaDaily: this.videoQuotaDaily,
872 videoQuotaUsed: videoQuotaUsed !== undefined
873 ? parseInt(videoQuotaUsed + '', 10)
875 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
876 ? parseInt(videoQuotaUsedDaily + '', 10)
878 videosCount: videosCount !== undefined
879 ? parseInt(videosCount + '', 10)
881 abusesCount: abusesCount
882 ? parseInt(abusesCount, 10)
884 abusesAcceptedCount: abusesAcceptedCount
885 ? parseInt(abusesAcceptedCount, 10)
887 abusesCreatedCount: abusesCreatedCount !== undefined
888 ? parseInt(abusesCreatedCount + '', 10)
890 videoCommentsCount: videoCommentsCount !== undefined
891 ? parseInt(videoCommentsCount + '', 10)
894 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
895 noWelcomeModal: this.noWelcomeModal,
897 blocked: this.blocked,
898 blockedReason: this.blockedReason,
900 account: this.Account.toFormattedJSON(),
902 notificationSettings: this.NotificationSetting
903 ? this.NotificationSetting.toFormattedJSON()
908 createdAt: this.createdAt,
910 pluginAuth: this.pluginAuth,
912 lastLoginDate: this.lastLoginDate
915 if (parameters.withAdminFlags) {
916 Object.assign(json, { adminFlags: this.adminFlags })
919 if (Array.isArray(this.Account.VideoChannels) === true) {
920 json.videoChannels = this.Account.VideoChannels
921 .map(c => c.toFormattedJSON())
923 if (v1.createdAt < v2.createdAt) return -1
924 if (v1.createdAt === v2.createdAt) return 0
933 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
934 const formatted = this.toFormattedJSON()
936 const specialPlaylists = this.Account.VideoPlaylists
937 .map(p => ({ id: p.id, name: p.name, type: p.type }))
939 return Object.assign(formatted, { specialPlaylists })