1 import * as Sequelize from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isUserAutoPlayVideoValid,
26 isUserBlockedReasonValid,
28 isUserEmailVerifiedValid,
29 isUserNSFWPolicyValid,
33 isUserVideoQuotaDailyValid,
34 isUserVideoQuotaValid,
35 isUserVideosHistoryEnabledValid,
36 isUserWebTorrentEnabledValid
37 } from '../../helpers/custom-validators/users'
38 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
39 import { OAuthTokenModel } from '../oauth/oauth-token'
40 import { getSort, throwIfNotValid } from '../utils'
41 import { VideoChannelModel } from '../video/video-channel'
42 import { AccountModel } from './account'
43 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
44 import { values } from 'lodash'
45 import { NSFW_POLICY_TYPES } from '../../initializers'
46 import { clearCacheByUserId } from '../../lib/oauth-model'
47 import { UserNotificationSettingModel } from './user-notification-setting'
48 import { VideoModel } from '../video/video'
49 import { ActorModel } from '../activitypub/actor'
50 import { ActorFollowModel } from '../activitypub/actor-follow'
51 import { VideoImportModel } from '../video/video-import'
54 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
60 model: () => AccountModel,
64 model: () => UserNotificationSettingModel,
70 [ScopeNames.WITH_VIDEO_CHANNEL]: {
73 model: () => AccountModel,
75 include: [ () => VideoChannelModel ]
78 model: () => UserNotificationSettingModel,
88 fields: [ 'username' ],
97 export class UserModel extends Model<UserModel> {
100 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
105 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
111 @Column(DataType.STRING(400))
116 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
118 emailVerified: boolean
121 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
122 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
123 nsfwPolicy: NSFWPolicyType
127 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
129 webTorrentEnabled: boolean
133 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
135 videosHistoryEnabled: boolean
139 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
141 autoPlayVideo: boolean
145 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
151 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
153 blockedReason: string
156 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
161 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
162 @Column(DataType.BIGINT)
166 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
167 @Column(DataType.BIGINT)
168 videoQuotaDaily: number
176 @HasOne(() => AccountModel, {
177 foreignKey: 'userId',
181 Account: AccountModel
183 @HasOne(() => UserNotificationSettingModel, {
184 foreignKey: 'userId',
188 NotificationSetting: UserNotificationSettingModel
190 @HasMany(() => VideoImportModel, {
191 foreignKey: 'userId',
194 VideoImports: VideoImportModel[]
196 @HasMany(() => OAuthTokenModel, {
197 foreignKey: 'userId',
200 OAuthTokens: OAuthTokenModel[]
204 static cryptPasswordIfNeeded (instance: UserModel) {
205 if (instance.changed('password')) {
206 return cryptPassword(instance.password)
208 instance.password = hash
216 static removeTokenCache (instance: UserModel) {
217 return clearCacheByUserId(instance.id)
220 static countTotal () {
224 static listForApi (start: number, count: number, sort: string, search?: string) {
225 let where = undefined
231 [Sequelize.Op.iLike]: '%' + search + '%'
236 [ Sequelize.Op.iLike ]: '%' + search + '%'
249 'SELECT COALESCE(SUM("size"), 0) ' +
251 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
252 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
253 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
254 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
255 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
260 ] as any // FIXME: typings
265 order: getSort(sort),
269 return UserModel.findAndCountAll(query)
270 .then(({ rows, count }) => {
278 static listWithRight (right: UserRight) {
279 const roles = Object.keys(USER_ROLE_LABELS)
280 .map(k => parseInt(k, 10) as UserRole)
281 .filter(role => hasUserRight(role, right))
286 [Sequelize.Op.in]: roles
291 return UserModel.findAll(query)
294 static listUserSubscribersOf (actorId: number) {
298 model: UserNotificationSettingModel.unscoped(),
302 attributes: [ 'userId' ],
303 model: AccountModel.unscoped(),
308 model: ActorModel.unscoped(),
316 as: 'ActorFollowings',
317 model: ActorFollowModel.unscoped(),
320 targetActorId: actorId
330 return UserModel.unscoped().findAll(query)
333 static loadById (id: number) {
334 return UserModel.findById(id)
337 static loadByUsername (username: string) {
344 return UserModel.findOne(query)
347 static loadByUsernameAndPopulateChannels (username: string) {
354 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
357 static loadByEmail (email: string) {
364 return UserModel.findOne(query)
367 static loadByUsernameOrEmail (username: string, email?: string) {
368 if (!email) email = username
372 [ Sequelize.Op.or ]: [ { username }, { email } ]
376 return UserModel.findOne(query)
379 static loadByVideoId (videoId: number) {
384 attributes: [ 'id' ],
385 model: AccountModel.unscoped(),
389 attributes: [ 'id' ],
390 model: VideoChannelModel.unscoped(),
394 attributes: [ 'id' ],
395 model: VideoModel.unscoped(),
407 return UserModel.findOne(query)
410 static loadByVideoImportId (videoImportId: number) {
415 attributes: [ 'id' ],
416 model: VideoImportModel.unscoped(),
424 return UserModel.findOne(query)
427 static getOriginalVideoFileTotalFromUser (user: UserModel) {
428 // Don't use sequelize because we need to use a sub query
429 const query = UserModel.generateUserQuotaBaseSQL()
431 return UserModel.getTotalRawQuery(query, user.id)
434 // Returns cumulative size of all video files uploaded in the last 24 hours.
435 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
436 // Don't use sequelize because we need to use a sub query
437 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
439 return UserModel.getTotalRawQuery(query, user.id)
442 static async getStats () {
443 const totalUsers = await UserModel.count()
450 static autoComplete (search: string) {
454 [ Sequelize.Op.like ]: `%${search}%`
460 return UserModel.findAll(query)
461 .then(u => u.map(u => u.username))
464 hasRight (right: UserRight) {
465 return hasUserRight(this.role, right)
468 isPasswordMatch (password: string) {
469 return comparePassword(password, this.password)
472 toFormattedJSON (): User {
473 const videoQuotaUsed = this.get('videoQuotaUsed')
474 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
478 username: this.username,
480 emailVerified: this.emailVerified,
481 nsfwPolicy: this.nsfwPolicy,
482 webTorrentEnabled: this.webTorrentEnabled,
483 videosHistoryEnabled: this.videosHistoryEnabled,
484 autoPlayVideo: this.autoPlayVideo,
486 roleLabel: USER_ROLE_LABELS[ this.role ],
487 videoQuota: this.videoQuota,
488 videoQuotaDaily: this.videoQuotaDaily,
489 createdAt: this.createdAt,
490 blocked: this.blocked,
491 blockedReason: this.blockedReason,
492 account: this.Account.toFormattedJSON(),
493 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
495 videoQuotaUsed: videoQuotaUsed !== undefined
496 ? parseInt(videoQuotaUsed, 10)
498 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
499 ? parseInt(videoQuotaUsedDaily, 10)
503 if (Array.isArray(this.Account.VideoChannels) === true) {
504 json.videoChannels = this.Account.VideoChannels
505 .map(c => c.toFormattedJSON())
507 if (v1.createdAt < v2.createdAt) return -1
508 if (v1.createdAt === v2.createdAt) return 0
517 async isAbleToUploadVideo (videoFile: { size: number }) {
518 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
520 const [ totalBytes, totalBytesDaily ] = await Promise.all([
521 UserModel.getOriginalVideoFileTotalFromUser(this),
522 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
525 const uploadedTotal = videoFile.size + totalBytes
526 const uploadedDaily = videoFile.size + totalBytesDaily
527 if (this.videoQuotaDaily === -1) {
528 return uploadedTotal < this.videoQuota
530 if (this.videoQuota === -1) {
531 return uploadedDaily < this.videoQuotaDaily
534 return (uploadedTotal < this.videoQuota) &&
535 (uploadedDaily < this.videoQuotaDaily)
538 private static generateUserQuotaBaseSQL (where?: string) {
539 const andWhere = where ? 'AND ' + where : ''
541 return 'SELECT SUM("size") AS "total" ' +
543 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
544 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
545 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
546 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
547 'WHERE "account"."userId" = $userId ' + andWhere +
548 'GROUP BY "video"."id"' +
552 private static getTotalRawQuery (query: string, userId: number) {
555 type: Sequelize.QueryTypes.SELECT
558 return UserModel.sequelize.query(query, options)
559 .then(([ { total } ]) => {
560 if (total === null) return 0
562 return parseInt(total, 10)