1 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, VideoAbuseState, 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("videoAbuse"."id") AS "abuses", ' +
172 `COUNT("videoAbuse"."id") FILTER (WHERE "videoAbuse"."state" = ${VideoAbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
173 'FROM "videoAbuse" ' +
174 'INNER JOIN "video" ON "videoAbuse"."videoId" = "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"' +
186 'SELECT COUNT("videoAbuse"."id") ' +
187 'FROM "videoAbuse" ' +
188 'INNER JOIN "account" ON "account"."id" = "videoAbuse"."reporterAccountId" ' +
189 'WHERE "account"."userId" = "UserModel"."id"' +
192 'videoAbusesCreatedCount'
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, withStats = false): Bluebird<MUserDefault> {
546 ScopeNames.WITH_VIDEOCHANNELS
549 if (withStats) scopes.push(ScopeNames.WITH_STATS)
551 return UserModel.scope(scopes).findByPk(id)
554 static loadByUsername (username: string): Bluebird<MUserDefault> {
557 username: { [Op.iLike]: username }
561 return UserModel.findOne(query)
564 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
567 username: { [Op.iLike]: username }
571 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
574 static loadByEmail (email: string): Bluebird<MUserDefault> {
581 return UserModel.findOne(query)
584 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
585 if (!email) email = username
590 where(fn('lower', col('username')), fn('lower', username)),
597 return UserModel.findOne(query)
600 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
605 attributes: [ 'id' ],
606 model: AccountModel.unscoped(),
610 attributes: [ 'id' ],
611 model: VideoChannelModel.unscoped(),
615 attributes: [ 'id' ],
616 model: VideoModel.unscoped(),
628 return UserModel.findOne(query)
631 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
636 attributes: [ 'id' ],
637 model: VideoImportModel.unscoped(),
645 return UserModel.findOne(query)
648 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
653 attributes: [ 'id' ],
654 model: AccountModel.unscoped(),
658 attributes: [ 'id' ],
659 model: VideoChannelModel.unscoped(),
661 actorId: videoChannelActorId
669 return UserModel.findOne(query)
672 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
677 attributes: [ 'id' ],
678 model: AccountModel.unscoped(),
680 actorId: accountActorId
686 return UserModel.findOne(query)
689 static getOriginalVideoFileTotalFromUser (user: MUserId) {
690 // Don't use sequelize because we need to use a sub query
691 const query = UserModel.generateUserQuotaBaseSQL({
693 whereUserId: '$userId'
696 return UserModel.getTotalRawQuery(query, user.id)
699 // Returns cumulative size of all video files uploaded in the last 24 hours.
700 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
701 // Don't use sequelize because we need to use a sub query
702 const query = UserModel.generateUserQuotaBaseSQL({
704 whereUserId: '$userId',
705 where: '"video"."createdAt" > now() - interval \'24 hours\''
708 return UserModel.getTotalRawQuery(query, user.id)
711 static async getStats () {
712 function getActiveUsers (days: number) {
716 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
721 return UserModel.count(query)
724 const totalUsers = await UserModel.count()
725 const totalDailyActiveUsers = await getActiveUsers(1)
726 const totalWeeklyActiveUsers = await getActiveUsers(7)
727 const totalMonthlyActiveUsers = await getActiveUsers(30)
731 totalDailyActiveUsers,
732 totalWeeklyActiveUsers,
733 totalMonthlyActiveUsers
737 static autoComplete (search: string) {
741 [Op.like]: `%${search}%`
747 return UserModel.findAll(query)
748 .then(u => u.map(u => u.username))
751 canGetVideo (video: MVideoFullLight) {
752 const videoUserId = video.VideoChannel.Account.userId
754 if (video.isBlacklisted()) {
755 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
758 if (video.privacy === VideoPrivacy.PRIVATE) {
759 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
762 if (video.privacy === VideoPrivacy.INTERNAL) return true
767 hasRight (right: UserRight) {
768 return hasUserRight(this.role, right)
771 hasAdminFlag (flag: UserAdminFlag) {
772 return this.adminFlags & flag
775 isPasswordMatch (password: string) {
776 return comparePassword(password, this.password)
779 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
780 const videoQuotaUsed = this.get('videoQuotaUsed')
781 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
782 const videosCount = this.get('videosCount')
783 const [ videoAbusesCount, videoAbusesAcceptedCount ] = (this.get('videoAbusesCount') as string || ':').split(':')
784 const videoAbusesCreatedCount = this.get('videoAbusesCreatedCount')
785 const videoCommentsCount = this.get('videoCommentsCount')
789 username: this.username,
791 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
793 pendingEmail: this.pendingEmail,
794 emailVerified: this.emailVerified,
796 nsfwPolicy: this.nsfwPolicy,
797 webTorrentEnabled: this.webTorrentEnabled,
798 videosHistoryEnabled: this.videosHistoryEnabled,
799 autoPlayVideo: this.autoPlayVideo,
800 autoPlayNextVideo: this.autoPlayNextVideo,
801 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
802 videoLanguages: this.videoLanguages,
805 roleLabel: USER_ROLE_LABELS[this.role],
807 videoQuota: this.videoQuota,
808 videoQuotaDaily: this.videoQuotaDaily,
809 videoQuotaUsed: videoQuotaUsed !== undefined
810 ? parseInt(videoQuotaUsed + '', 10)
812 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
813 ? parseInt(videoQuotaUsedDaily + '', 10)
815 videosCount: videosCount !== undefined
816 ? parseInt(videosCount + '', 10)
818 videoAbusesCount: videoAbusesCount
819 ? parseInt(videoAbusesCount, 10)
821 videoAbusesAcceptedCount: videoAbusesAcceptedCount
822 ? parseInt(videoAbusesAcceptedCount, 10)
824 videoAbusesCreatedCount: videoAbusesCreatedCount !== undefined
825 ? parseInt(videoAbusesCreatedCount + '', 10)
827 videoCommentsCount: videoCommentsCount !== undefined
828 ? parseInt(videoCommentsCount + '', 10)
831 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
832 noWelcomeModal: this.noWelcomeModal,
834 blocked: this.blocked,
835 blockedReason: this.blockedReason,
837 account: this.Account.toFormattedJSON(),
839 notificationSettings: this.NotificationSetting
840 ? this.NotificationSetting.toFormattedJSON()
845 createdAt: this.createdAt,
847 pluginAuth: this.pluginAuth,
849 lastLoginDate: this.lastLoginDate
852 if (parameters.withAdminFlags) {
853 Object.assign(json, { adminFlags: this.adminFlags })
856 if (Array.isArray(this.Account.VideoChannels) === true) {
857 json.videoChannels = this.Account.VideoChannels
858 .map(c => c.toFormattedJSON())
860 if (v1.createdAt < v2.createdAt) return -1
861 if (v1.createdAt === v2.createdAt) return 0
870 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
871 const formatted = this.toFormattedJSON()
873 const specialPlaylists = this.Account.VideoPlaylists
874 .map(p => ({ id: p.id, name: p.name, type: p.type }))
876 return Object.assign(formatted, { specialPlaylists })
879 async isAbleToUploadVideo (videoFile: { size: number }) {
880 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
882 const [ totalBytes, totalBytesDaily ] = await Promise.all([
883 UserModel.getOriginalVideoFileTotalFromUser(this),
884 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
887 const uploadedTotal = videoFile.size + totalBytes
888 const uploadedDaily = videoFile.size + totalBytesDaily
890 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
891 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
893 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
896 private static generateUserQuotaBaseSQL (options: {
897 whereUserId: '$userId' | '"UserModel"."id"'
901 const andWhere = options.where
902 ? 'AND ' + options.where
905 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
906 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
907 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
909 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
910 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
913 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
914 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
915 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
918 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
920 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
921 'GROUP BY "t1"."videoId"' +
925 private static getTotalRawQuery (query: string, userId: number) {
928 type: QueryTypes.SELECT as QueryTypes.SELECT
931 return UserModel.sequelize.query<{ total: string }>(query, options)
932 .then(([ { total } ]) => {
933 if (total === null) return 0
935 return parseInt(total, 10)