1 import * as Sequelize from 'sequelize'
3 AllowNull, BeforeCreate, BeforeUpdate, Column, CreatedAt, DataType, Default, DefaultScope, HasMany, HasOne, Is, IsEmail, Model,
4 Scopes, Table, UpdatedAt
5 } from 'sequelize-typescript'
6 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
7 import { User } from '../../../shared/models/users'
9 isUserAutoPlayVideoValid, isUserDisplayNSFWValid, isUserPasswordValid, isUserRoleValid, isUserUsernameValid,
11 } from '../../helpers/custom-validators/users'
12 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
13 import { OAuthTokenModel } from '../oauth/oauth-token'
14 import { getSort, throwIfNotValid } from '../utils'
15 import { VideoChannelModel } from '../video/video-channel'
16 import { AccountModel } from './account'
21 model: () => AccountModel,
30 model: () => AccountModel,
32 include: [ () => VideoChannelModel ]
41 fields: [ 'username' ],
50 export class UserModel extends Model<UserModel> {
53 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
58 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
64 @Column(DataType.STRING(400))
69 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
75 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
77 autoPlayVideo: boolean
80 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
85 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
86 @Column(DataType.BIGINT)
95 @HasOne(() => AccountModel, {
101 @HasMany(() => OAuthTokenModel, {
102 foreignKey: 'userId',
105 OAuthTokens: OAuthTokenModel[]
109 static cryptPasswordIfNeeded (instance: UserModel) {
110 if (instance.changed('password')) {
111 return cryptPassword(instance.password)
113 instance.password = hash
119 static countTotal () {
123 static getByUsername (username: string) {
128 include: [ { model: AccountModel, required: true } ]
131 return UserModel.findOne(query)
134 static listForApi (start: number, count: number, sort: string) {
138 order: [ getSort(sort) ]
141 return UserModel.findAndCountAll(query)
142 .then(({ rows, count }) => {
150 static loadById (id: number) {
151 return UserModel.findById(id)
154 static loadByUsername (username: string) {
161 return UserModel.findOne(query)
164 static loadByUsernameAndPopulateChannels (username: string) {
171 return UserModel.scope('withVideoChannel').findOne(query)
174 static loadByUsernameOrEmail (username: string, email: string) {
177 [ Sequelize.Op.or ]: [ { username }, { email } ]
181 return UserModel.findOne(query)
184 private static getOriginalVideoFileTotalFromUser (user: UserModel) {
185 // Don't use sequelize because we need to use a sub query
186 const query = 'SELECT SUM("size") AS "total" FROM ' +
187 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
188 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
189 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
190 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
191 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
192 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
195 bind: { userId: user.id },
196 type: Sequelize.QueryTypes.SELECT
198 return UserModel.sequelize.query(query, options)
199 .then(([ { total } ]) => {
200 if (total === null) return 0
202 return parseInt(total, 10)
206 hasRight (right: UserRight) {
207 return hasUserRight(this.role, right)
210 isPasswordMatch (password: string) {
211 return comparePassword(password, this.password)
214 toFormattedJSON (): User {
217 username: this.username,
219 displayNSFW: this.displayNSFW,
220 autoPlayVideo: this.autoPlayVideo,
222 roleLabel: USER_ROLE_LABELS[ this.role ],
223 videoQuota: this.videoQuota,
224 createdAt: this.createdAt,
225 account: this.Account.toFormattedJSON(),
229 if (Array.isArray(this.Account.VideoChannels) === true) {
230 json.videoChannels = this.Account.VideoChannels
231 .map(c => c.toFormattedJSON())
233 if (v1.createdAt < v2.createdAt) return -1
234 if (v1.createdAt === v2.createdAt) return 0
243 isAbleToUploadVideo (videoFile: Express.Multer.File) {
244 if (this.videoQuota === -1) return Promise.resolve(true)
246 return UserModel.getOriginalVideoFileTotalFromUser(this)
247 .then(totalBytes => {
248 return (videoFile.size + totalBytes) < this.videoQuota