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