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 } 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
190 'UserAutoPlayNextVideoPlaylist',
191 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
194 autoPlayNextVideoPlaylist: boolean
198 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
199 @Column(DataType.ARRAY(DataType.STRING))
200 videoLanguages: string[]
203 @Default(UserAdminFlag.NONE)
204 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
206 adminFlags?: UserAdminFlag
210 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
216 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
218 blockedReason: string
221 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
226 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
227 @Column(DataType.BIGINT)
231 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
232 @Column(DataType.BIGINT)
233 videoQuotaDaily: number
236 @Default(DEFAULT_THEME_NAME)
237 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
244 'UserNoInstanceConfigWarningModal',
245 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
248 noInstanceConfigWarningModal: boolean
253 'UserNoInstanceConfigWarningModal',
254 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
257 noWelcomeModal: boolean
265 @HasOne(() => AccountModel, {
266 foreignKey: 'userId',
270 Account: AccountModel
272 @HasOne(() => UserNotificationSettingModel, {
273 foreignKey: 'userId',
277 NotificationSetting: UserNotificationSettingModel
279 @HasMany(() => VideoImportModel, {
280 foreignKey: 'userId',
283 VideoImports: VideoImportModel[]
285 @HasMany(() => OAuthTokenModel, {
286 foreignKey: 'userId',
289 OAuthTokens: OAuthTokenModel[]
293 static cryptPasswordIfNeeded (instance: UserModel) {
294 if (instance.changed('password')) {
295 return cryptPassword(instance.password)
297 instance.password = hash
305 static removeTokenCache (instance: UserModel) {
306 return clearCacheByUserId(instance.id)
309 static countTotal () {
313 static listForApi (start: number, count: number, sort: string, search?: string) {
314 let where: WhereOptions
321 [Op.iLike]: '%' + search + '%'
326 [Op.iLike]: '%' + search + '%'
333 const query: FindOptions = {
339 'SELECT COALESCE(SUM("size"), 0) ' +
341 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
342 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
343 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
344 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
345 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
355 order: getSort(sort),
359 return UserModel.findAndCountAll(query)
360 .then(({ rows, count }) => {
368 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
369 const roles = Object.keys(USER_ROLE_LABELS)
370 .map(k => parseInt(k, 10) as UserRole)
371 .filter(role => hasUserRight(role, right))
381 return UserModel.findAll(query)
384 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
388 model: UserNotificationSettingModel.unscoped(),
392 attributes: [ 'userId' ],
393 model: AccountModel.unscoped(),
398 model: ActorModel.unscoped(),
406 as: 'ActorFollowings',
407 model: ActorFollowModel.unscoped(),
410 targetActorId: actorId
420 return UserModel.unscoped().findAll(query)
423 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
430 return UserModel.findAll(query)
433 static loadById (id: number): Bluebird<MUserDefault> {
434 return UserModel.findByPk(id)
437 static loadByUsername (username: string): Bluebird<MUserDefault> {
440 username: { [Op.iLike]: username }
444 return UserModel.findOne(query)
447 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
450 username: { [Op.iLike]: username }
454 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
457 static loadByEmail (email: string): Bluebird<MUserDefault> {
464 return UserModel.findOne(query)
467 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
468 if (!email) email = username
473 where(fn('lower', col('username')), fn('lower', username)),
480 return UserModel.findOne(query)
483 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
488 attributes: [ 'id' ],
489 model: AccountModel.unscoped(),
493 attributes: [ 'id' ],
494 model: VideoChannelModel.unscoped(),
498 attributes: [ 'id' ],
499 model: VideoModel.unscoped(),
511 return UserModel.findOne(query)
514 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
519 attributes: [ 'id' ],
520 model: VideoImportModel.unscoped(),
528 return UserModel.findOne(query)
531 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
536 attributes: [ 'id' ],
537 model: AccountModel.unscoped(),
541 attributes: [ 'id' ],
542 model: VideoChannelModel.unscoped(),
544 actorId: videoChannelActorId
552 return UserModel.findOne(query)
555 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
560 attributes: [ 'id' ],
561 model: AccountModel.unscoped(),
563 actorId: accountActorId
569 return UserModel.findOne(query)
572 static getOriginalVideoFileTotalFromUser (user: MUserId) {
573 // Don't use sequelize because we need to use a sub query
574 const query = UserModel.generateUserQuotaBaseSQL()
576 return UserModel.getTotalRawQuery(query, user.id)
579 // Returns cumulative size of all video files uploaded in the last 24 hours.
580 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
581 // Don't use sequelize because we need to use a sub query
582 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
584 return UserModel.getTotalRawQuery(query, user.id)
587 static async getStats () {
588 const totalUsers = await UserModel.count()
595 static autoComplete (search: string) {
599 [Op.like]: `%${search}%`
605 return UserModel.findAll(query)
606 .then(u => u.map(u => u.username))
609 canGetVideo (video: MVideoFullLight) {
610 const videoUserId = video.VideoChannel.Account.userId
612 if (video.isBlacklisted()) {
613 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
616 if (video.privacy === VideoPrivacy.PRIVATE) {
617 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
620 if (video.privacy === VideoPrivacy.INTERNAL) return true
625 hasRight (right: UserRight) {
626 return hasUserRight(this.role, right)
629 hasAdminFlag (flag: UserAdminFlag) {
630 return this.adminFlags & flag
633 isPasswordMatch (password: string) {
634 return comparePassword(password, this.password)
637 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
638 const videoQuotaUsed = this.get('videoQuotaUsed')
639 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
643 username: this.username,
645 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
647 pendingEmail: this.pendingEmail,
648 emailVerified: this.emailVerified,
650 nsfwPolicy: this.nsfwPolicy,
651 webTorrentEnabled: this.webTorrentEnabled,
652 videosHistoryEnabled: this.videosHistoryEnabled,
653 autoPlayVideo: this.autoPlayVideo,
654 autoPlayNextVideo: this.autoPlayNextVideo,
655 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
656 videoLanguages: this.videoLanguages,
659 roleLabel: USER_ROLE_LABELS[this.role],
661 videoQuota: this.videoQuota,
662 videoQuotaDaily: this.videoQuotaDaily,
663 videoQuotaUsed: videoQuotaUsed !== undefined
664 ? parseInt(videoQuotaUsed + '', 10)
666 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
667 ? parseInt(videoQuotaUsedDaily + '', 10)
670 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
671 noWelcomeModal: this.noWelcomeModal,
673 blocked: this.blocked,
674 blockedReason: this.blockedReason,
676 account: this.Account.toFormattedJSON(),
678 notificationSettings: this.NotificationSetting
679 ? this.NotificationSetting.toFormattedJSON()
684 createdAt: this.createdAt
687 if (parameters.withAdminFlags) {
688 Object.assign(json, { adminFlags: this.adminFlags })
691 if (Array.isArray(this.Account.VideoChannels) === true) {
692 json.videoChannels = this.Account.VideoChannels
693 .map(c => c.toFormattedJSON())
695 if (v1.createdAt < v2.createdAt) return -1
696 if (v1.createdAt === v2.createdAt) return 0
705 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
706 const formatted = this.toFormattedJSON()
708 const specialPlaylists = this.Account.VideoPlaylists
709 .map(p => ({ id: p.id, name: p.name, type: p.type }))
711 return Object.assign(formatted, { specialPlaylists })
714 async isAbleToUploadVideo (videoFile: { size: number }) {
715 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
717 const [ totalBytes, totalBytesDaily ] = await Promise.all([
718 UserModel.getOriginalVideoFileTotalFromUser(this),
719 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
722 const uploadedTotal = videoFile.size + totalBytes
723 const uploadedDaily = videoFile.size + totalBytesDaily
725 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
726 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
728 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
731 private static generateUserQuotaBaseSQL (where?: string) {
732 const andWhere = where ? 'AND ' + where : ''
734 return 'SELECT SUM("size") AS "total" ' +
736 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
737 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
738 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
739 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
740 'WHERE "account"."userId" = $userId ' + andWhere +
741 'GROUP BY "video"."id"' +
745 private static getTotalRawQuery (query: string, userId: number) {
748 type: QueryTypes.SELECT as QueryTypes.SELECT
751 return UserModel.sequelize.query<{ total: string }>(query, options)
752 .then(([ { total } ]) => {
753 if (total === null) return 0
755 return parseInt(total, 10)