]>
Commit | Line | Data |
---|---|---|
1 | import * as Sequelize from 'sequelize' | |
2 | import { | |
3 | AfterDelete, | |
4 | AfterUpdate, | |
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 | |
21 | } from 'sequelize-typescript' | |
22 | import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared' | |
23 | import { User, UserRole } from '../../../shared/models/users' | |
24 | import { | |
25 | isUserAutoPlayVideoValid, | |
26 | isUserBlockedReasonValid, | |
27 | isUserBlockedValid, | |
28 | isUserEmailVerifiedValid, | |
29 | isUserNSFWPolicyValid, | |
30 | isUserPasswordValid, | |
31 | isUserRoleValid, | |
32 | isUserUsernameValid, | |
33 | isUserVideoQuotaDailyValid, | |
34 | isUserVideoQuotaValid, | |
35 | isUserWebTorrentEnabledValid | |
36 | } from '../../helpers/custom-validators/users' | |
37 | import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto' | |
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' | |
42 | import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type' | |
43 | import { values } from 'lodash' | |
44 | import { NSFW_POLICY_TYPES } from '../../initializers' | |
45 | import { clearCacheByUserId } from '../../lib/oauth-model' | |
46 | ||
47 | enum ScopeNames { | |
48 | WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL' | |
49 | } | |
50 | ||
51 | @DefaultScope({ | |
52 | include: [ | |
53 | { | |
54 | model: () => AccountModel, | |
55 | required: true | |
56 | } | |
57 | ] | |
58 | }) | |
59 | @Scopes({ | |
60 | [ScopeNames.WITH_VIDEO_CHANNEL]: { | |
61 | include: [ | |
62 | { | |
63 | model: () => AccountModel, | |
64 | required: true, | |
65 | include: [ () => VideoChannelModel ] | |
66 | } | |
67 | ] | |
68 | } | |
69 | }) | |
70 | @Table({ | |
71 | tableName: 'user', | |
72 | indexes: [ | |
73 | { | |
74 | fields: [ 'username' ], | |
75 | unique: true | |
76 | }, | |
77 | { | |
78 | fields: [ 'email' ], | |
79 | unique: true | |
80 | } | |
81 | ] | |
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 | ||
100 | @AllowNull(true) | |
101 | @Default(null) | |
102 | @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean')) | |
103 | @Column | |
104 | emailVerified: boolean | |
105 | ||
106 | @AllowNull(false) | |
107 | @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy')) | |
108 | @Column(DataType.ENUM(values(NSFW_POLICY_TYPES))) | |
109 | nsfwPolicy: NSFWPolicyType | |
110 | ||
111 | @AllowNull(false) | |
112 | @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled')) | |
113 | @Column | |
114 | webTorrentEnabled: boolean | |
115 | ||
116 | @AllowNull(false) | |
117 | @Default(true) | |
118 | @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean')) | |
119 | @Column | |
120 | autoPlayVideo: boolean | |
121 | ||
122 | @AllowNull(false) | |
123 | @Default(false) | |
124 | @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean')) | |
125 | @Column | |
126 | blocked: boolean | |
127 | ||
128 | @AllowNull(true) | |
129 | @Default(null) | |
130 | @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason')) | |
131 | @Column | |
132 | blockedReason: string | |
133 | ||
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 | ||
144 | @AllowNull(false) | |
145 | @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily')) | |
146 | @Column(DataType.BIGINT) | |
147 | videoQuotaDaily: number | |
148 | ||
149 | @CreatedAt | |
150 | createdAt: Date | |
151 | ||
152 | @UpdatedAt | |
153 | updatedAt: Date | |
154 | ||
155 | @HasOne(() => AccountModel, { | |
156 | foreignKey: 'userId', | |
157 | onDelete: 'cascade', | |
158 | hooks: true | |
159 | }) | |
160 | Account: AccountModel | |
161 | ||
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 | } | |
178 | } | |
179 | ||
180 | @AfterUpdate | |
181 | @AfterDelete | |
182 | static removeTokenCache (instance: UserModel) { | |
183 | return clearCacheByUserId(instance.id) | |
184 | } | |
185 | ||
186 | static countTotal () { | |
187 | return this.count() | |
188 | } | |
189 | ||
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 | ||
209 | const query = { | |
210 | attributes: { | |
211 | include: [ | |
212 | [ | |
213 | Sequelize.literal( | |
214 | '(' + | |
215 | 'SELECT COALESCE(SUM("size"), 0) ' + | |
216 | 'FROM (' + | |
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 | }, | |
229 | offset: start, | |
230 | limit: count, | |
231 | order: getSort(sort), | |
232 | where | |
233 | } | |
234 | ||
235 | return UserModel.findAndCountAll(query) | |
236 | .then(({ rows, count }) => { | |
237 | return { | |
238 | data: rows, | |
239 | total: count | |
240 | } | |
241 | }) | |
242 | } | |
243 | ||
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 | ||
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 | ||
263 | static loadById (id: number) { | |
264 | return UserModel.findById(id) | |
265 | } | |
266 | ||
267 | static loadByUsername (username: string) { | |
268 | const query = { | |
269 | where: { | |
270 | username | |
271 | } | |
272 | } | |
273 | ||
274 | return UserModel.findOne(query) | |
275 | } | |
276 | ||
277 | static loadByUsernameAndPopulateChannels (username: string) { | |
278 | const query = { | |
279 | where: { | |
280 | username | |
281 | } | |
282 | } | |
283 | ||
284 | return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query) | |
285 | } | |
286 | ||
287 | static loadByEmail (email: string) { | |
288 | const query = { | |
289 | where: { | |
290 | ||
291 | } | |
292 | } | |
293 | ||
294 | return UserModel.findOne(query) | |
295 | } | |
296 | ||
297 | static loadByUsernameOrEmail (username: string, email?: string) { | |
298 | if (!email) email = username | |
299 | ||
300 | const query = { | |
301 | where: { | |
302 | [ Sequelize.Op.or ]: [ { username }, { email } ] | |
303 | } | |
304 | } | |
305 | ||
306 | return UserModel.findOne(query) | |
307 | } | |
308 | ||
309 | static getOriginalVideoFileTotalFromUser (user: UserModel) { | |
310 | // Don't use sequelize because we need to use a sub query | |
311 | const query = UserModel.generateUserQuotaBaseSQL() | |
312 | ||
313 | return UserModel.getTotalRawQuery(query, user.id) | |
314 | } | |
315 | ||
316 | // Returns cumulative size of all video files uploaded in the last 24 hours. | |
317 | static getOriginalVideoFileTotalDailyFromUser (user: UserModel) { | |
318 | // Don't use sequelize because we need to use a sub query | |
319 | const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'') | |
320 | ||
321 | return UserModel.getTotalRawQuery(query, user.id) | |
322 | } | |
323 | ||
324 | static async getStats () { | |
325 | const totalUsers = await UserModel.count() | |
326 | ||
327 | return { | |
328 | totalUsers | |
329 | } | |
330 | } | |
331 | ||
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 | ||
346 | hasRight (right: UserRight) { | |
347 | return hasUserRight(this.role, right) | |
348 | } | |
349 | ||
350 | isPasswordMatch (password: string) { | |
351 | return comparePassword(password, this.password) | |
352 | } | |
353 | ||
354 | toFormattedJSON (): User { | |
355 | const videoQuotaUsed = this.get('videoQuotaUsed') | |
356 | const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily') | |
357 | ||
358 | const json = { | |
359 | id: this.id, | |
360 | username: this.username, | |
361 | email: this.email, | |
362 | emailVerified: this.emailVerified, | |
363 | nsfwPolicy: this.nsfwPolicy, | |
364 | webTorrentEnabled: this.webTorrentEnabled, | |
365 | autoPlayVideo: this.autoPlayVideo, | |
366 | role: this.role, | |
367 | roleLabel: USER_ROLE_LABELS[ this.role ], | |
368 | videoQuota: this.videoQuota, | |
369 | videoQuotaDaily: this.videoQuotaDaily, | |
370 | createdAt: this.createdAt, | |
371 | blocked: this.blocked, | |
372 | blockedReason: this.blockedReason, | |
373 | account: this.Account.toFormattedJSON(), | |
374 | videoChannels: [], | |
375 | videoQuotaUsed: videoQuotaUsed !== undefined | |
376 | ? parseInt(videoQuotaUsed, 10) | |
377 | : undefined, | |
378 | videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined | |
379 | ? parseInt(videoQuotaUsedDaily, 10) | |
380 | : undefined | |
381 | } | |
382 | ||
383 | if (Array.isArray(this.Account.VideoChannels) === true) { | |
384 | json.videoChannels = this.Account.VideoChannels | |
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 | |
389 | ||
390 | return 1 | |
391 | }) | |
392 | } | |
393 | ||
394 | return json | |
395 | } | |
396 | ||
397 | async isAbleToUploadVideo (videoFile: { size: number }) { | |
398 | if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true) | |
399 | ||
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) | |
416 | } | |
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 | } | |
445 | } |