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