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