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 { VideoPlaylistModel } from '../video/video-playlist'
71 import { AccountModel } from './account'
72 import { UserNotificationSettingModel } from './user-notification-setting'
75 FOR_ME_API = 'FOR_ME_API',
76 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
77 WITH_STATS = 'WITH_STATS'
80 @DefaultScope(() => ({
87 model: UserNotificationSettingModel,
93 [ScopeNames.FOR_ME_API]: {
99 model: VideoChannelModel
102 attributes: [ 'id', 'name', 'type' ],
103 model: VideoPlaylistModel.unscoped(),
107 [Op.ne]: VideoPlaylistType.REGULAR
114 model: UserNotificationSettingModel,
119 [ScopeNames.WITH_VIDEOCHANNELS]: {
125 model: VideoChannelModel
128 attributes: [ 'id', 'name', 'type' ],
129 model: VideoPlaylistModel.unscoped(),
133 [Op.ne]: VideoPlaylistType.REGULAR
141 [ScopeNames.WITH_STATS]: {
147 UserModel.generateUserQuotaBaseSQL({
149 whereUserId: '"UserModel"."id"'
158 'SELECT COUNT("video"."id") ' +
160 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
161 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
162 'WHERE "account"."userId" = "UserModel"."id"' +
170 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
172 'SELECT COUNT("abuse"."id") AS "abuses", ' +
173 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
175 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
176 'WHERE "account"."userId" = "UserModel"."id"' +
185 'SELECT COUNT("abuse"."id") ' +
187 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
188 'WHERE "account"."userId" = "UserModel"."id"' +
196 'SELECT COUNT("videoComment"."id") ' +
197 'FROM "videoComment" ' +
198 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
199 'WHERE "account"."userId" = "UserModel"."id"' +
212 fields: [ 'username' ],
221 export class UserModel extends Model<UserModel> {
224 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
229 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
235 @Column(DataType.STRING(400))
240 @Column(DataType.STRING(400))
245 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
247 emailVerified: boolean
250 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
251 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
252 nsfwPolicy: NSFWPolicyType
256 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
258 webTorrentEnabled: boolean
262 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
264 videosHistoryEnabled: boolean
268 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
270 autoPlayVideo: boolean
274 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
276 autoPlayNextVideo: boolean
281 'UserAutoPlayNextVideoPlaylist',
282 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
285 autoPlayNextVideoPlaylist: boolean
289 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
290 @Column(DataType.ARRAY(DataType.STRING))
291 videoLanguages: string[]
294 @Default(UserAdminFlag.NONE)
295 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
297 adminFlags?: UserAdminFlag
301 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
307 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
309 blockedReason: string
312 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
317 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
318 @Column(DataType.BIGINT)
322 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
323 @Column(DataType.BIGINT)
324 videoQuotaDaily: number
327 @Default(DEFAULT_USER_THEME_NAME)
328 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
335 'UserNoInstanceConfigWarningModal',
336 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
339 noInstanceConfigWarningModal: boolean
344 'UserNoInstanceConfigWarningModal',
345 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
348 noWelcomeModal: boolean
366 @HasOne(() => AccountModel, {
367 foreignKey: 'userId',
371 Account: AccountModel
373 @HasOne(() => UserNotificationSettingModel, {
374 foreignKey: 'userId',
378 NotificationSetting: UserNotificationSettingModel
380 @HasMany(() => VideoImportModel, {
381 foreignKey: 'userId',
384 VideoImports: VideoImportModel[]
386 @HasMany(() => OAuthTokenModel, {
387 foreignKey: 'userId',
390 OAuthTokens: OAuthTokenModel[]
394 static cryptPasswordIfNeeded (instance: UserModel) {
395 if (instance.changed('password') && instance.password) {
396 return cryptPassword(instance.password)
398 instance.password = hash
406 static removeTokenCache (instance: UserModel) {
407 return clearCacheByUserId(instance.id)
410 static countTotal () {
414 static listForApi (parameters: {
421 const { start, count, sort, search, blocked } = parameters
422 const where: WhereOptions = {}
425 Object.assign(where, {
429 [Op.iLike]: '%' + search + '%'
434 [Op.iLike]: '%' + search + '%'
441 if (blocked !== undefined) {
442 Object.assign(where, {
447 const query: FindOptions = {
453 UserModel.generateUserQuotaBaseSQL({
455 whereUserId: '"UserModel"."id"'
460 ] as any // FIXME: typings
465 order: getSort(sort),
469 return UserModel.findAndCountAll(query)
470 .then(({ rows, count }) => {
478 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
479 const roles = Object.keys(USER_ROLE_LABELS)
480 .map(k => parseInt(k, 10) as UserRole)
481 .filter(role => hasUserRight(role, right))
491 return UserModel.findAll(query)
494 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
498 model: UserNotificationSettingModel.unscoped(),
502 attributes: [ 'userId' ],
503 model: AccountModel.unscoped(),
508 model: ActorModel.unscoped(),
516 as: 'ActorFollowings',
517 model: ActorFollowModel.unscoped(),
520 targetActorId: actorId
530 return UserModel.unscoped().findAll(query)
533 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
540 return UserModel.findAll(query)
543 static loadById (id: number, withStats = false): Bluebird<MUserDefault> {
545 ScopeNames.WITH_VIDEOCHANNELS
548 if (withStats) scopes.push(ScopeNames.WITH_STATS)
550 return UserModel.scope(scopes).findByPk(id)
553 static loadByUsername (username: string): Bluebird<MUserDefault> {
556 username: { [Op.iLike]: username }
560 return UserModel.findOne(query)
563 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
566 username: { [Op.iLike]: username }
570 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
573 static loadByEmail (email: string): Bluebird<MUserDefault> {
580 return UserModel.findOne(query)
583 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
584 if (!email) email = username
589 where(fn('lower', col('username')), fn('lower', username)),
596 return UserModel.findOne(query)
599 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
604 attributes: [ 'id' ],
605 model: AccountModel.unscoped(),
609 attributes: [ 'id' ],
610 model: VideoChannelModel.unscoped(),
614 attributes: [ 'id' ],
615 model: VideoModel.unscoped(),
627 return UserModel.findOne(query)
630 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
635 attributes: [ 'id' ],
636 model: VideoImportModel.unscoped(),
644 return UserModel.findOne(query)
647 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
652 attributes: [ 'id' ],
653 model: AccountModel.unscoped(),
657 attributes: [ 'id' ],
658 model: VideoChannelModel.unscoped(),
660 actorId: videoChannelActorId
668 return UserModel.findOne(query)
671 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
676 attributes: [ 'id' ],
677 model: AccountModel.unscoped(),
679 actorId: accountActorId
685 return UserModel.findOne(query)
688 static getOriginalVideoFileTotalFromUser (user: MUserId) {
689 // Don't use sequelize because we need to use a sub query
690 const query = UserModel.generateUserQuotaBaseSQL({
692 whereUserId: '$userId'
695 return UserModel.getTotalRawQuery(query, user.id)
698 // Returns cumulative size of all video files uploaded in the last 24 hours.
699 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
700 // Don't use sequelize because we need to use a sub query
701 const query = UserModel.generateUserQuotaBaseSQL({
703 whereUserId: '$userId',
704 where: '"video"."createdAt" > now() - interval \'24 hours\''
707 return UserModel.getTotalRawQuery(query, user.id)
710 static async getStats () {
711 function getActiveUsers (days: number) {
715 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
720 return UserModel.count(query)
723 const totalUsers = await UserModel.count()
724 const totalDailyActiveUsers = await getActiveUsers(1)
725 const totalWeeklyActiveUsers = await getActiveUsers(7)
726 const totalMonthlyActiveUsers = await getActiveUsers(30)
730 totalDailyActiveUsers,
731 totalWeeklyActiveUsers,
732 totalMonthlyActiveUsers
736 static autoComplete (search: string) {
740 [Op.like]: `%${search}%`
746 return UserModel.findAll(query)
747 .then(u => u.map(u => u.username))
750 canGetVideo (video: MVideoFullLight) {
751 const videoUserId = video.VideoChannel.Account.userId
753 if (video.isBlacklisted()) {
754 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
757 if (video.privacy === VideoPrivacy.PRIVATE) {
758 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
761 if (video.privacy === VideoPrivacy.INTERNAL) return true
766 hasRight (right: UserRight) {
767 return hasUserRight(this.role, right)
770 hasAdminFlag (flag: UserAdminFlag) {
771 return this.adminFlags & flag
774 isPasswordMatch (password: string) {
775 return comparePassword(password, this.password)
778 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
779 const videoQuotaUsed = this.get('videoQuotaUsed')
780 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
781 const videosCount = this.get('videosCount')
782 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
783 const abusesCreatedCount = this.get('abusesCreatedCount')
784 const videoCommentsCount = this.get('videoCommentsCount')
788 username: this.username,
790 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
792 pendingEmail: this.pendingEmail,
793 emailVerified: this.emailVerified,
795 nsfwPolicy: this.nsfwPolicy,
796 webTorrentEnabled: this.webTorrentEnabled,
797 videosHistoryEnabled: this.videosHistoryEnabled,
798 autoPlayVideo: this.autoPlayVideo,
799 autoPlayNextVideo: this.autoPlayNextVideo,
800 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
801 videoLanguages: this.videoLanguages,
804 roleLabel: USER_ROLE_LABELS[this.role],
806 videoQuota: this.videoQuota,
807 videoQuotaDaily: this.videoQuotaDaily,
808 videoQuotaUsed: videoQuotaUsed !== undefined
809 ? parseInt(videoQuotaUsed + '', 10)
811 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
812 ? parseInt(videoQuotaUsedDaily + '', 10)
814 videosCount: videosCount !== undefined
815 ? parseInt(videosCount + '', 10)
817 abusesCount: abusesCount
818 ? parseInt(abusesCount, 10)
820 abusesAcceptedCount: abusesAcceptedCount
821 ? parseInt(abusesAcceptedCount, 10)
823 abusesCreatedCount: abusesCreatedCount !== undefined
824 ? parseInt(abusesCreatedCount + '', 10)
826 videoCommentsCount: videoCommentsCount !== undefined
827 ? parseInt(videoCommentsCount + '', 10)
830 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
831 noWelcomeModal: this.noWelcomeModal,
833 blocked: this.blocked,
834 blockedReason: this.blockedReason,
836 account: this.Account.toFormattedJSON(),
838 notificationSettings: this.NotificationSetting
839 ? this.NotificationSetting.toFormattedJSON()
844 createdAt: this.createdAt,
846 pluginAuth: this.pluginAuth,
848 lastLoginDate: this.lastLoginDate
851 if (parameters.withAdminFlags) {
852 Object.assign(json, { adminFlags: this.adminFlags })
855 if (Array.isArray(this.Account.VideoChannels) === true) {
856 json.videoChannels = this.Account.VideoChannels
857 .map(c => c.toFormattedJSON())
859 if (v1.createdAt < v2.createdAt) return -1
860 if (v1.createdAt === v2.createdAt) return 0
869 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
870 const formatted = this.toFormattedJSON()
872 const specialPlaylists = this.Account.VideoPlaylists
873 .map(p => ({ id: p.id, name: p.name, type: p.type }))
875 return Object.assign(formatted, { specialPlaylists })
878 async isAbleToUploadVideo (videoFile: { size: number }) {
879 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
881 const [ totalBytes, totalBytesDaily ] = await Promise.all([
882 UserModel.getOriginalVideoFileTotalFromUser(this),
883 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
886 const uploadedTotal = videoFile.size + totalBytes
887 const uploadedDaily = videoFile.size + totalBytesDaily
889 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
890 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
892 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
895 private static generateUserQuotaBaseSQL (options: {
896 whereUserId: '$userId' | '"UserModel"."id"'
900 const andWhere = options.where
901 ? 'AND ' + options.where
904 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
905 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
906 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
908 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
909 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
912 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
913 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
914 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
917 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
919 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
920 'GROUP BY "t1"."videoId"' +
924 private static getTotalRawQuery (query: string, userId: number) {
927 type: QueryTypes.SELECT as QueryTypes.SELECT
930 return UserModel.sequelize.query<{ total: string }>(query, options)
931 .then(([ { total } ]) => {
932 if (total === null) return 0
934 return parseInt(total, 10)