1 import { FindOptions, literal, Op, QueryTypes } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isUserAdminFlagsValid,
26 isUserAutoPlayVideoValid,
27 isUserBlockedReasonValid,
29 isUserEmailVerifiedValid,
30 isUserNSFWPolicyValid,
35 isUserVideoQuotaDailyValid,
36 isUserVideoQuotaValid,
37 isUserVideosHistoryEnabledValid,
38 isUserWebTorrentEnabledValid
39 } from '../../helpers/custom-validators/users'
40 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
41 import { OAuthTokenModel } from '../oauth/oauth-token'
42 import { getSort, throwIfNotValid } from '../utils'
43 import { VideoChannelModel } from '../video/video-channel'
44 import { AccountModel } from './account'
45 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
46 import { values } from 'lodash'
47 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
48 import { clearCacheByUserId } from '../../lib/oauth-model'
49 import { UserNotificationSettingModel } from './user-notification-setting'
50 import { VideoModel } from '../video/video'
51 import { ActorModel } from '../activitypub/actor'
52 import { ActorFollowModel } from '../activitypub/actor-follow'
53 import { VideoImportModel } from '../video/video-import'
54 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
55 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
56 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
57 import * as Bluebird from 'bluebird'
58 import { MUserChannel, MUserDefault, MUserId, MUserWithNotificationSetting } from '@server/typings/models'
61 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
64 @DefaultScope(() => ({
71 model: UserNotificationSettingModel,
77 [ScopeNames.WITH_VIDEO_CHANNEL]: {
82 include: [ VideoChannelModel ]
85 model: UserNotificationSettingModel,
95 fields: [ 'username' ],
104 export class UserModel extends Model<UserModel> {
107 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
112 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
118 @Column(DataType.STRING(400))
123 @Column(DataType.STRING(400))
128 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
130 emailVerified: boolean
133 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
134 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
135 nsfwPolicy: NSFWPolicyType
139 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
141 webTorrentEnabled: boolean
145 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
147 videosHistoryEnabled: boolean
151 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
153 autoPlayVideo: boolean
157 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
158 @Column(DataType.ARRAY(DataType.STRING))
159 videoLanguages: string[]
162 @Default(UserAdminFlag.NONE)
163 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
165 adminFlags?: UserAdminFlag
169 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
175 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
177 blockedReason: string
180 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
185 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
186 @Column(DataType.BIGINT)
190 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
191 @Column(DataType.BIGINT)
192 videoQuotaDaily: number
195 @Default(DEFAULT_THEME_NAME)
196 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
206 @HasOne(() => AccountModel, {
207 foreignKey: 'userId',
211 Account: AccountModel
213 @HasOne(() => UserNotificationSettingModel, {
214 foreignKey: 'userId',
218 NotificationSetting: UserNotificationSettingModel
220 @HasMany(() => VideoImportModel, {
221 foreignKey: 'userId',
224 VideoImports: VideoImportModel[]
226 @HasMany(() => OAuthTokenModel, {
227 foreignKey: 'userId',
230 OAuthTokens: OAuthTokenModel[]
234 static cryptPasswordIfNeeded (instance: UserModel) {
235 if (instance.changed('password')) {
236 return cryptPassword(instance.password)
238 instance.password = hash
246 static removeTokenCache (instance: UserModel) {
247 return clearCacheByUserId(instance.id)
250 static countTotal () {
254 static listForApi (start: number, count: number, sort: string, search?: string) {
255 let where = undefined
261 [Op.iLike]: '%' + search + '%'
266 [ Op.iLike ]: '%' + search + '%'
273 const query: FindOptions = {
279 'SELECT COALESCE(SUM("size"), 0) ' +
281 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
282 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
283 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
284 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
285 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
295 order: getSort(sort),
299 return UserModel.findAndCountAll(query)
300 .then(({ rows, count }) => {
308 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
309 const roles = Object.keys(USER_ROLE_LABELS)
310 .map(k => parseInt(k, 10) as UserRole)
311 .filter(role => hasUserRight(role, right))
321 return UserModel.findAll(query)
324 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
328 model: UserNotificationSettingModel.unscoped(),
332 attributes: [ 'userId' ],
333 model: AccountModel.unscoped(),
338 model: ActorModel.unscoped(),
346 as: 'ActorFollowings',
347 model: ActorFollowModel.unscoped(),
350 targetActorId: actorId
360 return UserModel.unscoped().findAll(query)
363 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
370 return UserModel.findAll(query)
373 static loadById (id: number): Bluebird<MUserDefault> {
374 return UserModel.findByPk(id)
377 static loadByUsername (username: string): Bluebird<MUserDefault> {
380 username: { [ Op.iLike ]: username }
384 return UserModel.findOne(query)
387 static loadByUsernameAndPopulateChannels (username: string): Bluebird<MUserChannel> {
390 username: { [ Op.iLike ]: username }
394 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
397 static loadByEmail (email: string): Bluebird<MUserDefault> {
404 return UserModel.findOne(query)
407 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
408 if (!email) email = username
412 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
416 return UserModel.findOne(query)
419 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
424 attributes: [ 'id' ],
425 model: AccountModel.unscoped(),
429 attributes: [ 'id' ],
430 model: VideoChannelModel.unscoped(),
434 attributes: [ 'id' ],
435 model: VideoModel.unscoped(),
447 return UserModel.findOne(query)
450 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
455 attributes: [ 'id' ],
456 model: VideoImportModel.unscoped(),
464 return UserModel.findOne(query)
467 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
472 attributes: [ 'id' ],
473 model: AccountModel.unscoped(),
477 attributes: [ 'id' ],
478 model: VideoChannelModel.unscoped(),
480 actorId: videoChannelActorId
488 return UserModel.findOne(query)
491 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
496 attributes: [ 'id' ],
497 model: AccountModel.unscoped(),
499 actorId: accountActorId
505 return UserModel.findOne(query)
508 static getOriginalVideoFileTotalFromUser (user: MUserId) {
509 // Don't use sequelize because we need to use a sub query
510 const query = UserModel.generateUserQuotaBaseSQL()
512 return UserModel.getTotalRawQuery(query, user.id)
515 // Returns cumulative size of all video files uploaded in the last 24 hours.
516 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
517 // Don't use sequelize because we need to use a sub query
518 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
520 return UserModel.getTotalRawQuery(query, user.id)
523 static async getStats () {
524 const totalUsers = await UserModel.count()
531 static autoComplete (search: string) {
535 [ Op.like ]: `%${search}%`
541 return UserModel.findAll(query)
542 .then(u => u.map(u => u.username))
545 hasRight (right: UserRight) {
546 return hasUserRight(this.role, right)
549 hasAdminFlag (flag: UserAdminFlag) {
550 return this.adminFlags & flag
553 isPasswordMatch (password: string) {
554 return comparePassword(password, this.password)
557 toFormattedJSON (parameters: { withAdminFlags?: boolean } = {}): User {
558 const videoQuotaUsed = this.get('videoQuotaUsed')
559 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
563 username: this.username,
565 pendingEmail: this.pendingEmail,
566 emailVerified: this.emailVerified,
567 nsfwPolicy: this.nsfwPolicy,
568 webTorrentEnabled: this.webTorrentEnabled,
569 videosHistoryEnabled: this.videosHistoryEnabled,
570 autoPlayVideo: this.autoPlayVideo,
571 videoLanguages: this.videoLanguages,
573 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
574 roleLabel: USER_ROLE_LABELS[ this.role ],
575 videoQuota: this.videoQuota,
576 videoQuotaDaily: this.videoQuotaDaily,
577 createdAt: this.createdAt,
578 blocked: this.blocked,
579 blockedReason: this.blockedReason,
580 account: this.Account.toFormattedJSON(),
581 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
583 videoQuotaUsed: videoQuotaUsed !== undefined
584 ? parseInt(videoQuotaUsed + '', 10)
586 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
587 ? parseInt(videoQuotaUsedDaily + '', 10)
591 if (parameters.withAdminFlags) {
592 Object.assign(json, { adminFlags: this.adminFlags })
595 if (Array.isArray(this.Account.VideoChannels) === true) {
596 json.videoChannels = this.Account.VideoChannels
597 .map(c => c.toFormattedJSON())
599 if (v1.createdAt < v2.createdAt) return -1
600 if (v1.createdAt === v2.createdAt) return 0
609 async isAbleToUploadVideo (videoFile: { size: number }) {
610 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
612 const [ totalBytes, totalBytesDaily ] = await Promise.all([
613 UserModel.getOriginalVideoFileTotalFromUser(this),
614 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
617 const uploadedTotal = videoFile.size + totalBytes
618 const uploadedDaily = videoFile.size + totalBytesDaily
620 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
621 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
623 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
626 private static generateUserQuotaBaseSQL (where?: string) {
627 const andWhere = where ? 'AND ' + where : ''
629 return 'SELECT SUM("size") AS "total" ' +
631 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
632 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
633 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
634 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
635 'WHERE "account"."userId" = $userId ' + andWhere +
636 'GROUP BY "video"."id"' +
640 private static getTotalRawQuery (query: string, userId: number) {
643 type: QueryTypes.SELECT as QueryTypes.SELECT
646 return UserModel.sequelize.query<{ total: string }>(query, options)
647 .then(([ { total } ]) => {
648 if (total === null) return 0
650 return parseInt(total, 10)