1 import { FindOptions, literal, Op, QueryTypes, where, fn, col } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, 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_THEME_NAME, 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'
77 @DefaultScope(() => ({
84 model: UserNotificationSettingModel,
90 [ScopeNames.FOR_ME_API]: {
96 model: VideoChannelModel
99 attributes: [ 'id', 'name', 'type' ],
100 model: VideoPlaylistModel.unscoped(),
104 [ Op.ne ]: VideoPlaylistType.REGULAR
111 model: UserNotificationSettingModel,
121 fields: [ 'username' ],
130 export class UserModel extends Model<UserModel> {
133 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
138 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
144 @Column(DataType.STRING(400))
149 @Column(DataType.STRING(400))
154 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
156 emailVerified: boolean
159 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
160 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
161 nsfwPolicy: NSFWPolicyType
165 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
167 webTorrentEnabled: boolean
171 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
173 videosHistoryEnabled: boolean
177 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
179 autoPlayVideo: boolean
183 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
185 autoPlayNextVideo: boolean
189 @Is('UserAutoPlayNextVideoPlaylist', value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean'))
191 autoPlayNextVideoPlaylist: boolean
195 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
196 @Column(DataType.ARRAY(DataType.STRING))
197 videoLanguages: string[]
200 @Default(UserAdminFlag.NONE)
201 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
203 adminFlags?: UserAdminFlag
207 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
213 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
215 blockedReason: string
218 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
223 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
224 @Column(DataType.BIGINT)
228 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
229 @Column(DataType.BIGINT)
230 videoQuotaDaily: number
233 @Default(DEFAULT_THEME_NAME)
234 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
241 'UserNoInstanceConfigWarningModal',
242 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
245 noInstanceConfigWarningModal: boolean
250 'UserNoInstanceConfigWarningModal',
251 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
254 noWelcomeModal: boolean
262 @HasOne(() => AccountModel, {
263 foreignKey: 'userId',
267 Account: AccountModel
269 @HasOne(() => UserNotificationSettingModel, {
270 foreignKey: 'userId',
274 NotificationSetting: UserNotificationSettingModel
276 @HasMany(() => VideoImportModel, {
277 foreignKey: 'userId',
280 VideoImports: VideoImportModel[]
282 @HasMany(() => OAuthTokenModel, {
283 foreignKey: 'userId',
286 OAuthTokens: OAuthTokenModel[]
290 static cryptPasswordIfNeeded (instance: UserModel) {
291 if (instance.changed('password')) {
292 return cryptPassword(instance.password)
294 instance.password = hash
302 static removeTokenCache (instance: UserModel) {
303 return clearCacheByUserId(instance.id)
306 static countTotal () {
310 static listForApi (start: number, count: number, sort: string, search?: string) {
311 let where = undefined
317 [Op.iLike]: '%' + search + '%'
322 [ Op.iLike ]: '%' + search + '%'
329 const query: FindOptions = {
335 'SELECT COALESCE(SUM("size"), 0) ' +
337 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
338 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
339 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
340 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
341 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
351 order: getSort(sort),
355 return UserModel.findAndCountAll(query)
356 .then(({ rows, count }) => {
364 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
365 const roles = Object.keys(USER_ROLE_LABELS)
366 .map(k => parseInt(k, 10) as UserRole)
367 .filter(role => hasUserRight(role, right))
377 return UserModel.findAll(query)
380 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
384 model: UserNotificationSettingModel.unscoped(),
388 attributes: [ 'userId' ],
389 model: AccountModel.unscoped(),
394 model: ActorModel.unscoped(),
402 as: 'ActorFollowings',
403 model: ActorFollowModel.unscoped(),
406 targetActorId: actorId
416 return UserModel.unscoped().findAll(query)
419 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
426 return UserModel.findAll(query)
429 static loadById (id: number): Bluebird<MUserDefault> {
430 return UserModel.findByPk(id)
433 static loadByUsername (username: string): Bluebird<MUserDefault> {
436 username: { [ Op.iLike ]: username }
440 return UserModel.findOne(query)
443 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
446 username: { [ Op.iLike ]: username }
450 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
453 static loadByEmail (email: string): Bluebird<MUserDefault> {
460 return UserModel.findOne(query)
463 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
464 if (!email) email = username
469 where(fn('lower', col('username')), fn('lower', username)),
476 return UserModel.findOne(query)
479 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
484 attributes: [ 'id' ],
485 model: AccountModel.unscoped(),
489 attributes: [ 'id' ],
490 model: VideoChannelModel.unscoped(),
494 attributes: [ 'id' ],
495 model: VideoModel.unscoped(),
507 return UserModel.findOne(query)
510 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
515 attributes: [ 'id' ],
516 model: VideoImportModel.unscoped(),
524 return UserModel.findOne(query)
527 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
532 attributes: [ 'id' ],
533 model: AccountModel.unscoped(),
537 attributes: [ 'id' ],
538 model: VideoChannelModel.unscoped(),
540 actorId: videoChannelActorId
548 return UserModel.findOne(query)
551 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
556 attributes: [ 'id' ],
557 model: AccountModel.unscoped(),
559 actorId: accountActorId
565 return UserModel.findOne(query)
568 static getOriginalVideoFileTotalFromUser (user: MUserId) {
569 // Don't use sequelize because we need to use a sub query
570 const query = UserModel.generateUserQuotaBaseSQL()
572 return UserModel.getTotalRawQuery(query, user.id)
575 // Returns cumulative size of all video files uploaded in the last 24 hours.
576 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
577 // Don't use sequelize because we need to use a sub query
578 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
580 return UserModel.getTotalRawQuery(query, user.id)
583 static async getStats () {
584 const totalUsers = await UserModel.count()
591 static autoComplete (search: string) {
595 [ Op.like ]: `%${search}%`
601 return UserModel.findAll(query)
602 .then(u => u.map(u => u.username))
605 canGetVideo (video: MVideoFullLight) {
606 const videoUserId = video.VideoChannel.Account.userId
608 if (video.isBlacklisted()) {
609 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
612 if (video.privacy === VideoPrivacy.PRIVATE) {
613 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
616 if (video.privacy === VideoPrivacy.INTERNAL) return true
621 hasRight (right: UserRight) {
622 return hasUserRight(this.role, right)
625 hasAdminFlag (flag: UserAdminFlag) {
626 return this.adminFlags & flag
629 isPasswordMatch (password: string) {
630 return comparePassword(password, this.password)
633 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
634 const videoQuotaUsed = this.get('videoQuotaUsed')
635 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
639 username: this.username,
641 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
643 pendingEmail: this.pendingEmail,
644 emailVerified: this.emailVerified,
646 nsfwPolicy: this.nsfwPolicy,
647 webTorrentEnabled: this.webTorrentEnabled,
648 videosHistoryEnabled: this.videosHistoryEnabled,
649 autoPlayVideo: this.autoPlayVideo,
650 autoPlayNextVideo: this.autoPlayNextVideo,
651 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
652 videoLanguages: this.videoLanguages,
655 roleLabel: USER_ROLE_LABELS[ this.role ],
657 videoQuota: this.videoQuota,
658 videoQuotaDaily: this.videoQuotaDaily,
659 videoQuotaUsed: videoQuotaUsed !== undefined
660 ? parseInt(videoQuotaUsed + '', 10)
662 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
663 ? parseInt(videoQuotaUsedDaily + '', 10)
666 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
667 noWelcomeModal: this.noWelcomeModal,
669 blocked: this.blocked,
670 blockedReason: this.blockedReason,
672 account: this.Account.toFormattedJSON(),
674 notificationSettings: this.NotificationSetting
675 ? this.NotificationSetting.toFormattedJSON()
680 createdAt: this.createdAt
683 if (parameters.withAdminFlags) {
684 Object.assign(json, { adminFlags: this.adminFlags })
687 if (Array.isArray(this.Account.VideoChannels) === true) {
688 json.videoChannels = this.Account.VideoChannels
689 .map(c => c.toFormattedJSON())
691 if (v1.createdAt < v2.createdAt) return -1
692 if (v1.createdAt === v2.createdAt) return 0
701 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
702 const formatted = this.toFormattedJSON()
704 const specialPlaylists = this.Account.VideoPlaylists
705 .map(p => ({ id: p.id, name: p.name, type: p.type }))
707 return Object.assign(formatted, { specialPlaylists })
710 async isAbleToUploadVideo (videoFile: { size: number }) {
711 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
713 const [ totalBytes, totalBytesDaily ] = await Promise.all([
714 UserModel.getOriginalVideoFileTotalFromUser(this),
715 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
718 const uploadedTotal = videoFile.size + totalBytes
719 const uploadedDaily = videoFile.size + totalBytesDaily
721 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
722 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
724 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
727 private static generateUserQuotaBaseSQL (where?: string) {
728 const andWhere = where ? 'AND ' + where : ''
730 return 'SELECT SUM("size") AS "total" ' +
732 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
733 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
734 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
735 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
736 'WHERE "account"."userId" = $userId ' + andWhere +
737 'GROUP BY "video"."id"' +
741 private static getTotalRawQuery (query: string, userId: number) {
744 type: QueryTypes.SELECT as QueryTypes.SELECT
747 return UserModel.sequelize.query<{ total: string }>(query, options)
748 .then(([ { total } ]) => {
749 if (total === null) return 0
751 return parseInt(total, 10)