]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
809e821bd389bbee3cf9a9b2d99ac841657017cc
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import {
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'
8 import {
9 isUserAutoPlayVideoValid, isUserDisplayNSFWValid, isUserPasswordValid, isUserRoleValid, isUserUsernameValid,
10 isUserVideoQuotaValid
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'
17
18 @DefaultScope({
19 include: [
20 {
21 model: () => AccountModel,
22 required: true
23 }
24 ]
25 })
26 @Scopes({
27 withVideoChannel: {
28 include: [
29 {
30 model: () => AccountModel,
31 required: true,
32 include: [ () => VideoChannelModel ]
33 }
34 ]
35 }
36 })
37 @Table({
38 tableName: 'user',
39 indexes: [
40 {
41 fields: [ 'username' ],
42 unique: true
43 },
44 {
45 fields: [ 'email' ],
46 unique: true
47 }
48 ]
49 })
50 export class UserModel extends Model<UserModel> {
51
52 @AllowNull(false)
53 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
54 @Column
55 password: string
56
57 @AllowNull(false)
58 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
59 @Column
60 username: string
61
62 @AllowNull(false)
63 @IsEmail
64 @Column(DataType.STRING(400))
65 email: string
66
67 @AllowNull(false)
68 @Default(false)
69 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
70 @Column
71 displayNSFW: boolean
72
73 @AllowNull(false)
74 @Default(true)
75 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
76 @Column
77 autoPlayVideo: boolean
78
79 @AllowNull(false)
80 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
81 @Column
82 role: number
83
84 @AllowNull(false)
85 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
86 @Column(DataType.BIGINT)
87 videoQuota: number
88
89 @CreatedAt
90 createdAt: Date
91
92 @UpdatedAt
93 updatedAt: Date
94
95 @HasOne(() => AccountModel, {
96 foreignKey: 'userId',
97 onDelete: 'cascade',
98 hooks: true
99 })
100 Account: AccountModel
101
102 @HasMany(() => OAuthTokenModel, {
103 foreignKey: 'userId',
104 onDelete: 'cascade'
105 })
106 OAuthTokens: OAuthTokenModel[]
107
108 @BeforeCreate
109 @BeforeUpdate
110 static cryptPasswordIfNeeded (instance: UserModel) {
111 if (instance.changed('password')) {
112 return cryptPassword(instance.password)
113 .then(hash => {
114 instance.password = hash
115 return undefined
116 })
117 }
118 }
119
120 static countTotal () {
121 return this.count()
122 }
123
124 static listForApi (start: number, count: number, sort: string) {
125 const query = {
126 offset: start,
127 limit: count,
128 order: [ getSort(sort) ]
129 }
130
131 return UserModel.findAndCountAll(query)
132 .then(({ rows, count }) => {
133 return {
134 data: rows,
135 total: count
136 }
137 })
138 }
139
140 static loadById (id: number) {
141 return UserModel.findById(id)
142 }
143
144 static loadByUsername (username: string) {
145 const query = {
146 where: {
147 username
148 }
149 }
150
151 return UserModel.findOne(query)
152 }
153
154 static loadByUsernameAndPopulateChannels (username: string) {
155 const query = {
156 where: {
157 username
158 }
159 }
160
161 return UserModel.scope('withVideoChannel').findOne(query)
162 }
163
164 static loadByUsernameOrEmail (username: string, email?: string) {
165 if (!email) email = username
166
167 const query = {
168 where: {
169 [ Sequelize.Op.or ]: [ { username }, { email } ]
170 }
171 }
172
173 return UserModel.findOne(query)
174 }
175
176 static getOriginalVideoFileTotalFromUser (user: UserModel) {
177 // Don't use sequelize because we need to use a sub query
178 const query = 'SELECT SUM("size") AS "total" FROM ' +
179 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
180 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
181 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
182 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
183 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
184 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
185
186 const options = {
187 bind: { userId: user.id },
188 type: Sequelize.QueryTypes.SELECT
189 }
190 return UserModel.sequelize.query(query, options)
191 .then(([ { total } ]) => {
192 if (total === null) return 0
193
194 return parseInt(total, 10)
195 })
196 }
197
198 hasRight (right: UserRight) {
199 return hasUserRight(this.role, right)
200 }
201
202 isPasswordMatch (password: string) {
203 return comparePassword(password, this.password)
204 }
205
206 toFormattedJSON (): User {
207 const json = {
208 id: this.id,
209 username: this.username,
210 email: this.email,
211 displayNSFW: this.displayNSFW,
212 autoPlayVideo: this.autoPlayVideo,
213 role: this.role,
214 roleLabel: USER_ROLE_LABELS[ this.role ],
215 videoQuota: this.videoQuota,
216 createdAt: this.createdAt,
217 account: this.Account.toFormattedJSON(),
218 videoChannels: []
219 }
220
221 if (Array.isArray(this.Account.VideoChannels) === true) {
222 json.videoChannels = this.Account.VideoChannels
223 .map(c => c.toFormattedJSON())
224 .sort((v1, v2) => {
225 if (v1.createdAt < v2.createdAt) return -1
226 if (v1.createdAt === v2.createdAt) return 0
227
228 return 1
229 })
230 }
231
232 return json
233 }
234
235 isAbleToUploadVideo (videoFile: Express.Multer.File) {
236 if (this.videoQuota === -1) return Promise.resolve(true)
237
238 return UserModel.getOriginalVideoFileTotalFromUser(this)
239 .then(totalBytes => {
240 return (videoFile.size + totalBytes) < this.videoQuota
241 })
242 }
243 }