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