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 listByUsernames (usernames: string[]) {
340 return UserModel.findAll(query)
343 static loadById (id: number) {
344 return UserModel.findByPk(id)
347 static loadByUsername (username: string) {
354 return UserModel.findOne(query)
357 static loadByUsernameAndPopulateChannels (username: string) {
364 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
367 static loadByEmail (email: string) {
374 return UserModel.findOne(query)
377 static loadByUsernameOrEmail (username: string, email?: string) {
378 if (!email) email = username
382 [ Sequelize.Op.or ]: [ { username }, { email } ]
386 return UserModel.findOne(query)
389 static loadByVideoId (videoId: number) {
394 attributes: [ 'id' ],
395 model: AccountModel.unscoped(),
399 attributes: [ 'id' ],
400 model: VideoChannelModel.unscoped(),
404 attributes: [ 'id' ],
405 model: VideoModel.unscoped(),
417 return UserModel.findOne(query)
420 static loadByVideoImportId (videoImportId: number) {
425 attributes: [ 'id' ],
426 model: VideoImportModel.unscoped(),
434 return UserModel.findOne(query)
437 static loadByChannelActorId (videoChannelActorId: number) {
442 attributes: [ 'id' ],
443 model: AccountModel.unscoped(),
447 attributes: [ 'id' ],
448 model: VideoChannelModel.unscoped(),
450 actorId: videoChannelActorId
458 return UserModel.findOne(query)
461 static loadByAccountActorId (accountActorId: number) {
466 attributes: [ 'id' ],
467 model: AccountModel.unscoped(),
469 actorId: accountActorId
475 return UserModel.findOne(query)
478 static getOriginalVideoFileTotalFromUser (user: UserModel) {
479 // Don't use sequelize because we need to use a sub query
480 const query = UserModel.generateUserQuotaBaseSQL()
482 return UserModel.getTotalRawQuery(query, user.id)
485 // Returns cumulative size of all video files uploaded in the last 24 hours.
486 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
487 // Don't use sequelize because we need to use a sub query
488 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
490 return UserModel.getTotalRawQuery(query, user.id)
493 static async getStats () {
494 const totalUsers = await UserModel.count()
501 static autoComplete (search: string) {
505 [ Sequelize.Op.like ]: `%${search}%`
511 return UserModel.findAll(query)
512 .then(u => u.map(u => u.username))
515 hasRight (right: UserRight) {
516 return hasUserRight(this.role, right)
519 isPasswordMatch (password: string) {
520 return comparePassword(password, this.password)
523 toFormattedJSON (): User {
524 const videoQuotaUsed = this.get('videoQuotaUsed')
525 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
529 username: this.username,
531 emailVerified: this.emailVerified,
532 nsfwPolicy: this.nsfwPolicy,
533 webTorrentEnabled: this.webTorrentEnabled,
534 videosHistoryEnabled: this.videosHistoryEnabled,
535 autoPlayVideo: this.autoPlayVideo,
537 roleLabel: USER_ROLE_LABELS[ this.role ],
538 videoQuota: this.videoQuota,
539 videoQuotaDaily: this.videoQuotaDaily,
540 createdAt: this.createdAt,
541 blocked: this.blocked,
542 blockedReason: this.blockedReason,
543 account: this.Account.toFormattedJSON(),
544 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
546 videoQuotaUsed: videoQuotaUsed !== undefined
547 ? parseInt(videoQuotaUsed, 10)
549 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
550 ? parseInt(videoQuotaUsedDaily, 10)
554 if (Array.isArray(this.Account.VideoChannels) === true) {
555 json.videoChannels = this.Account.VideoChannels
556 .map(c => c.toFormattedJSON())
558 if (v1.createdAt < v2.createdAt) return -1
559 if (v1.createdAt === v2.createdAt) return 0
568 async isAbleToUploadVideo (videoFile: { size: number }) {
569 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
571 const [ totalBytes, totalBytesDaily ] = await Promise.all([
572 UserModel.getOriginalVideoFileTotalFromUser(this),
573 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
576 const uploadedTotal = videoFile.size + totalBytes
577 const uploadedDaily = videoFile.size + totalBytesDaily
578 if (this.videoQuotaDaily === -1) {
579 return uploadedTotal < this.videoQuota
581 if (this.videoQuota === -1) {
582 return uploadedDaily < this.videoQuotaDaily
585 return (uploadedTotal < this.videoQuota) &&
586 (uploadedDaily < this.videoQuotaDaily)
589 private static generateUserQuotaBaseSQL (where?: string) {
590 const andWhere = where ? 'AND ' + where : ''
592 return 'SELECT SUM("size") AS "total" ' +
594 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
595 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
596 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
597 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
598 'WHERE "account"."userId" = $userId ' + andWhere +
599 'GROUP BY "video"."id"' +
603 private static getTotalRawQuery (query: string, userId: number) {
606 type: Sequelize.QueryTypes.SELECT
609 return UserModel.sequelize.query(query, options)
610 .then(([ { total } ]) => {
611 if (total === null) return 0
613 return parseInt(total, 10)