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/typings/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'))
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
357 @HasOne(() => AccountModel, {
358 foreignKey: 'userId',
362 Account: AccountModel
364 @HasOne(() => UserNotificationSettingModel, {
365 foreignKey: 'userId',
369 NotificationSetting: UserNotificationSettingModel
371 @HasMany(() => VideoImportModel, {
372 foreignKey: 'userId',
375 VideoImports: VideoImportModel[]
377 @HasMany(() => OAuthTokenModel, {
378 foreignKey: 'userId',
381 OAuthTokens: OAuthTokenModel[]
385 static cryptPasswordIfNeeded (instance: UserModel) {
386 if (instance.changed('password')) {
387 return cryptPassword(instance.password)
389 instance.password = hash
397 static removeTokenCache (instance: UserModel) {
398 return clearCacheByUserId(instance.id)
401 static countTotal () {
405 static listForApi (start: number, count: number, sort: string, search?: string) {
406 let where: WhereOptions
413 [Op.iLike]: '%' + search + '%'
418 [Op.iLike]: '%' + search + '%'
425 const query: FindOptions = {
431 UserModel.generateUserQuotaBaseSQL({
433 whereUserId: '"UserModel"."id"'
438 ] as any // FIXME: typings
443 order: getSort(sort),
447 return UserModel.findAndCountAll(query)
448 .then(({ rows, count }) => {
456 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
457 const roles = Object.keys(USER_ROLE_LABELS)
458 .map(k => parseInt(k, 10) as UserRole)
459 .filter(role => hasUserRight(role, right))
469 return UserModel.findAll(query)
472 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
476 model: UserNotificationSettingModel.unscoped(),
480 attributes: [ 'userId' ],
481 model: AccountModel.unscoped(),
486 model: ActorModel.unscoped(),
494 as: 'ActorFollowings',
495 model: ActorFollowModel.unscoped(),
498 targetActorId: actorId
508 return UserModel.unscoped().findAll(query)
511 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
518 return UserModel.findAll(query)
521 static loadById (id: number, withStats = false): Bluebird<MUserDefault> {
523 ScopeNames.WITH_VIDEOCHANNELS
526 if (withStats) scopes.push(ScopeNames.WITH_STATS)
528 return UserModel.scope(scopes).findByPk(id)
531 static loadByUsername (username: string): Bluebird<MUserDefault> {
534 username: { [Op.iLike]: username }
538 return UserModel.findOne(query)
541 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
544 username: { [Op.iLike]: username }
548 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
551 static loadByEmail (email: string): Bluebird<MUserDefault> {
558 return UserModel.findOne(query)
561 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
562 if (!email) email = username
567 where(fn('lower', col('username')), fn('lower', username)),
574 return UserModel.findOne(query)
577 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
582 attributes: [ 'id' ],
583 model: AccountModel.unscoped(),
587 attributes: [ 'id' ],
588 model: VideoChannelModel.unscoped(),
592 attributes: [ 'id' ],
593 model: VideoModel.unscoped(),
605 return UserModel.findOne(query)
608 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
613 attributes: [ 'id' ],
614 model: VideoImportModel.unscoped(),
622 return UserModel.findOne(query)
625 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
630 attributes: [ 'id' ],
631 model: AccountModel.unscoped(),
635 attributes: [ 'id' ],
636 model: VideoChannelModel.unscoped(),
638 actorId: videoChannelActorId
646 return UserModel.findOne(query)
649 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
654 attributes: [ 'id' ],
655 model: AccountModel.unscoped(),
657 actorId: accountActorId
663 return UserModel.findOne(query)
666 static getOriginalVideoFileTotalFromUser (user: MUserId) {
667 // Don't use sequelize because we need to use a sub query
668 const query = UserModel.generateUserQuotaBaseSQL({
670 whereUserId: '$userId'
673 return UserModel.getTotalRawQuery(query, user.id)
676 // Returns cumulative size of all video files uploaded in the last 24 hours.
677 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
678 // Don't use sequelize because we need to use a sub query
679 const query = UserModel.generateUserQuotaBaseSQL({
681 whereUserId: '$userId',
682 where: '"video"."createdAt" > now() - interval \'24 hours\''
685 return UserModel.getTotalRawQuery(query, user.id)
688 static async getStats () {
689 const totalUsers = await UserModel.count()
696 static autoComplete (search: string) {
700 [Op.like]: `%${search}%`
706 return UserModel.findAll(query)
707 .then(u => u.map(u => u.username))
710 canGetVideo (video: MVideoFullLight) {
711 const videoUserId = video.VideoChannel.Account.userId
713 if (video.isBlacklisted()) {
714 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
717 if (video.privacy === VideoPrivacy.PRIVATE) {
718 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
721 if (video.privacy === VideoPrivacy.INTERNAL) return true
726 hasRight (right: UserRight) {
727 return hasUserRight(this.role, right)
730 hasAdminFlag (flag: UserAdminFlag) {
731 return this.adminFlags & flag
734 isPasswordMatch (password: string) {
735 return comparePassword(password, this.password)
738 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
739 const videoQuotaUsed = this.get('videoQuotaUsed')
740 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
741 const videosCount = this.get('videosCount')
742 const [ videoAbusesCount, videoAbusesAcceptedCount ] = (this.get('videoAbusesCount') as string || ':').split(':')
743 const videoAbusesCreatedCount = this.get('videoAbusesCreatedCount')
744 const videoCommentsCount = this.get('videoCommentsCount')
748 username: this.username,
750 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
752 pendingEmail: this.pendingEmail,
753 emailVerified: this.emailVerified,
755 nsfwPolicy: this.nsfwPolicy,
756 webTorrentEnabled: this.webTorrentEnabled,
757 videosHistoryEnabled: this.videosHistoryEnabled,
758 autoPlayVideo: this.autoPlayVideo,
759 autoPlayNextVideo: this.autoPlayNextVideo,
760 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
761 videoLanguages: this.videoLanguages,
764 roleLabel: USER_ROLE_LABELS[this.role],
766 videoQuota: this.videoQuota,
767 videoQuotaDaily: this.videoQuotaDaily,
768 videoQuotaUsed: videoQuotaUsed !== undefined
769 ? parseInt(videoQuotaUsed + '', 10)
771 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
772 ? parseInt(videoQuotaUsedDaily + '', 10)
774 videosCount: videosCount !== undefined
775 ? parseInt(videosCount + '', 10)
777 videoAbusesCount: videoAbusesCount
778 ? parseInt(videoAbusesCount, 10)
780 videoAbusesAcceptedCount: videoAbusesAcceptedCount
781 ? parseInt(videoAbusesAcceptedCount, 10)
783 videoAbusesCreatedCount: videoAbusesCreatedCount !== undefined
784 ? parseInt(videoAbusesCreatedCount + '', 10)
786 videoCommentsCount: videoCommentsCount !== undefined
787 ? parseInt(videoCommentsCount + '', 10)
790 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
791 noWelcomeModal: this.noWelcomeModal,
793 blocked: this.blocked,
794 blockedReason: this.blockedReason,
796 account: this.Account.toFormattedJSON(),
798 notificationSettings: this.NotificationSetting
799 ? this.NotificationSetting.toFormattedJSON()
804 createdAt: this.createdAt
807 if (parameters.withAdminFlags) {
808 Object.assign(json, { adminFlags: this.adminFlags })
811 if (Array.isArray(this.Account.VideoChannels) === true) {
812 json.videoChannels = this.Account.VideoChannels
813 .map(c => c.toFormattedJSON())
815 if (v1.createdAt < v2.createdAt) return -1
816 if (v1.createdAt === v2.createdAt) return 0
825 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
826 const formatted = this.toFormattedJSON()
828 const specialPlaylists = this.Account.VideoPlaylists
829 .map(p => ({ id: p.id, name: p.name, type: p.type }))
831 return Object.assign(formatted, { specialPlaylists })
834 async isAbleToUploadVideo (videoFile: { size: number }) {
835 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
837 const [ totalBytes, totalBytesDaily ] = await Promise.all([
838 UserModel.getOriginalVideoFileTotalFromUser(this),
839 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
842 const uploadedTotal = videoFile.size + totalBytes
843 const uploadedDaily = videoFile.size + totalBytesDaily
845 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
846 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
848 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
851 private static generateUserQuotaBaseSQL (options: {
852 whereUserId: '$userId' | '"UserModel"."id"'
856 const andWhere = options.where
857 ? 'AND ' + options.where
860 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
861 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
862 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
864 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
865 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
868 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
869 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
870 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
873 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
875 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
876 'GROUP BY "t1"."videoId"' +
880 private static getTotalRawQuery (query: string, userId: number) {
883 type: QueryTypes.SELECT as QueryTypes.SELECT
886 return UserModel.sequelize.query<{ total: string }>(query, options)
887 .then(([ { total } ]) => {
888 if (total === null) return 0
890 return parseInt(total, 10)