]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
Add features table on signup
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
e02643f3 1import * as Sequelize from 'sequelize'
3fd3ab2d 2import {
a73c582e
C
3 AllowNull,
4 BeforeCreate,
5 BeforeUpdate,
6 Column,
7 CreatedAt,
8 DataType,
9 Default,
10 DefaultScope,
11 HasMany,
12 HasOne,
13 Is,
14 IsEmail,
15 Model,
16 Scopes,
17 Table,
18 UpdatedAt
3fd3ab2d 19} from 'sequelize-typescript'
e34c85e5 20import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
ba75d268 21import { User, UserRole } from '../../../shared/models/users'
65fcc311 22import {
a73c582e 23 isUserAutoPlayVideoValid,
eacb25c4 24 isUserBlockedReasonValid,
e6921918 25 isUserBlockedValid,
0883b324 26 isUserNSFWPolicyValid,
a73c582e
C
27 isUserPasswordValid,
28 isUserRoleValid,
29 isUserUsernameValid,
bee0abff
FA
30 isUserVideoQuotaValid,
31 isUserVideoQuotaDailyValid
3fd3ab2d 32} from '../../helpers/custom-validators/users'
da854ddd 33import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
34import { OAuthTokenModel } from '../oauth/oauth-token'
35import { getSort, throwIfNotValid } from '../utils'
36import { VideoChannelModel } from '../video/video-channel'
37import { AccountModel } from './account'
0883b324
C
38import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39import { values } from 'lodash'
40import { NSFW_POLICY_TYPES } from '../../initializers'
3fd3ab2d 41
9c2e0dbf
C
42enum ScopeNames {
43 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
44}
45
d48ff09d
C
46@DefaultScope({
47 include: [
48 {
49 model: () => AccountModel,
50 required: true
51 }
52 ]
53})
54@Scopes({
9c2e0dbf 55 [ScopeNames.WITH_VIDEO_CHANNEL]: {
d48ff09d
C
56 include: [
57 {
58 model: () => AccountModel,
59 required: true,
60 include: [ () => VideoChannelModel ]
61 }
62 ]
63 }
64})
3fd3ab2d
C
65@Table({
66 tableName: 'user',
67 indexes: [
feb4bdfd 68 {
3fd3ab2d
C
69 fields: [ 'username' ],
70 unique: true
feb4bdfd
C
71 },
72 {
3fd3ab2d
C
73 fields: [ 'email' ],
74 unique: true
feb4bdfd 75 }
e02643f3 76 ]
3fd3ab2d
C
77})
78export class UserModel extends Model<UserModel> {
79
80 @AllowNull(false)
81 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
82 @Column
83 password: string
84
85 @AllowNull(false)
86 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
87 @Column
88 username: string
89
90 @AllowNull(false)
91 @IsEmail
92 @Column(DataType.STRING(400))
93 email: string
94
95 @AllowNull(false)
0883b324
C
96 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
97 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
98 nsfwPolicy: NSFWPolicyType
3fd3ab2d 99
7efe153b
AL
100 @AllowNull(false)
101 @Default(true)
102 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
103 @Column
104 autoPlayVideo: boolean
105
e6921918
C
106 @AllowNull(false)
107 @Default(false)
108 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
109 @Column
110 blocked: boolean
111
eacb25c4
C
112 @AllowNull(true)
113 @Default(null)
114 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
115 @Column
116 blockedReason: string
117
3fd3ab2d
C
118 @AllowNull(false)
119 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
120 @Column
121 role: number
122
123 @AllowNull(false)
124 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
125 @Column(DataType.BIGINT)
126 videoQuota: number
127
bee0abff
FA
128 @AllowNull(false)
129 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
130 @Column(DataType.BIGINT)
131 videoQuotaDaily: number
132
3fd3ab2d
C
133 @CreatedAt
134 createdAt: Date
135
136 @UpdatedAt
137 updatedAt: Date
138
139 @HasOne(() => AccountModel, {
140 foreignKey: 'userId',
f05a1c30
C
141 onDelete: 'cascade',
142 hooks: true
3fd3ab2d
C
143 })
144 Account: AccountModel
69b0a27c 145
3fd3ab2d
C
146 @HasMany(() => OAuthTokenModel, {
147 foreignKey: 'userId',
148 onDelete: 'cascade'
149 })
150 OAuthTokens: OAuthTokenModel[]
151
152 @BeforeCreate
153 @BeforeUpdate
154 static cryptPasswordIfNeeded (instance: UserModel) {
155 if (instance.changed('password')) {
156 return cryptPassword(instance.password)
157 .then(hash => {
158 instance.password = hash
159 return undefined
160 })
161 }
59557c46 162 }
26d7d31b 163
3fd3ab2d
C
164 static countTotal () {
165 return this.count()
166 }
954605a8 167
3fd3ab2d
C
168 static listForApi (start: number, count: number, sort: string) {
169 const query = {
a76138ff
C
170 attributes: {
171 include: [
172 [
173 Sequelize.literal(
174 '(' +
175 'SELECT COALESCE(SUM("size"), 0) FROM ' +
176 '(' +
177 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
178 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
179 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
180 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
181 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
182 ') t' +
183 ')'
184 ),
185 'videoQuotaUsed'
186 ] as any // FIXME: typings
187 ]
188 },
3fd3ab2d
C
189 offset: start,
190 limit: count,
6ff9c676 191 order: getSort(sort)
3fd3ab2d 192 }
72c7248b 193
3fd3ab2d
C
194 return UserModel.findAndCountAll(query)
195 .then(({ rows, count }) => {
196 return {
197 data: rows,
198 total: count
199 }
72c7248b 200 })
72c7248b
C
201 }
202
ba75d268
C
203 static listEmailsWithRight (right: UserRight) {
204 const roles = Object.keys(USER_ROLE_LABELS)
205 .map(k => parseInt(k, 10) as UserRole)
206 .filter(role => hasUserRight(role, right))
207
ba75d268
C
208 const query = {
209 attribute: [ 'email' ],
210 where: {
211 role: {
212 [Sequelize.Op.in]: roles
213 }
214 }
215 }
216
217 return UserModel.unscoped()
218 .findAll(query)
219 .then(u => u.map(u => u.email))
220 }
221
3fd3ab2d 222 static loadById (id: number) {
d48ff09d 223 return UserModel.findById(id)
3fd3ab2d 224 }
feb4bdfd 225
3fd3ab2d
C
226 static loadByUsername (username: string) {
227 const query = {
228 where: {
229 username
d48ff09d 230 }
3fd3ab2d 231 }
089ff2f2 232
3fd3ab2d 233 return UserModel.findOne(query)
feb4bdfd
C
234 }
235
3fd3ab2d
C
236 static loadByUsernameAndPopulateChannels (username: string) {
237 const query = {
238 where: {
239 username
d48ff09d 240 }
3fd3ab2d 241 }
9bd26629 242
9c2e0dbf 243 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
feb4bdfd
C
244 }
245
ecb4e35f
C
246 static loadByEmail (email: string) {
247 const query = {
248 where: {
249 email
250 }
251 }
252
253 return UserModel.findOne(query)
254 }
255
ba12e8b3
C
256 static loadByUsernameOrEmail (username: string, email?: string) {
257 if (!email) email = username
258
3fd3ab2d 259 const query = {
3fd3ab2d
C
260 where: {
261 [ Sequelize.Op.or ]: [ { username }, { email } ]
262 }
6fcd19ba 263 }
69b0a27c 264
d48ff09d 265 return UserModel.findOne(query)
72c7248b
C
266 }
267
ce5496d6 268 static getOriginalVideoFileTotalFromUser (user: UserModel) {
3fd3ab2d
C
269 // Don't use sequelize because we need to use a sub query
270 const query = 'SELECT SUM("size") AS "total" FROM ' +
271 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
272 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
273 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
274 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
bee0abff
FA
275 'WHERE "account"."userId" = $userId ' +
276 'GROUP BY "video"."id") t'
277
278 const options = {
279 bind: { userId: user.id },
280 type: Sequelize.QueryTypes.SELECT
281 }
282 return UserModel.sequelize.query(query, options)
283 .then(([ { total } ]) => {
284 if (total === null) return 0
285
286 return parseInt(total, 10)
287 })
288 }
289
290 // Returns comulative size of all video files uploaded in the last 24 hours.
291 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
292 // Don't use sequelize because we need to use a sub query
293 const query = 'SELECT SUM("size") AS "total" FROM ' +
294 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
295 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
296 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
297 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
298 'WHERE "account"."userId" = $userId ' +
299 'AND "video"."createdAt" > now() - interval \'24 hours\'' +
300 'GROUP BY "video"."id") t'
3fd3ab2d
C
301
302 const options = {
303 bind: { userId: user.id },
304 type: Sequelize.QueryTypes.SELECT
305 }
306 return UserModel.sequelize.query(query, options)
307 .then(([ { total } ]) => {
308 if (total === null) return 0
68a3b9f2 309
3fd3ab2d
C
310 return parseInt(total, 10)
311 })
72c7248b
C
312 }
313
09cababd
C
314 static async getStats () {
315 const totalUsers = await UserModel.count()
316
317 return {
318 totalUsers
319 }
320 }
321
3fd3ab2d
C
322 hasRight (right: UserRight) {
323 return hasUserRight(this.role, right)
324 }
72c7248b 325
3fd3ab2d
C
326 isPasswordMatch (password: string) {
327 return comparePassword(password, this.password)
feb4bdfd
C
328 }
329
c5911fd3 330 toFormattedJSON (): User {
a76138ff 331 const videoQuotaUsed = this.get('videoQuotaUsed')
bee0abff 332 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
a76138ff 333
3fd3ab2d
C
334 const json = {
335 id: this.id,
336 username: this.username,
337 email: this.email,
0883b324 338 nsfwPolicy: this.nsfwPolicy,
7efe153b 339 autoPlayVideo: this.autoPlayVideo,
3fd3ab2d
C
340 role: this.role,
341 roleLabel: USER_ROLE_LABELS[ this.role ],
342 videoQuota: this.videoQuota,
bee0abff 343 videoQuotaDaily: this.videoQuotaDaily,
3fd3ab2d 344 createdAt: this.createdAt,
eacb25c4
C
345 blocked: this.blocked,
346 blockedReason: this.blockedReason,
c5911fd3 347 account: this.Account.toFormattedJSON(),
a76138ff 348 videoChannels: [],
bee0abff
FA
349 videoQuotaUsed: videoQuotaUsed !== undefined
350 ? parseInt(videoQuotaUsed, 10)
351 : undefined,
352 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
353 ? parseInt(videoQuotaUsedDaily, 10)
354 : undefined
3fd3ab2d
C
355 }
356
357 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 358 json.videoChannels = this.Account.VideoChannels
3fd3ab2d
C
359 .map(c => c.toFormattedJSON())
360 .sort((v1, v2) => {
361 if (v1.createdAt < v2.createdAt) return -1
362 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 363
3fd3ab2d
C
364 return 1
365 })
ad4a8a1c 366 }
3fd3ab2d
C
367
368 return json
ad4a8a1c
C
369 }
370
bee0abff
FA
371 async isAbleToUploadVideo (videoFile: { size: number }) {
372 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
b0f9f39e 373
bee0abff
FA
374 const [ totalBytes, totalBytesDaily ] = await Promise.all([
375 UserModel.getOriginalVideoFileTotalFromUser(this),
376 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
377 ])
378
379 const uploadedTotal = videoFile.size + totalBytes
380 const uploadedDaily = videoFile.size + totalBytesDaily
381 if (this.videoQuotaDaily === -1) {
382 return uploadedTotal < this.videoQuota
383 }
384 if (this.videoQuota === -1) {
385 return uploadedDaily < this.videoQuotaDaily
386 }
387
388 return (uploadedTotal < this.videoQuota) &&
389 (uploadedDaily < this.videoQuotaDaily)
b0f9f39e 390 }
b0f9f39e 391}