1 import { FindOptions, literal, Op, QueryTypes } 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
468 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
472 return UserModel.findOne(query)
475 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
480 attributes: [ 'id' ],
481 model: AccountModel.unscoped(),
485 attributes: [ 'id' ],
486 model: VideoChannelModel.unscoped(),
490 attributes: [ 'id' ],
491 model: VideoModel.unscoped(),
503 return UserModel.findOne(query)
506 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
511 attributes: [ 'id' ],
512 model: VideoImportModel.unscoped(),
520 return UserModel.findOne(query)
523 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
528 attributes: [ 'id' ],
529 model: AccountModel.unscoped(),
533 attributes: [ 'id' ],
534 model: VideoChannelModel.unscoped(),
536 actorId: videoChannelActorId
544 return UserModel.findOne(query)
547 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
552 attributes: [ 'id' ],
553 model: AccountModel.unscoped(),
555 actorId: accountActorId
561 return UserModel.findOne(query)
564 static getOriginalVideoFileTotalFromUser (user: MUserId) {
565 // Don't use sequelize because we need to use a sub query
566 const query = UserModel.generateUserQuotaBaseSQL()
568 return UserModel.getTotalRawQuery(query, user.id)
571 // Returns cumulative size of all video files uploaded in the last 24 hours.
572 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
573 // Don't use sequelize because we need to use a sub query
574 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
576 return UserModel.getTotalRawQuery(query, user.id)
579 static async getStats () {
580 const totalUsers = await UserModel.count()
587 static autoComplete (search: string) {
591 [ Op.like ]: `%${search}%`
597 return UserModel.findAll(query)
598 .then(u => u.map(u => u.username))
601 canGetVideo (video: MVideoFullLight) {
602 const videoUserId = video.VideoChannel.Account.userId
604 if (video.isBlacklisted()) {
605 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
608 if (video.privacy === VideoPrivacy.PRIVATE) {
609 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
612 if (video.privacy === VideoPrivacy.INTERNAL) return true
617 hasRight (right: UserRight) {
618 return hasUserRight(this.role, right)
621 hasAdminFlag (flag: UserAdminFlag) {
622 return this.adminFlags & flag
625 isPasswordMatch (password: string) {
626 return comparePassword(password, this.password)
629 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
630 const videoQuotaUsed = this.get('videoQuotaUsed')
631 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
635 username: this.username,
637 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
639 pendingEmail: this.pendingEmail,
640 emailVerified: this.emailVerified,
642 nsfwPolicy: this.nsfwPolicy,
643 webTorrentEnabled: this.webTorrentEnabled,
644 videosHistoryEnabled: this.videosHistoryEnabled,
645 autoPlayVideo: this.autoPlayVideo,
646 autoPlayNextVideo: this.autoPlayNextVideo,
647 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
648 videoLanguages: this.videoLanguages,
651 roleLabel: USER_ROLE_LABELS[ this.role ],
653 videoQuota: this.videoQuota,
654 videoQuotaDaily: this.videoQuotaDaily,
655 videoQuotaUsed: videoQuotaUsed !== undefined
656 ? parseInt(videoQuotaUsed + '', 10)
658 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
659 ? parseInt(videoQuotaUsedDaily + '', 10)
662 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
663 noWelcomeModal: this.noWelcomeModal,
665 blocked: this.blocked,
666 blockedReason: this.blockedReason,
668 account: this.Account.toFormattedJSON(),
670 notificationSettings: this.NotificationSetting
671 ? this.NotificationSetting.toFormattedJSON()
676 createdAt: this.createdAt
679 if (parameters.withAdminFlags) {
680 Object.assign(json, { adminFlags: this.adminFlags })
683 if (Array.isArray(this.Account.VideoChannels) === true) {
684 json.videoChannels = this.Account.VideoChannels
685 .map(c => c.toFormattedJSON())
687 if (v1.createdAt < v2.createdAt) return -1
688 if (v1.createdAt === v2.createdAt) return 0
697 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
698 const formatted = this.toFormattedJSON()
700 const specialPlaylists = this.Account.VideoPlaylists
701 .map(p => ({ id: p.id, name: p.name, type: p.type }))
703 return Object.assign(formatted, { specialPlaylists })
706 async isAbleToUploadVideo (videoFile: { size: number }) {
707 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
709 const [ totalBytes, totalBytesDaily ] = await Promise.all([
710 UserModel.getOriginalVideoFileTotalFromUser(this),
711 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
714 const uploadedTotal = videoFile.size + totalBytes
715 const uploadedDaily = videoFile.size + totalBytesDaily
717 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
718 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
720 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
723 private static generateUserQuotaBaseSQL (where?: string) {
724 const andWhere = where ? 'AND ' + where : ''
726 return 'SELECT SUM("size") AS "total" ' +
728 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
729 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
730 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
731 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
732 'WHERE "account"."userId" = $userId ' + andWhere +
733 'GROUP BY "video"."id"' +
737 private static getTotalRawQuery (query: string, userId: number) {
740 type: QueryTypes.SELECT as QueryTypes.SELECT
743 return UserModel.sequelize.query<{ total: string }>(query, options)
744 .then(([ { total } ]) => {
745 if (total === null) return 0
747 return parseInt(total, 10)