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