1 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, AbuseState, VideoPlaylistType, VideoPrivacy } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isNoInstanceConfigWarningModal,
27 isUserAdminFlagsValid,
28 isUserAutoPlayNextVideoPlaylistValid,
29 isUserAutoPlayNextVideoValid,
30 isUserAutoPlayVideoValid,
31 isUserBlockedReasonValid,
33 isUserEmailVerifiedValid,
34 isUserNSFWPolicyValid,
39 isUserVideoQuotaDailyValid,
40 isUserVideoQuotaValid,
41 isUserVideosHistoryEnabledValid,
42 isUserWebTorrentEnabledValid
43 } from '../../helpers/custom-validators/users'
44 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
45 import { OAuthTokenModel } from '../oauth/oauth-token'
46 import { getSort, throwIfNotValid } from '../utils'
47 import { VideoChannelModel } from '../video/video-channel'
48 import { VideoPlaylistModel } from '../video/video-playlist'
49 import { AccountModel } from './account'
50 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
51 import { values } from 'lodash'
52 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
53 import { clearCacheByUserId } from '../../lib/oauth-model'
54 import { UserNotificationSettingModel } from './user-notification-setting'
55 import { VideoModel } from '../video/video'
56 import { ActorModel } from '../activitypub/actor'
57 import { ActorFollowModel } from '../activitypub/actor-follow'
58 import { VideoImportModel } from '../video/video-import'
59 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
60 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
61 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
62 import * as Bluebird from 'bluebird'
68 MUserNotifSettingChannelDefault,
69 MUserWithNotificationSetting,
71 } from '@server/types/models'
74 FOR_ME_API = 'FOR_ME_API',
75 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
76 WITH_STATS = 'WITH_STATS'
79 @DefaultScope(() => ({
86 model: UserNotificationSettingModel,
92 [ScopeNames.FOR_ME_API]: {
98 model: VideoChannelModel
101 attributes: [ 'id', 'name', 'type' ],
102 model: VideoPlaylistModel.unscoped(),
106 [Op.ne]: VideoPlaylistType.REGULAR
113 model: UserNotificationSettingModel,
118 [ScopeNames.WITH_VIDEOCHANNELS]: {
124 model: VideoChannelModel
127 attributes: [ 'id', 'name', 'type' ],
128 model: VideoPlaylistModel.unscoped(),
132 [Op.ne]: VideoPlaylistType.REGULAR
140 [ScopeNames.WITH_STATS]: {
146 UserModel.generateUserQuotaBaseSQL({
148 whereUserId: '"UserModel"."id"'
157 'SELECT COUNT("video"."id") ' +
159 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
160 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
161 'WHERE "account"."userId" = "UserModel"."id"' +
169 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
171 'SELECT COUNT("abuse"."id") AS "abuses", ' +
172 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
174 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
175 'WHERE "account"."userId" = "UserModel"."id"' +
184 'SELECT COUNT("abuse"."id") ' +
186 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
187 'WHERE "account"."userId" = "UserModel"."id"' +
195 'SELECT COUNT("videoComment"."id") ' +
196 'FROM "videoComment" ' +
197 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
198 'WHERE "account"."userId" = "UserModel"."id"' +
211 fields: [ 'username' ],
220 export class UserModel extends Model<UserModel> {
223 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
228 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
234 @Column(DataType.STRING(400))
239 @Column(DataType.STRING(400))
244 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
246 emailVerified: boolean
249 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
250 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
251 nsfwPolicy: NSFWPolicyType
255 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
257 webTorrentEnabled: boolean
261 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
263 videosHistoryEnabled: boolean
267 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
269 autoPlayVideo: boolean
273 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
275 autoPlayNextVideo: boolean
280 'UserAutoPlayNextVideoPlaylist',
281 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
284 autoPlayNextVideoPlaylist: boolean
288 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
289 @Column(DataType.ARRAY(DataType.STRING))
290 videoLanguages: string[]
293 @Default(UserAdminFlag.NONE)
294 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
296 adminFlags?: UserAdminFlag
300 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
306 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
308 blockedReason: string
311 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
316 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
317 @Column(DataType.BIGINT)
321 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
322 @Column(DataType.BIGINT)
323 videoQuotaDaily: number
326 @Default(DEFAULT_USER_THEME_NAME)
327 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
334 'UserNoInstanceConfigWarningModal',
335 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
338 noInstanceConfigWarningModal: boolean
343 'UserNoInstanceConfigWarningModal',
344 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
347 noWelcomeModal: boolean
365 @HasOne(() => AccountModel, {
366 foreignKey: 'userId',
370 Account: AccountModel
372 @HasOne(() => UserNotificationSettingModel, {
373 foreignKey: 'userId',
377 NotificationSetting: UserNotificationSettingModel
379 @HasMany(() => VideoImportModel, {
380 foreignKey: 'userId',
383 VideoImports: VideoImportModel[]
385 @HasMany(() => OAuthTokenModel, {
386 foreignKey: 'userId',
389 OAuthTokens: OAuthTokenModel[]
393 static cryptPasswordIfNeeded (instance: UserModel) {
394 if (instance.changed('password') && instance.password) {
395 return cryptPassword(instance.password)
397 instance.password = hash
405 static removeTokenCache (instance: UserModel) {
406 return clearCacheByUserId(instance.id)
409 static countTotal () {
413 static listForApi (parameters: {
420 const { start, count, sort, search, blocked } = parameters
421 const where: WhereOptions = {}
424 Object.assign(where, {
428 [Op.iLike]: '%' + search + '%'
433 [Op.iLike]: '%' + search + '%'
440 if (blocked !== undefined) {
441 Object.assign(where, {
446 const query: FindOptions = {
452 UserModel.generateUserQuotaBaseSQL({
454 whereUserId: '"UserModel"."id"'
459 ] as any // FIXME: typings
464 order: getSort(sort),
468 return UserModel.findAndCountAll(query)
469 .then(({ rows, count }) => {
477 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
478 const roles = Object.keys(USER_ROLE_LABELS)
479 .map(k => parseInt(k, 10) as UserRole)
480 .filter(role => hasUserRight(role, right))
490 return UserModel.findAll(query)
493 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
497 model: UserNotificationSettingModel.unscoped(),
501 attributes: [ 'userId' ],
502 model: AccountModel.unscoped(),
507 model: ActorModel.unscoped(),
515 as: 'ActorFollowings',
516 model: ActorFollowModel.unscoped(),
519 targetActorId: actorId
529 return UserModel.unscoped().findAll(query)
532 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
539 return UserModel.findAll(query)
542 static loadById (id: number, withStats = false): Bluebird<MUserDefault> {
544 ScopeNames.WITH_VIDEOCHANNELS
547 if (withStats) scopes.push(ScopeNames.WITH_STATS)
549 return UserModel.scope(scopes).findByPk(id)
552 static loadByUsername (username: string): Bluebird<MUserDefault> {
555 username: { [Op.iLike]: username }
559 return UserModel.findOne(query)
562 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
565 username: { [Op.iLike]: username }
569 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
572 static loadByEmail (email: string): Bluebird<MUserDefault> {
579 return UserModel.findOne(query)
582 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
583 if (!email) email = username
588 where(fn('lower', col('username')), fn('lower', username)),
595 return UserModel.findOne(query)
598 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
603 attributes: [ 'id' ],
604 model: AccountModel.unscoped(),
608 attributes: [ 'id' ],
609 model: VideoChannelModel.unscoped(),
613 attributes: [ 'id' ],
614 model: VideoModel.unscoped(),
626 return UserModel.findOne(query)
629 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
634 attributes: [ 'id' ],
635 model: VideoImportModel.unscoped(),
643 return UserModel.findOne(query)
646 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
651 attributes: [ 'id' ],
652 model: AccountModel.unscoped(),
656 attributes: [ 'id' ],
657 model: VideoChannelModel.unscoped(),
659 actorId: videoChannelActorId
667 return UserModel.findOne(query)
670 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
675 attributes: [ 'id' ],
676 model: AccountModel.unscoped(),
678 actorId: accountActorId
684 return UserModel.findOne(query)
687 static getOriginalVideoFileTotalFromUser (user: MUserId) {
688 // Don't use sequelize because we need to use a sub query
689 const query = UserModel.generateUserQuotaBaseSQL({
691 whereUserId: '$userId'
694 return UserModel.getTotalRawQuery(query, user.id)
697 // Returns cumulative size of all video files uploaded in the last 24 hours.
698 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
699 // Don't use sequelize because we need to use a sub query
700 const query = UserModel.generateUserQuotaBaseSQL({
702 whereUserId: '$userId',
703 where: '"video"."createdAt" > now() - interval \'24 hours\''
706 return UserModel.getTotalRawQuery(query, user.id)
709 static async getStats () {
710 function getActiveUsers (days: number) {
714 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
719 return UserModel.count(query)
722 const totalUsers = await UserModel.count()
723 const totalDailyActiveUsers = await getActiveUsers(1)
724 const totalWeeklyActiveUsers = await getActiveUsers(7)
725 const totalMonthlyActiveUsers = await getActiveUsers(30)
729 totalDailyActiveUsers,
730 totalWeeklyActiveUsers,
731 totalMonthlyActiveUsers
735 static autoComplete (search: string) {
739 [Op.like]: `%${search}%`
745 return UserModel.findAll(query)
746 .then(u => u.map(u => u.username))
749 canGetVideo (video: MVideoFullLight) {
750 const videoUserId = video.VideoChannel.Account.userId
752 if (video.isBlacklisted()) {
753 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
756 if (video.privacy === VideoPrivacy.PRIVATE) {
757 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
760 if (video.privacy === VideoPrivacy.INTERNAL) return true
765 hasRight (right: UserRight) {
766 return hasUserRight(this.role, right)
769 hasAdminFlag (flag: UserAdminFlag) {
770 return this.adminFlags & flag
773 isPasswordMatch (password: string) {
774 return comparePassword(password, this.password)
777 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
778 const videoQuotaUsed = this.get('videoQuotaUsed')
779 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
780 const videosCount = this.get('videosCount')
781 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
782 const abusesCreatedCount = this.get('abusesCreatedCount')
783 const videoCommentsCount = this.get('videoCommentsCount')
787 username: this.username,
789 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
791 pendingEmail: this.pendingEmail,
792 emailVerified: this.emailVerified,
794 nsfwPolicy: this.nsfwPolicy,
795 webTorrentEnabled: this.webTorrentEnabled,
796 videosHistoryEnabled: this.videosHistoryEnabled,
797 autoPlayVideo: this.autoPlayVideo,
798 autoPlayNextVideo: this.autoPlayNextVideo,
799 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
800 videoLanguages: this.videoLanguages,
803 roleLabel: USER_ROLE_LABELS[this.role],
805 videoQuota: this.videoQuota,
806 videoQuotaDaily: this.videoQuotaDaily,
807 videoQuotaUsed: videoQuotaUsed !== undefined
808 ? parseInt(videoQuotaUsed + '', 10)
810 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
811 ? parseInt(videoQuotaUsedDaily + '', 10)
813 videosCount: videosCount !== undefined
814 ? parseInt(videosCount + '', 10)
816 abusesCount: abusesCount
817 ? parseInt(abusesCount, 10)
819 abusesAcceptedCount: abusesAcceptedCount
820 ? parseInt(abusesAcceptedCount, 10)
822 abusesCreatedCount: abusesCreatedCount !== undefined
823 ? parseInt(abusesCreatedCount + '', 10)
825 videoCommentsCount: videoCommentsCount !== undefined
826 ? parseInt(videoCommentsCount + '', 10)
829 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
830 noWelcomeModal: this.noWelcomeModal,
832 blocked: this.blocked,
833 blockedReason: this.blockedReason,
835 account: this.Account.toFormattedJSON(),
837 notificationSettings: this.NotificationSetting
838 ? this.NotificationSetting.toFormattedJSON()
843 createdAt: this.createdAt,
845 pluginAuth: this.pluginAuth,
847 lastLoginDate: this.lastLoginDate
850 if (parameters.withAdminFlags) {
851 Object.assign(json, { adminFlags: this.adminFlags })
854 if (Array.isArray(this.Account.VideoChannels) === true) {
855 json.videoChannels = this.Account.VideoChannels
856 .map(c => c.toFormattedJSON())
858 if (v1.createdAt < v2.createdAt) return -1
859 if (v1.createdAt === v2.createdAt) return 0
868 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
869 const formatted = this.toFormattedJSON()
871 const specialPlaylists = this.Account.VideoPlaylists
872 .map(p => ({ id: p.id, name: p.name, type: p.type }))
874 return Object.assign(formatted, { specialPlaylists })
877 async isAbleToUploadVideo (videoFile: { size: number }) {
878 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
880 const [ totalBytes, totalBytesDaily ] = await Promise.all([
881 UserModel.getOriginalVideoFileTotalFromUser(this),
882 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
885 const uploadedTotal = videoFile.size + totalBytes
886 const uploadedDaily = videoFile.size + totalBytesDaily
888 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
889 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
891 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
894 private static generateUserQuotaBaseSQL (options: {
895 whereUserId: '$userId' | '"UserModel"."id"'
899 const andWhere = options.where
900 ? 'AND ' + options.where
903 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
904 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
905 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
907 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
908 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
911 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
912 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
913 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
916 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
918 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
919 'GROUP BY "t1"."videoId"' +
923 private static getTotalRawQuery (query: string, userId: number) {
926 type: QueryTypes.SELECT as QueryTypes.SELECT
929 return UserModel.sequelize.query<{ total: string }>(query, options)
930 .then(([ { total } ]) => {
931 if (total === null) return 0
933 return parseInt(total, 10)