1 import { FindOptions, literal, Op, QueryTypes, where, fn, col, WhereOptions } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, VideoPlaylistType, VideoPrivacy, VideoAbuseState } 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/typings/models'
73 const literalVideoQuotaUsed: any = [
76 'SELECT COALESCE(SUM("size"), 0) ' +
78 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
79 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
80 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
81 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
82 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
90 FOR_ME_API = 'FOR_ME_API',
91 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
92 WITH_STATS = 'WITH_STATS'
95 @DefaultScope(() => ({
102 model: UserNotificationSettingModel,
108 [ScopeNames.FOR_ME_API]: {
114 model: VideoChannelModel
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]: {
159 literalVideoQuotaUsed,
163 'SELECT COUNT("video"."id") ' +
165 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
166 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
167 'WHERE "account"."userId" = "UserModel"."id"' +
175 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
177 'SELECT COUNT("videoAbuse"."id") AS "abuses", ' +
178 `COUNT("videoAbuse"."id") FILTER (WHERE "videoAbuse"."state" = ${VideoAbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
179 'FROM "videoAbuse" ' +
180 'INNER JOIN "video" ON "videoAbuse"."videoId" = "video"."id" ' +
181 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
182 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
183 'WHERE "account"."userId" = "UserModel"."id"' +
192 'SELECT COUNT("videoAbuse"."id") ' +
193 'FROM "videoAbuse" ' +
194 'INNER JOIN "account" ON "account"."id" = "videoAbuse"."reporterAccountId" ' +
195 'WHERE "account"."userId" = "UserModel"."id"' +
198 'videoAbusesCreatedCount'
203 'SELECT COUNT("videoComment"."id") ' +
204 'FROM "videoComment" ' +
205 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
206 'WHERE "account"."userId" = "UserModel"."id"' +
219 fields: [ 'username' ],
228 export class UserModel extends Model<UserModel> {
231 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
236 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
242 @Column(DataType.STRING(400))
247 @Column(DataType.STRING(400))
252 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
254 emailVerified: boolean
257 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
258 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
259 nsfwPolicy: NSFWPolicyType
263 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
265 webTorrentEnabled: boolean
269 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
271 videosHistoryEnabled: boolean
275 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
277 autoPlayVideo: boolean
281 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
283 autoPlayNextVideo: boolean
288 'UserAutoPlayNextVideoPlaylist',
289 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
292 autoPlayNextVideoPlaylist: boolean
296 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
297 @Column(DataType.ARRAY(DataType.STRING))
298 videoLanguages: string[]
301 @Default(UserAdminFlag.NONE)
302 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
304 adminFlags?: UserAdminFlag
308 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
314 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
316 blockedReason: string
319 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
324 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
325 @Column(DataType.BIGINT)
329 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
330 @Column(DataType.BIGINT)
331 videoQuotaDaily: number
334 @Default(DEFAULT_USER_THEME_NAME)
335 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
342 'UserNoInstanceConfigWarningModal',
343 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
346 noInstanceConfigWarningModal: boolean
351 'UserNoInstanceConfigWarningModal',
352 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
355 noWelcomeModal: boolean
363 @HasOne(() => AccountModel, {
364 foreignKey: 'userId',
368 Account: AccountModel
370 @HasOne(() => UserNotificationSettingModel, {
371 foreignKey: 'userId',
375 NotificationSetting: UserNotificationSettingModel
377 @HasMany(() => VideoImportModel, {
378 foreignKey: 'userId',
381 VideoImports: VideoImportModel[]
383 @HasMany(() => OAuthTokenModel, {
384 foreignKey: 'userId',
387 OAuthTokens: OAuthTokenModel[]
391 static cryptPasswordIfNeeded (instance: UserModel) {
392 if (instance.changed('password')) {
393 return cryptPassword(instance.password)
395 instance.password = hash
403 static removeTokenCache (instance: UserModel) {
404 return clearCacheByUserId(instance.id)
407 static countTotal () {
411 static listForApi (start: number, count: number, sort: string, search?: string) {
412 let where: WhereOptions
419 [Op.iLike]: '%' + search + '%'
424 [Op.iLike]: '%' + search + '%'
431 const query: FindOptions = {
433 include: [ literalVideoQuotaUsed ]
437 order: getSort(sort),
441 return UserModel.findAndCountAll(query)
442 .then(({ rows, count }) => {
450 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
451 const roles = Object.keys(USER_ROLE_LABELS)
452 .map(k => parseInt(k, 10) as UserRole)
453 .filter(role => hasUserRight(role, right))
463 return UserModel.findAll(query)
466 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
470 model: UserNotificationSettingModel.unscoped(),
474 attributes: [ 'userId' ],
475 model: AccountModel.unscoped(),
480 model: ActorModel.unscoped(),
488 as: 'ActorFollowings',
489 model: ActorFollowModel.unscoped(),
492 targetActorId: actorId
502 return UserModel.unscoped().findAll(query)
505 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
512 return UserModel.findAll(query)
515 static loadById (id: number, withStats = false): Bluebird<MUserDefault> {
517 ScopeNames.WITH_VIDEOCHANNELS
520 if (withStats) scopes.push(ScopeNames.WITH_STATS)
522 return UserModel.scope(scopes).findByPk(id)
525 static loadByUsername (username: string): Bluebird<MUserDefault> {
528 username: { [Op.iLike]: username }
532 return UserModel.findOne(query)
535 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
538 username: { [Op.iLike]: username }
542 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
545 static loadByEmail (email: string): Bluebird<MUserDefault> {
552 return UserModel.findOne(query)
555 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
556 if (!email) email = username
561 where(fn('lower', col('username')), fn('lower', username)),
568 return UserModel.findOne(query)
571 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
576 attributes: [ 'id' ],
577 model: AccountModel.unscoped(),
581 attributes: [ 'id' ],
582 model: VideoChannelModel.unscoped(),
586 attributes: [ 'id' ],
587 model: VideoModel.unscoped(),
599 return UserModel.findOne(query)
602 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
607 attributes: [ 'id' ],
608 model: VideoImportModel.unscoped(),
616 return UserModel.findOne(query)
619 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
624 attributes: [ 'id' ],
625 model: AccountModel.unscoped(),
629 attributes: [ 'id' ],
630 model: VideoChannelModel.unscoped(),
632 actorId: videoChannelActorId
640 return UserModel.findOne(query)
643 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
648 attributes: [ 'id' ],
649 model: AccountModel.unscoped(),
651 actorId: accountActorId
657 return UserModel.findOne(query)
660 static getOriginalVideoFileTotalFromUser (user: MUserId) {
661 // Don't use sequelize because we need to use a sub query
662 const query = UserModel.generateUserQuotaBaseSQL()
664 return UserModel.getTotalRawQuery(query, user.id)
667 // Returns cumulative size of all video files uploaded in the last 24 hours.
668 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
669 // Don't use sequelize because we need to use a sub query
670 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
672 return UserModel.getTotalRawQuery(query, user.id)
675 static async getStats () {
676 const totalUsers = await UserModel.count()
683 static autoComplete (search: string) {
687 [Op.like]: `%${search}%`
693 return UserModel.findAll(query)
694 .then(u => u.map(u => u.username))
697 canGetVideo (video: MVideoFullLight) {
698 const videoUserId = video.VideoChannel.Account.userId
700 if (video.isBlacklisted()) {
701 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
704 if (video.privacy === VideoPrivacy.PRIVATE) {
705 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
708 if (video.privacy === VideoPrivacy.INTERNAL) return true
713 hasRight (right: UserRight) {
714 return hasUserRight(this.role, right)
717 hasAdminFlag (flag: UserAdminFlag) {
718 return this.adminFlags & flag
721 isPasswordMatch (password: string) {
722 return comparePassword(password, this.password)
725 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
726 const videoQuotaUsed = this.get('videoQuotaUsed')
727 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
728 const videosCount = this.get('videosCount')
729 const [ videoAbusesCount, videoAbusesAcceptedCount ] = (this.get('videoAbusesCount') as string || ':').split(':')
730 const videoAbusesCreatedCount = this.get('videoAbusesCreatedCount')
731 const videoCommentsCount = this.get('videoCommentsCount')
735 username: this.username,
737 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
739 pendingEmail: this.pendingEmail,
740 emailVerified: this.emailVerified,
742 nsfwPolicy: this.nsfwPolicy,
743 webTorrentEnabled: this.webTorrentEnabled,
744 videosHistoryEnabled: this.videosHistoryEnabled,
745 autoPlayVideo: this.autoPlayVideo,
746 autoPlayNextVideo: this.autoPlayNextVideo,
747 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
748 videoLanguages: this.videoLanguages,
751 roleLabel: USER_ROLE_LABELS[this.role],
753 videoQuota: this.videoQuota,
754 videoQuotaDaily: this.videoQuotaDaily,
755 videoQuotaUsed: videoQuotaUsed !== undefined
756 ? parseInt(videoQuotaUsed + '', 10)
758 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
759 ? parseInt(videoQuotaUsedDaily + '', 10)
761 videosCount: videosCount !== undefined
762 ? parseInt(videosCount + '', 10)
764 videoAbusesCount: videoAbusesCount
765 ? parseInt(videoAbusesCount, 10)
767 videoAbusesAcceptedCount: videoAbusesAcceptedCount
768 ? parseInt(videoAbusesAcceptedCount, 10)
770 videoAbusesCreatedCount: videoAbusesCreatedCount !== undefined
771 ? parseInt(videoAbusesCreatedCount + '', 10)
773 videoCommentsCount: videoCommentsCount !== undefined
774 ? parseInt(videoCommentsCount + '', 10)
777 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
778 noWelcomeModal: this.noWelcomeModal,
780 blocked: this.blocked,
781 blockedReason: this.blockedReason,
783 account: this.Account.toFormattedJSON(),
785 notificationSettings: this.NotificationSetting
786 ? this.NotificationSetting.toFormattedJSON()
791 createdAt: this.createdAt
794 if (parameters.withAdminFlags) {
795 Object.assign(json, { adminFlags: this.adminFlags })
798 if (Array.isArray(this.Account.VideoChannels) === true) {
799 json.videoChannels = this.Account.VideoChannels
800 .map(c => c.toFormattedJSON())
802 if (v1.createdAt < v2.createdAt) return -1
803 if (v1.createdAt === v2.createdAt) return 0
812 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
813 const formatted = this.toFormattedJSON()
815 const specialPlaylists = this.Account.VideoPlaylists
816 .map(p => ({ id: p.id, name: p.name, type: p.type }))
818 return Object.assign(formatted, { specialPlaylists })
821 async isAbleToUploadVideo (videoFile: { size: number }) {
822 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
824 const [ totalBytes, totalBytesDaily ] = await Promise.all([
825 UserModel.getOriginalVideoFileTotalFromUser(this),
826 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
829 const uploadedTotal = videoFile.size + totalBytes
830 const uploadedDaily = videoFile.size + totalBytesDaily
832 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
833 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
835 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
838 private static generateUserQuotaBaseSQL (where?: string) {
839 const andWhere = where ? 'AND ' + where : ''
841 return 'SELECT SUM("size") AS "total" ' +
843 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
844 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
845 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
846 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
847 'WHERE "account"."userId" = $userId ' + andWhere +
848 'GROUP BY "video"."id"' +
852 private static getTotalRawQuery (query: string, userId: number) {
855 type: QueryTypes.SELECT as QueryTypes.SELECT
858 return UserModel.sequelize.query<{ total: string }>(query, options)
859 .then(([ { total } ]) => {
860 if (total === null) return 0
862 return parseInt(total, 10)