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,
24 isUserNSFWPolicyValid,
29 } from '../../helpers/custom-validators/users'
30 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
31 import { OAuthTokenModel } from '../oauth/oauth-token'
32 import { getSort, throwIfNotValid } from '../utils'
33 import { VideoChannelModel } from '../video/video-channel'
34 import { AccountModel } from './account'
35 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
36 import { values } from 'lodash'
37 import { NSFW_POLICY_TYPES } from '../../initializers'
40 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
46 model: () => AccountModel,
52 [ScopeNames.WITH_VIDEO_CHANNEL]: {
55 model: () => AccountModel,
57 include: [ () => VideoChannelModel ]
66 fields: [ 'username' ],
75 export class UserModel extends Model<UserModel> {
78 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
83 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
89 @Column(DataType.STRING(400))
93 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
94 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
95 nsfwPolicy: NSFWPolicyType
99 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
101 autoPlayVideo: boolean
104 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
109 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
110 @Column(DataType.BIGINT)
119 @HasOne(() => AccountModel, {
120 foreignKey: 'userId',
124 Account: AccountModel
126 @HasMany(() => OAuthTokenModel, {
127 foreignKey: 'userId',
130 OAuthTokens: OAuthTokenModel[]
134 static cryptPasswordIfNeeded (instance: UserModel) {
135 if (instance.changed('password')) {
136 return cryptPassword(instance.password)
138 instance.password = hash
144 static countTotal () {
148 static listForApi (start: number, count: number, sort: string) {
155 return UserModel.findAndCountAll(query)
156 .then(({ rows, count }) => {
164 static listEmailsWithRight (right: UserRight) {
165 const roles = Object.keys(USER_ROLE_LABELS)
166 .map(k => parseInt(k, 10) as UserRole)
167 .filter(role => hasUserRight(role, right))
172 attribute: [ 'email' ],
175 [Sequelize.Op.in]: roles
180 return UserModel.unscoped()
182 .then(u => u.map(u => u.email))
185 static loadById (id: number) {
186 return UserModel.findById(id)
189 static loadByUsername (username: string) {
196 return UserModel.findOne(query)
199 static loadByUsernameAndPopulateChannels (username: string) {
206 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
209 static loadByEmail (email: string) {
216 return UserModel.findOne(query)
219 static loadByUsernameOrEmail (username: string, email?: string) {
220 if (!email) email = username
224 [ Sequelize.Op.or ]: [ { username }, { email } ]
228 return UserModel.findOne(query)
231 static getOriginalVideoFileTotalFromUser (user: UserModel) {
232 // Don't use sequelize because we need to use a sub query
233 const query = 'SELECT SUM("size") AS "total" FROM ' +
234 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
235 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
236 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
237 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
238 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
239 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
242 bind: { userId: user.id },
243 type: Sequelize.QueryTypes.SELECT
245 return UserModel.sequelize.query(query, options)
246 .then(([ { total } ]) => {
247 if (total === null) return 0
249 return parseInt(total, 10)
253 static async getStats () {
254 const totalUsers = await UserModel.count()
261 hasRight (right: UserRight) {
262 return hasUserRight(this.role, right)
265 isPasswordMatch (password: string) {
266 return comparePassword(password, this.password)
269 toFormattedJSON (): User {
272 username: this.username,
274 nsfwPolicy: this.nsfwPolicy,
275 autoPlayVideo: this.autoPlayVideo,
277 roleLabel: USER_ROLE_LABELS[ this.role ],
278 videoQuota: this.videoQuota,
279 createdAt: this.createdAt,
280 account: this.Account.toFormattedJSON(),
284 if (Array.isArray(this.Account.VideoChannels) === true) {
285 json.videoChannels = this.Account.VideoChannels
286 .map(c => c.toFormattedJSON())
288 if (v1.createdAt < v2.createdAt) return -1
289 if (v1.createdAt === v2.createdAt) return 0
298 isAbleToUploadVideo (videoFile: { size: number }) {
299 if (this.videoQuota === -1) return Promise.resolve(true)
301 return UserModel.getOriginalVideoFileTotalFromUser(this)
302 .then(totalBytes => {
303 return (videoFile.size + totalBytes) < this.videoQuota