1 import * as Sequelize from 'sequelize'
19 } from 'sequelize-typescript'
20 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
21 import { User, UserRole } from '../../../shared/models/users'
23 isUserAutoPlayVideoValid,
25 isUserNSFWPolicyValid,
30 } from '../../helpers/custom-validators/users'
31 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
32 import { OAuthTokenModel } from '../oauth/oauth-token'
33 import { getSort, throwIfNotValid } from '../utils'
34 import { VideoChannelModel } from '../video/video-channel'
35 import { AccountModel } from './account'
36 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
37 import { values } from 'lodash'
38 import { NSFW_POLICY_TYPES } from '../../initializers'
41 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
47 model: () => AccountModel,
53 [ScopeNames.WITH_VIDEO_CHANNEL]: {
56 model: () => AccountModel,
58 include: [ () => VideoChannelModel ]
67 fields: [ 'username' ],
76 export class UserModel extends Model<UserModel> {
79 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
84 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
90 @Column(DataType.STRING(400))
94 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
95 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
96 nsfwPolicy: NSFWPolicyType
100 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
102 autoPlayVideo: boolean
106 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
111 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
116 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
117 @Column(DataType.BIGINT)
126 @HasOne(() => AccountModel, {
127 foreignKey: 'userId',
131 Account: AccountModel
133 @HasMany(() => OAuthTokenModel, {
134 foreignKey: 'userId',
137 OAuthTokens: OAuthTokenModel[]
141 static cryptPasswordIfNeeded (instance: UserModel) {
142 if (instance.changed('password')) {
143 return cryptPassword(instance.password)
145 instance.password = hash
151 static countTotal () {
155 static listForApi (start: number, count: number, sort: string) {
162 return UserModel.findAndCountAll(query)
163 .then(({ rows, count }) => {
171 static listEmailsWithRight (right: UserRight) {
172 const roles = Object.keys(USER_ROLE_LABELS)
173 .map(k => parseInt(k, 10) as UserRole)
174 .filter(role => hasUserRight(role, right))
179 attribute: [ 'email' ],
182 [Sequelize.Op.in]: roles
187 return UserModel.unscoped()
189 .then(u => u.map(u => u.email))
192 static loadById (id: number) {
193 return UserModel.findById(id)
196 static loadByUsername (username: string) {
203 return UserModel.findOne(query)
206 static loadByUsernameAndPopulateChannels (username: string) {
213 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
216 static loadByEmail (email: string) {
223 return UserModel.findOne(query)
226 static loadByUsernameOrEmail (username: string, email?: string) {
227 if (!email) email = username
231 [ Sequelize.Op.or ]: [ { username }, { email } ]
235 return UserModel.findOne(query)
238 static getOriginalVideoFileTotalFromUser (user: UserModel) {
239 // Don't use sequelize because we need to use a sub query
240 const query = 'SELECT SUM("size") AS "total" FROM ' +
241 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
242 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
243 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
244 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
245 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
246 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
249 bind: { userId: user.id },
250 type: Sequelize.QueryTypes.SELECT
252 return UserModel.sequelize.query(query, options)
253 .then(([ { total } ]) => {
254 if (total === null) return 0
256 return parseInt(total, 10)
260 static async getStats () {
261 const totalUsers = await UserModel.count()
268 hasRight (right: UserRight) {
269 return hasUserRight(this.role, right)
272 isPasswordMatch (password: string) {
273 return comparePassword(password, this.password)
276 toFormattedJSON (): User {
279 username: this.username,
281 nsfwPolicy: this.nsfwPolicy,
282 autoPlayVideo: this.autoPlayVideo,
284 roleLabel: USER_ROLE_LABELS[ this.role ],
285 videoQuota: this.videoQuota,
286 createdAt: this.createdAt,
287 account: this.Account.toFormattedJSON(),
291 if (Array.isArray(this.Account.VideoChannels) === true) {
292 json.videoChannels = this.Account.VideoChannels
293 .map(c => c.toFormattedJSON())
295 if (v1.createdAt < v2.createdAt) return -1
296 if (v1.createdAt === v2.createdAt) return 0
305 isAbleToUploadVideo (videoFile: { size: number }) {
306 if (this.videoQuota === -1) return Promise.resolve(true)
308 return UserModel.getOriginalVideoFileTotalFromUser(this)
309 .then(totalBytes => {
310 return (videoFile.size + totalBytes) < this.videoQuota