]>
Commit | Line | Data |
---|---|---|
5600def4 | 1 | import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize' |
3fd3ab2d | 2 | import { |
d175a6f7 | 3 | AfterDestroy, |
f201a749 | 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, | |
b49f22d8 | 17 | IsUUID, |
a73c582e C |
18 | Model, |
19 | Scopes, | |
20 | Table, | |
b49f22d8 | 21 | UpdatedAt |
3fd3ab2d | 22 | } from 'sequelize-typescript' |
f43db2f4 | 23 | import { TokensCache } from '@server/lib/auth/tokens-cache' |
d493e2d4 | 24 | import { LiveQuotaStore } from '@server/lib/live' |
bd45d503 C |
25 | import { |
26 | MMyUserFormattable, | |
fb719404 | 27 | MUser, |
bd45d503 C |
28 | MUserDefault, |
29 | MUserFormattable, | |
bd45d503 | 30 | MUserNotifSettingChannelDefault, |
ff9d43f6 | 31 | MUserWithNotificationSetting |
bd45d503 | 32 | } from '@server/types/models' |
8c4bbd94 | 33 | import { forceNumber } from '@shared/core-utils' |
6b5f72be | 34 | import { AttributesOnly } from '@shared/typescript-utils' |
bd45d503 | 35 | import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users' |
ff9d43f6 | 36 | import { AbuseState, MyUser, UserRight, VideoPlaylistType } from '../../../shared/models' |
ba75d268 | 37 | import { User, UserRole } from '../../../shared/models/users' |
bd45d503 C |
38 | import { UserAdminFlag } from '../../../shared/models/users/user-flag.model' |
39 | import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type' | |
40 | import { isThemeNameValid } from '../../helpers/custom-validators/plugins' | |
65fcc311 | 41 | import { |
1eddc9a7 | 42 | isUserAdminFlagsValid, |
bee29df8 | 43 | isUserAutoPlayNextVideoPlaylistValid, |
ac0868bc C |
44 | isUserAutoPlayNextVideoValid, |
45 | isUserAutoPlayVideoValid, | |
eacb25c4 | 46 | isUserBlockedReasonValid, |
e6921918 | 47 | isUserBlockedValid, |
d9eaee39 | 48 | isUserEmailVerifiedValid, |
8f581725 | 49 | isUserNoModal, |
5cf84858 | 50 | isUserNSFWPolicyValid, |
9d8ef212 | 51 | isUserP2PEnabledValid, |
a73c582e C |
52 | isUserPasswordValid, |
53 | isUserRoleValid, | |
3caf77d3 | 54 | isUserVideoLanguages, |
5cf84858 | 55 | isUserVideoQuotaDailyValid, |
64cc5e85 | 56 | isUserVideoQuotaValid, |
9d8ef212 | 57 | isUserVideosHistoryEnabledValid |
3fd3ab2d | 58 | } from '../../helpers/custom-validators/users' |
da854ddd | 59 | import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto' |
bd45d503 | 60 | import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants' |
bd45d503 | 61 | import { getThemeOrDefault } from '../../lib/plugins/theme-utils' |
7d9ba5c0 C |
62 | import { AccountModel } from '../account/account' |
63 | import { ActorModel } from '../actor/actor' | |
64 | import { ActorFollowModel } from '../actor/actor-follow' | |
65 | import { ActorImageModel } from '../actor/actor-image' | |
3fd3ab2d | 66 | import { OAuthTokenModel } from '../oauth/oauth-token' |
8c4bbd94 | 67 | import { getAdminUsersSort, throwIfNotValid } from '../shared' |
bd45d503 | 68 | import { VideoModel } from '../video/video' |
3fd3ab2d | 69 | import { VideoChannelModel } from '../video/video-channel' |
bd45d503 | 70 | import { VideoImportModel } from '../video/video-import' |
97969c4e | 71 | import { VideoLiveModel } from '../video/video-live' |
29128b2f | 72 | import { VideoPlaylistModel } from '../video/video-playlist' |
cef534ed | 73 | import { UserNotificationSettingModel } from './user-notification-setting' |
3fd3ab2d | 74 | |
9c2e0dbf | 75 | enum ScopeNames { |
76314386 RK |
76 | FOR_ME_API = 'FOR_ME_API', |
77 | WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS', | |
9a82ce24 | 78 | WITH_QUOTA = 'WITH_QUOTA', |
76314386 | 79 | WITH_STATS = 'WITH_STATS' |
9c2e0dbf C |
80 | } |
81 | ||
3acc5084 | 82 | @DefaultScope(() => ({ |
d48ff09d C |
83 | include: [ |
84 | { | |
3acc5084 | 85 | model: AccountModel, |
d48ff09d | 86 | required: true |
cef534ed C |
87 | }, |
88 | { | |
3acc5084 | 89 | model: UserNotificationSettingModel, |
cef534ed | 90 | required: true |
d48ff09d C |
91 | } |
92 | ] | |
3acc5084 C |
93 | })) |
94 | @Scopes(() => ({ | |
ac0868bc | 95 | [ScopeNames.FOR_ME_API]: { |
d48ff09d C |
96 | include: [ |
97 | { | |
3acc5084 | 98 | model: AccountModel, |
ac0868bc C |
99 | include: [ |
100 | { | |
cdeddff1 C |
101 | model: VideoChannelModel.unscoped(), |
102 | include: [ | |
103 | { | |
104 | model: ActorModel, | |
105 | required: true, | |
106 | include: [ | |
107 | { | |
108 | model: ActorImageModel, | |
d0800f76 | 109 | as: 'Banners', |
cdeddff1 C |
110 | required: false |
111 | } | |
112 | ] | |
113 | } | |
114 | ] | |
ac0868bc C |
115 | }, |
116 | { | |
117 | attributes: [ 'id', 'name', 'type' ], | |
118 | model: VideoPlaylistModel.unscoped(), | |
119 | required: true, | |
120 | where: { | |
121 | type: { | |
a1587156 | 122 | [Op.ne]: VideoPlaylistType.REGULAR |
ac0868bc C |
123 | } |
124 | } | |
125 | } | |
126 | ] | |
cef534ed C |
127 | }, |
128 | { | |
3acc5084 | 129 | model: UserNotificationSettingModel, |
cef534ed | 130 | required: true |
d48ff09d | 131 | } |
3acc5084 | 132 | ] |
76314386 RK |
133 | }, |
134 | [ScopeNames.WITH_VIDEOCHANNELS]: { | |
135 | include: [ | |
136 | { | |
137 | model: AccountModel, | |
138 | include: [ | |
139 | { | |
140 | model: VideoChannelModel | |
141 | }, | |
142 | { | |
143 | attributes: [ 'id', 'name', 'type' ], | |
144 | model: VideoPlaylistModel.unscoped(), | |
145 | required: true, | |
146 | where: { | |
147 | type: { | |
148 | [Op.ne]: VideoPlaylistType.REGULAR | |
149 | } | |
150 | } | |
151 | } | |
152 | ] | |
153 | } | |
154 | ] | |
155 | }, | |
9a82ce24 | 156 | [ScopeNames.WITH_QUOTA]: { |
76314386 RK |
157 | attributes: { |
158 | include: [ | |
5600def4 C |
159 | [ |
160 | literal( | |
161 | '(' + | |
162 | UserModel.generateUserQuotaBaseSQL({ | |
163 | withSelect: false, | |
9a82ce24 C |
164 | whereUserId: '"UserModel"."id"', |
165 | daily: false | |
5600def4 C |
166 | }) + |
167 | ')' | |
168 | ), | |
169 | 'videoQuotaUsed' | |
170 | ], | |
9a82ce24 C |
171 | [ |
172 | literal( | |
173 | '(' + | |
174 | UserModel.generateUserQuotaBaseSQL({ | |
175 | withSelect: false, | |
176 | whereUserId: '"UserModel"."id"', | |
177 | daily: true | |
178 | }) + | |
179 | ')' | |
180 | ), | |
181 | 'videoQuotaUsedDaily' | |
182 | ] | |
183 | ] | |
184 | } | |
185 | }, | |
186 | [ScopeNames.WITH_STATS]: { | |
187 | attributes: { | |
188 | include: [ | |
76314386 RK |
189 | [ |
190 | literal( | |
191 | '(' + | |
192 | 'SELECT COUNT("video"."id") ' + | |
193 | 'FROM "video" ' + | |
194 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
195 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
196 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
197 | ')' | |
198 | ), | |
199 | 'videosCount' | |
200 | ], | |
201 | [ | |
202 | literal( | |
203 | '(' + | |
204 | `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` + | |
205 | 'FROM (' + | |
4f32032f C |
206 | 'SELECT COUNT("abuse"."id") AS "abuses", ' + |
207 | `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` + | |
208 | 'FROM "abuse" ' + | |
209 | 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' + | |
76314386 RK |
210 | 'WHERE "account"."userId" = "UserModel"."id"' + |
211 | ') t' + | |
212 | ')' | |
213 | ), | |
4f32032f | 214 | 'abusesCount' |
76314386 RK |
215 | ], |
216 | [ | |
217 | literal( | |
218 | '(' + | |
4f32032f C |
219 | 'SELECT COUNT("abuse"."id") ' + |
220 | 'FROM "abuse" ' + | |
221 | 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' + | |
76314386 RK |
222 | 'WHERE "account"."userId" = "UserModel"."id"' + |
223 | ')' | |
224 | ), | |
4f32032f | 225 | 'abusesCreatedCount' |
76314386 RK |
226 | ], |
227 | [ | |
228 | literal( | |
229 | '(' + | |
230 | 'SELECT COUNT("videoComment"."id") ' + | |
231 | 'FROM "videoComment" ' + | |
232 | 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' + | |
233 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
234 | ')' | |
235 | ), | |
236 | 'videoCommentsCount' | |
237 | ] | |
238 | ] | |
239 | } | |
d48ff09d | 240 | } |
3acc5084 | 241 | })) |
3fd3ab2d C |
242 | @Table({ |
243 | tableName: 'user', | |
244 | indexes: [ | |
feb4bdfd | 245 | { |
3fd3ab2d C |
246 | fields: [ 'username' ], |
247 | unique: true | |
feb4bdfd C |
248 | }, |
249 | { | |
3fd3ab2d C |
250 | fields: [ 'email' ], |
251 | unique: true | |
feb4bdfd | 252 | } |
e02643f3 | 253 | ] |
3fd3ab2d | 254 | }) |
16c016e8 | 255 | export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> { |
3fd3ab2d | 256 | |
7fed6375 | 257 | @AllowNull(true) |
e1c55031 | 258 | @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true)) |
3fd3ab2d C |
259 | @Column |
260 | password: string | |
261 | ||
262 | @AllowNull(false) | |
3fd3ab2d C |
263 | @Column |
264 | username: string | |
265 | ||
266 | @AllowNull(false) | |
267 | @IsEmail | |
268 | @Column(DataType.STRING(400)) | |
269 | email: string | |
270 | ||
d1ab89de C |
271 | @AllowNull(true) |
272 | @IsEmail | |
273 | @Column(DataType.STRING(400)) | |
274 | pendingEmail: string | |
275 | ||
d9eaee39 JM |
276 | @AllowNull(true) |
277 | @Default(null) | |
1735c825 | 278 | @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true)) |
d9eaee39 JM |
279 | @Column |
280 | emailVerified: boolean | |
281 | ||
3fd3ab2d | 282 | @AllowNull(false) |
0883b324 | 283 | @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy')) |
690bb8f9 | 284 | @Column(DataType.ENUM(...Object.values(NSFW_POLICY_TYPES))) |
0883b324 | 285 | nsfwPolicy: NSFWPolicyType |
3fd3ab2d | 286 | |
64cc5e85 | 287 | @AllowNull(false) |
a9bfa85d | 288 | @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled')) |
ed638e53 | 289 | @Column |
a9bfa85d | 290 | p2pEnabled: boolean |
64cc5e85 | 291 | |
8b9a525a C |
292 | @AllowNull(false) |
293 | @Default(true) | |
294 | @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled')) | |
295 | @Column | |
296 | videosHistoryEnabled: boolean | |
297 | ||
7efe153b AL |
298 | @AllowNull(false) |
299 | @Default(true) | |
300 | @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean')) | |
301 | @Column | |
302 | autoPlayVideo: boolean | |
303 | ||
6aa54148 L |
304 | @AllowNull(false) |
305 | @Default(false) | |
306 | @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean')) | |
307 | @Column | |
308 | autoPlayNextVideo: boolean | |
309 | ||
bee29df8 RK |
310 | @AllowNull(false) |
311 | @Default(true) | |
a1587156 C |
312 | @Is( |
313 | 'UserAutoPlayNextVideoPlaylist', | |
314 | value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean') | |
315 | ) | |
bee29df8 RK |
316 | @Column |
317 | autoPlayNextVideoPlaylist: boolean | |
318 | ||
3caf77d3 C |
319 | @AllowNull(true) |
320 | @Default(null) | |
321 | @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages')) | |
322 | @Column(DataType.ARRAY(DataType.STRING)) | |
323 | videoLanguages: string[] | |
324 | ||
1eddc9a7 C |
325 | @AllowNull(false) |
326 | @Default(UserAdminFlag.NONE) | |
327 | @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags')) | |
328 | @Column | |
329 | adminFlags?: UserAdminFlag | |
330 | ||
e6921918 C |
331 | @AllowNull(false) |
332 | @Default(false) | |
333 | @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean')) | |
334 | @Column | |
335 | blocked: boolean | |
336 | ||
eacb25c4 C |
337 | @AllowNull(true) |
338 | @Default(null) | |
1735c825 | 339 | @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true)) |
eacb25c4 C |
340 | @Column |
341 | blockedReason: string | |
342 | ||
3fd3ab2d C |
343 | @AllowNull(false) |
344 | @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role')) | |
345 | @Column | |
346 | role: number | |
347 | ||
348 | @AllowNull(false) | |
349 | @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota')) | |
350 | @Column(DataType.BIGINT) | |
351 | videoQuota: number | |
352 | ||
bee0abff FA |
353 | @AllowNull(false) |
354 | @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily')) | |
355 | @Column(DataType.BIGINT) | |
356 | videoQuotaDaily: number | |
357 | ||
7cd4d2ba | 358 | @AllowNull(false) |
3f87a46f | 359 | @Default(DEFAULT_USER_THEME_NAME) |
503c6f44 | 360 | @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme')) |
7cd4d2ba C |
361 | @Column |
362 | theme: string | |
363 | ||
43d0ea7f C |
364 | @AllowNull(false) |
365 | @Default(false) | |
366 | @Is( | |
367 | 'UserNoInstanceConfigWarningModal', | |
8f581725 | 368 | value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal') |
43d0ea7f C |
369 | ) |
370 | @Column | |
371 | noInstanceConfigWarningModal: boolean | |
372 | ||
373 | @AllowNull(false) | |
374 | @Default(false) | |
375 | @Is( | |
8f581725 C |
376 | 'UserNoWelcomeModal', |
377 | value => throwIfNotValid(value, isUserNoModal, 'no welcome modal') | |
43d0ea7f C |
378 | ) |
379 | @Column | |
380 | noWelcomeModal: boolean | |
381 | ||
8f581725 C |
382 | @AllowNull(false) |
383 | @Default(false) | |
384 | @Is( | |
385 | 'UserNoAccountSetupWarningModal', | |
386 | value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal') | |
387 | ) | |
388 | @Column | |
389 | noAccountSetupWarningModal: boolean | |
390 | ||
7fed6375 C |
391 | @AllowNull(true) |
392 | @Default(null) | |
393 | @Column | |
394 | pluginAuth: string | |
395 | ||
afff310e RK |
396 | @AllowNull(false) |
397 | @Default(DataType.UUIDV4) | |
398 | @IsUUID(4) | |
399 | @Column(DataType.UUID) | |
400 | feedToken: string | |
401 | ||
3cc665f4 C |
402 | @AllowNull(true) |
403 | @Default(null) | |
404 | @Column | |
405 | lastLoginDate: Date | |
406 | ||
56f47830 C |
407 | @AllowNull(true) |
408 | @Default(null) | |
409 | @Column | |
410 | otpSecret: string | |
411 | ||
3fd3ab2d C |
412 | @CreatedAt |
413 | createdAt: Date | |
414 | ||
415 | @UpdatedAt | |
416 | updatedAt: Date | |
417 | ||
418 | @HasOne(() => AccountModel, { | |
419 | foreignKey: 'userId', | |
f05a1c30 C |
420 | onDelete: 'cascade', |
421 | hooks: true | |
3fd3ab2d C |
422 | }) |
423 | Account: AccountModel | |
69b0a27c | 424 | |
cef534ed C |
425 | @HasOne(() => UserNotificationSettingModel, { |
426 | foreignKey: 'userId', | |
427 | onDelete: 'cascade', | |
428 | hooks: true | |
429 | }) | |
430 | NotificationSetting: UserNotificationSettingModel | |
431 | ||
dc133480 C |
432 | @HasMany(() => VideoImportModel, { |
433 | foreignKey: 'userId', | |
434 | onDelete: 'cascade' | |
435 | }) | |
436 | VideoImports: VideoImportModel[] | |
437 | ||
3fd3ab2d C |
438 | @HasMany(() => OAuthTokenModel, { |
439 | foreignKey: 'userId', | |
440 | onDelete: 'cascade' | |
441 | }) | |
442 | OAuthTokens: OAuthTokenModel[] | |
443 | ||
e364e31e C |
444 | // Used if we already set an encrypted password in user model |
445 | skipPasswordEncryption = false | |
446 | ||
3fd3ab2d C |
447 | @BeforeCreate |
448 | @BeforeUpdate | |
e364e31e C |
449 | static async cryptPasswordIfNeeded (instance: UserModel) { |
450 | if (instance.skipPasswordEncryption) return | |
451 | if (!instance.changed('password')) return | |
452 | if (!instance.password) return | |
453 | ||
454 | instance.password = await cryptPassword(instance.password) | |
59557c46 | 455 | } |
26d7d31b | 456 | |
f201a749 | 457 | @AfterUpdate |
d175a6f7 | 458 | @AfterDestroy |
f201a749 | 459 | static removeTokenCache (instance: UserModel) { |
f43db2f4 | 460 | return TokensCache.Instance.clearCacheByUserId(instance.id) |
f201a749 C |
461 | } |
462 | ||
3fd3ab2d | 463 | static countTotal () { |
823e411f | 464 | return UserModel.unscoped().count() |
3fd3ab2d | 465 | } |
954605a8 | 466 | |
87a0cac6 | 467 | static listForAdminApi (parameters: { |
8491293b RK |
468 | start: number |
469 | count: number | |
470 | sort: string | |
471 | search?: string | |
472 | blocked?: boolean | |
473 | }) { | |
474 | const { start, count, sort, search, blocked } = parameters | |
475 | const where: WhereOptions = {} | |
a1587156 | 476 | |
24b9417c | 477 | if (search) { |
8491293b | 478 | Object.assign(where, { |
3acc5084 | 479 | [Op.or]: [ |
24b9417c C |
480 | { |
481 | email: { | |
3acc5084 | 482 | [Op.iLike]: '%' + search + '%' |
24b9417c C |
483 | } |
484 | }, | |
485 | { | |
486 | username: { | |
a1587156 | 487 | [Op.iLike]: '%' + search + '%' |
24b9417c C |
488 | } |
489 | } | |
490 | ] | |
8491293b RK |
491 | }) |
492 | } | |
493 | ||
494 | if (blocked !== undefined) { | |
ba2684ce | 495 | Object.assign(where, { blocked }) |
24b9417c C |
496 | } |
497 | ||
3acc5084 | 498 | const query: FindOptions = { |
3fd3ab2d C |
499 | offset: start, |
500 | limit: count, | |
87a0cac6 | 501 | order: getAdminUsersSort(sort), |
24b9417c | 502 | where |
3fd3ab2d | 503 | } |
72c7248b | 504 | |
d0800f76 | 505 | return Promise.all([ |
506 | UserModel.unscoped().count(query), | |
9a82ce24 | 507 | UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query) |
d0800f76 | 508 | ]).then(([ total, data ]) => ({ total, data })) |
72c7248b C |
509 | } |
510 | ||
b49f22d8 | 511 | static listWithRight (right: UserRight): Promise<MUserDefault[]> { |
ba75d268 | 512 | const roles = Object.keys(USER_ROLE_LABELS) |
a1587156 C |
513 | .map(k => parseInt(k, 10) as UserRole) |
514 | .filter(role => hasUserRight(role, right)) | |
ba75d268 | 515 | |
ba75d268 | 516 | const query = { |
ba75d268 C |
517 | where: { |
518 | role: { | |
3acc5084 | 519 | [Op.in]: roles |
ba75d268 C |
520 | } |
521 | } | |
522 | } | |
523 | ||
cef534ed C |
524 | return UserModel.findAll(query) |
525 | } | |
526 | ||
b49f22d8 | 527 | static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> { |
cef534ed C |
528 | const query = { |
529 | include: [ | |
530 | { | |
531 | model: UserNotificationSettingModel.unscoped(), | |
532 | required: true | |
533 | }, | |
534 | { | |
535 | attributes: [ 'userId' ], | |
536 | model: AccountModel.unscoped(), | |
537 | required: true, | |
538 | include: [ | |
539 | { | |
a1587156 | 540 | attributes: [], |
cef534ed C |
541 | model: ActorModel.unscoped(), |
542 | required: true, | |
543 | where: { | |
544 | serverId: null | |
545 | }, | |
546 | include: [ | |
547 | { | |
a1587156 | 548 | attributes: [], |
cef534ed C |
549 | as: 'ActorFollowings', |
550 | model: ActorFollowModel.unscoped(), | |
551 | required: true, | |
552 | where: { | |
553 | targetActorId: actorId | |
554 | } | |
555 | } | |
556 | ] | |
557 | } | |
558 | ] | |
559 | } | |
560 | ] | |
561 | } | |
562 | ||
563 | return UserModel.unscoped().findAll(query) | |
ba75d268 C |
564 | } |
565 | ||
b49f22d8 | 566 | static listByUsernames (usernames: string[]): Promise<MUserDefault[]> { |
f7cc67b4 C |
567 | const query = { |
568 | where: { | |
569 | username: usernames | |
570 | } | |
571 | } | |
572 | ||
573 | return UserModel.findAll(query) | |
574 | } | |
575 | ||
b49f22d8 | 576 | static loadById (id: number): Promise<MUser> { |
fb719404 C |
577 | return UserModel.unscoped().findByPk(id) |
578 | } | |
579 | ||
b31d7262 C |
580 | static loadByIdFull (id: number): Promise<MUserDefault> { |
581 | return UserModel.findByPk(id) | |
582 | } | |
583 | ||
b49f22d8 | 584 | static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> { |
76314386 RK |
585 | const scopes = [ |
586 | ScopeNames.WITH_VIDEOCHANNELS | |
587 | ] | |
588 | ||
9a82ce24 C |
589 | if (withStats) { |
590 | scopes.push(ScopeNames.WITH_QUOTA) | |
591 | scopes.push(ScopeNames.WITH_STATS) | |
592 | } | |
76314386 RK |
593 | |
594 | return UserModel.scope(scopes).findByPk(id) | |
3fd3ab2d | 595 | } |
feb4bdfd | 596 | |
b49f22d8 | 597 | static loadByUsername (username: string): Promise<MUserDefault> { |
3fd3ab2d C |
598 | const query = { |
599 | where: { | |
1acb9475 | 600 | username |
d48ff09d | 601 | } |
3fd3ab2d | 602 | } |
089ff2f2 | 603 | |
3fd3ab2d | 604 | return UserModel.findOne(query) |
feb4bdfd C |
605 | } |
606 | ||
1acb9475 | 607 | static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> { |
3fd3ab2d C |
608 | const query = { |
609 | where: { | |
1acb9475 | 610 | id |
d48ff09d | 611 | } |
3fd3ab2d | 612 | } |
9bd26629 | 613 | |
ac0868bc | 614 | return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query) |
feb4bdfd C |
615 | } |
616 | ||
b49f22d8 | 617 | static loadByEmail (email: string): Promise<MUserDefault> { |
ecb4e35f C |
618 | const query = { |
619 | where: { | |
620 | ||
621 | } | |
622 | } | |
623 | ||
624 | return UserModel.findOne(query) | |
625 | } | |
626 | ||
b49f22d8 | 627 | static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> { |
ba12e8b3 C |
628 | if (!email) email = username |
629 | ||
3fd3ab2d | 630 | const query = { |
3fd3ab2d | 631 | where: { |
a1587156 | 632 | [Op.or]: [ |
9d8ef212 | 633 | where(fn('lower', col('username')), fn('lower', username) as any), |
c4a1811e C |
634 | |
635 | { email } | |
636 | ] | |
3fd3ab2d | 637 | } |
6fcd19ba | 638 | } |
69b0a27c | 639 | |
d48ff09d | 640 | return UserModel.findOne(query) |
72c7248b C |
641 | } |
642 | ||
b49f22d8 | 643 | static loadByVideoId (videoId: number): Promise<MUserDefault> { |
cef534ed C |
644 | const query = { |
645 | include: [ | |
646 | { | |
647 | required: true, | |
648 | attributes: [ 'id' ], | |
649 | model: AccountModel.unscoped(), | |
650 | include: [ | |
651 | { | |
652 | required: true, | |
653 | attributes: [ 'id' ], | |
654 | model: VideoChannelModel.unscoped(), | |
655 | include: [ | |
656 | { | |
657 | required: true, | |
658 | attributes: [ 'id' ], | |
659 | model: VideoModel.unscoped(), | |
660 | where: { | |
661 | id: videoId | |
662 | } | |
663 | } | |
664 | ] | |
665 | } | |
666 | ] | |
667 | } | |
668 | ] | |
669 | } | |
670 | ||
671 | return UserModel.findOne(query) | |
672 | } | |
673 | ||
b49f22d8 | 674 | static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> { |
dc133480 C |
675 | const query = { |
676 | include: [ | |
677 | { | |
678 | required: true, | |
679 | attributes: [ 'id' ], | |
680 | model: VideoImportModel.unscoped(), | |
681 | where: { | |
682 | id: videoImportId | |
683 | } | |
684 | } | |
685 | ] | |
686 | } | |
687 | ||
688 | return UserModel.findOne(query) | |
689 | } | |
690 | ||
b49f22d8 | 691 | static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> { |
f7cc67b4 C |
692 | const query = { |
693 | include: [ | |
694 | { | |
695 | required: true, | |
696 | attributes: [ 'id' ], | |
697 | model: AccountModel.unscoped(), | |
698 | include: [ | |
699 | { | |
700 | required: true, | |
701 | attributes: [ 'id' ], | |
702 | model: VideoChannelModel.unscoped(), | |
703 | where: { | |
704 | actorId: videoChannelActorId | |
705 | } | |
706 | } | |
707 | ] | |
708 | } | |
709 | ] | |
710 | } | |
711 | ||
712 | return UserModel.findOne(query) | |
713 | } | |
714 | ||
b49f22d8 | 715 | static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> { |
f7cc67b4 C |
716 | const query = { |
717 | include: [ | |
718 | { | |
719 | required: true, | |
720 | attributes: [ 'id' ], | |
721 | model: AccountModel.unscoped(), | |
722 | where: { | |
723 | actorId: accountActorId | |
724 | } | |
725 | } | |
726 | ] | |
727 | } | |
728 | ||
729 | return UserModel.findOne(query) | |
730 | } | |
731 | ||
b49f22d8 | 732 | static loadByLiveId (liveId: number): Promise<MUser> { |
fb719404 C |
733 | const query = { |
734 | include: [ | |
735 | { | |
736 | attributes: [ 'id' ], | |
737 | model: AccountModel.unscoped(), | |
738 | required: true, | |
739 | include: [ | |
740 | { | |
741 | attributes: [ 'id' ], | |
742 | model: VideoChannelModel.unscoped(), | |
743 | required: true, | |
744 | include: [ | |
745 | { | |
746 | attributes: [ 'id' ], | |
747 | model: VideoModel.unscoped(), | |
748 | required: true, | |
749 | include: [ | |
750 | { | |
31c82cd9 | 751 | attributes: [], |
fb719404 C |
752 | model: VideoLiveModel.unscoped(), |
753 | required: true, | |
754 | where: { | |
755 | id: liveId | |
756 | } | |
757 | } | |
758 | ] | |
759 | } | |
760 | ] | |
761 | } | |
762 | ] | |
763 | } | |
764 | ] | |
765 | } | |
766 | ||
31c82cd9 | 767 | return UserModel.unscoped().findOne(query) |
fb719404 C |
768 | } |
769 | ||
770 | static generateUserQuotaBaseSQL (options: { | |
771 | whereUserId: '$userId' | '"UserModel"."id"' | |
772 | withSelect: boolean | |
9a82ce24 | 773 | daily: boolean |
fb719404 | 774 | }) { |
9a82ce24 C |
775 | const andWhere = options.daily === true |
776 | ? 'AND "video"."createdAt" > now() - interval \'24 hours\'' | |
fb719404 C |
777 | : '' |
778 | ||
779 | const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
780 | 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' + | |
781 | `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}` | |
782 | ||
783 | const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
f2dbbf6a | 784 | 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" AND "video"."isLive" IS FALSE ' + |
fb719404 C |
785 | videoChannelJoin |
786 | ||
787 | const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
788 | 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' + | |
f2dbbf6a | 789 | 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" AND "video"."isLive" IS FALSE ' + |
fb719404 | 790 | videoChannelJoin |
bee0abff | 791 | |
fb719404 C |
792 | return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' + |
793 | 'FROM (' + | |
794 | `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` + | |
795 | 'GROUP BY "t1"."videoId"' + | |
796 | ') t2' | |
bee0abff FA |
797 | } |
798 | ||
fb719404 C |
799 | static getTotalRawQuery (query: string, userId: number) { |
800 | const options = { | |
801 | bind: { userId }, | |
802 | type: QueryTypes.SELECT as QueryTypes.SELECT | |
803 | } | |
804 | ||
805 | return UserModel.sequelize.query<{ total: string }>(query, options) | |
806 | .then(([ { total } ]) => { | |
807 | if (total === null) return 0 | |
68a3b9f2 | 808 | |
fb719404 C |
809 | return parseInt(total, 10) |
810 | }) | |
72c7248b C |
811 | } |
812 | ||
09cababd | 813 | static async getStats () { |
3cc665f4 C |
814 | function getActiveUsers (days: number) { |
815 | const query = { | |
816 | where: { | |
817 | [Op.and]: [ | |
818 | literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`) | |
819 | ] | |
820 | } | |
821 | } | |
822 | ||
5e0dbb3e | 823 | return UserModel.unscoped().count(query) |
3cc665f4 C |
824 | } |
825 | ||
5e0dbb3e | 826 | const totalUsers = await UserModel.unscoped().count() |
3cc665f4 C |
827 | const totalDailyActiveUsers = await getActiveUsers(1) |
828 | const totalWeeklyActiveUsers = await getActiveUsers(7) | |
829 | const totalMonthlyActiveUsers = await getActiveUsers(30) | |
47d8e266 | 830 | const totalHalfYearActiveUsers = await getActiveUsers(180) |
09cababd C |
831 | |
832 | return { | |
3cc665f4 C |
833 | totalUsers, |
834 | totalDailyActiveUsers, | |
835 | totalWeeklyActiveUsers, | |
47d8e266 C |
836 | totalMonthlyActiveUsers, |
837 | totalHalfYearActiveUsers | |
09cababd C |
838 | } |
839 | } | |
840 | ||
5cf84858 C |
841 | static autoComplete (search: string) { |
842 | const query = { | |
843 | where: { | |
844 | username: { | |
a1587156 | 845 | [Op.like]: `%${search}%` |
5cf84858 C |
846 | } |
847 | }, | |
848 | limit: 10 | |
849 | } | |
850 | ||
851 | return UserModel.findAll(query) | |
852 | .then(u => u.map(u => u.username)) | |
853 | } | |
854 | ||
3fd3ab2d C |
855 | hasRight (right: UserRight) { |
856 | return hasUserRight(this.role, right) | |
857 | } | |
72c7248b | 858 | |
1eddc9a7 C |
859 | hasAdminFlag (flag: UserAdminFlag) { |
860 | return this.adminFlags & flag | |
861 | } | |
862 | ||
3fd3ab2d C |
863 | isPasswordMatch (password: string) { |
864 | return comparePassword(password, this.password) | |
feb4bdfd C |
865 | } |
866 | ||
ac0868bc | 867 | toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User { |
a76138ff | 868 | const videoQuotaUsed = this.get('videoQuotaUsed') |
bee0abff | 869 | const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily') |
76314386 | 870 | const videosCount = this.get('videosCount') |
4f32032f C |
871 | const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':') |
872 | const abusesCreatedCount = this.get('abusesCreatedCount') | |
76314386 | 873 | const videoCommentsCount = this.get('videoCommentsCount') |
a76138ff | 874 | |
ac0868bc | 875 | const json: User = { |
3fd3ab2d C |
876 | id: this.id, |
877 | username: this.username, | |
878 | email: this.email, | |
43d0ea7f C |
879 | theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME), |
880 | ||
d1ab89de | 881 | pendingEmail: this.pendingEmail, |
d9eaee39 | 882 | emailVerified: this.emailVerified, |
43d0ea7f | 883 | |
0883b324 | 884 | nsfwPolicy: this.nsfwPolicy, |
a9bfa85d C |
885 | |
886 | // FIXME: deprecated in 4.1 | |
887 | webTorrentEnabled: this.p2pEnabled, | |
888 | p2pEnabled: this.p2pEnabled, | |
889 | ||
276d9652 | 890 | videosHistoryEnabled: this.videosHistoryEnabled, |
7efe153b | 891 | autoPlayVideo: this.autoPlayVideo, |
6aa54148 | 892 | autoPlayNextVideo: this.autoPlayNextVideo, |
bee29df8 | 893 | autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist, |
3caf77d3 | 894 | videoLanguages: this.videoLanguages, |
43d0ea7f | 895 | |
9e5cf66b C |
896 | role: { |
897 | id: this.role, | |
898 | label: USER_ROLE_LABELS[this.role] | |
899 | }, | |
43d0ea7f | 900 | |
3fd3ab2d | 901 | videoQuota: this.videoQuota, |
bee0abff | 902 | videoQuotaDaily: this.videoQuotaDaily, |
9a82ce24 | 903 | |
43d0ea7f | 904 | videoQuotaUsed: videoQuotaUsed !== undefined |
4638cd71 | 905 | ? forceNumber(videoQuotaUsed) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id) |
43d0ea7f | 906 | : undefined, |
9a82ce24 | 907 | |
43d0ea7f | 908 | videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined |
4638cd71 | 909 | ? forceNumber(videoQuotaUsedDaily) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id) |
43d0ea7f | 910 | : undefined, |
9a82ce24 | 911 | |
76314386 | 912 | videosCount: videosCount !== undefined |
4638cd71 | 913 | ? forceNumber(videosCount) |
76314386 | 914 | : undefined, |
4f32032f | 915 | abusesCount: abusesCount |
4638cd71 | 916 | ? forceNumber(abusesCount) |
76314386 | 917 | : undefined, |
4f32032f | 918 | abusesAcceptedCount: abusesAcceptedCount |
4638cd71 | 919 | ? forceNumber(abusesAcceptedCount) |
76314386 | 920 | : undefined, |
4f32032f | 921 | abusesCreatedCount: abusesCreatedCount !== undefined |
4638cd71 | 922 | ? forceNumber(abusesCreatedCount) |
76314386 RK |
923 | : undefined, |
924 | videoCommentsCount: videoCommentsCount !== undefined | |
4638cd71 | 925 | ? forceNumber(videoCommentsCount) |
76314386 | 926 | : undefined, |
43d0ea7f C |
927 | |
928 | noInstanceConfigWarningModal: this.noInstanceConfigWarningModal, | |
929 | noWelcomeModal: this.noWelcomeModal, | |
8f581725 | 930 | noAccountSetupWarningModal: this.noAccountSetupWarningModal, |
43d0ea7f | 931 | |
eacb25c4 C |
932 | blocked: this.blocked, |
933 | blockedReason: this.blockedReason, | |
43d0ea7f | 934 | |
c5911fd3 | 935 | account: this.Account.toFormattedJSON(), |
43d0ea7f C |
936 | |
937 | notificationSettings: this.NotificationSetting | |
938 | ? this.NotificationSetting.toFormattedJSON() | |
939 | : undefined, | |
940 | ||
a76138ff | 941 | videoChannels: [], |
43d0ea7f | 942 | |
8bb71f2e C |
943 | createdAt: this.createdAt, |
944 | ||
3cc665f4 C |
945 | pluginAuth: this.pluginAuth, |
946 | ||
56f47830 C |
947 | lastLoginDate: this.lastLoginDate, |
948 | ||
949 | twoFactorEnabled: !!this.otpSecret | |
3fd3ab2d C |
950 | } |
951 | ||
1eddc9a7 C |
952 | if (parameters.withAdminFlags) { |
953 | Object.assign(json, { adminFlags: this.adminFlags }) | |
954 | } | |
955 | ||
3fd3ab2d | 956 | if (Array.isArray(this.Account.VideoChannels) === true) { |
c5911fd3 | 957 | json.videoChannels = this.Account.VideoChannels |
a1587156 C |
958 | .map(c => c.toFormattedJSON()) |
959 | .sort((v1, v2) => { | |
960 | if (v1.createdAt < v2.createdAt) return -1 | |
961 | if (v1.createdAt === v2.createdAt) return 0 | |
ad4a8a1c | 962 | |
a1587156 C |
963 | return 1 |
964 | }) | |
ad4a8a1c | 965 | } |
3fd3ab2d C |
966 | |
967 | return json | |
ad4a8a1c C |
968 | } |
969 | ||
ac0868bc | 970 | toMeFormattedJSON (this: MMyUserFormattable): MyUser { |
4e1592da | 971 | const formatted = this.toFormattedJSON({ withAdminFlags: true }) |
ac0868bc C |
972 | |
973 | const specialPlaylists = this.Account.VideoPlaylists | |
a1587156 | 974 | .map(p => ({ id: p.id, name: p.name, type: p.type })) |
ac0868bc C |
975 | |
976 | return Object.assign(formatted, { specialPlaylists }) | |
977 | } | |
b0f9f39e | 978 | } |