]>
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' |
6b5f72be | 33 | import { AttributesOnly } from '@shared/typescript-utils' |
bd45d503 | 34 | import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users' |
ff9d43f6 | 35 | import { AbuseState, MyUser, UserRight, VideoPlaylistType } from '../../../shared/models' |
ba75d268 | 36 | import { User, UserRole } from '../../../shared/models/users' |
bd45d503 C |
37 | import { UserAdminFlag } from '../../../shared/models/users/user-flag.model' |
38 | import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type' | |
39 | import { isThemeNameValid } from '../../helpers/custom-validators/plugins' | |
65fcc311 | 40 | import { |
1eddc9a7 | 41 | isUserAdminFlagsValid, |
bee29df8 | 42 | isUserAutoPlayNextVideoPlaylistValid, |
ac0868bc C |
43 | isUserAutoPlayNextVideoValid, |
44 | isUserAutoPlayVideoValid, | |
eacb25c4 | 45 | isUserBlockedReasonValid, |
e6921918 | 46 | isUserBlockedValid, |
d9eaee39 | 47 | isUserEmailVerifiedValid, |
8f581725 | 48 | isUserNoModal, |
5cf84858 | 49 | isUserNSFWPolicyValid, |
9d8ef212 | 50 | isUserP2PEnabledValid, |
a73c582e C |
51 | isUserPasswordValid, |
52 | isUserRoleValid, | |
53 | isUserUsernameValid, | |
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' |
87a0cac6 | 67 | import { getAdminUsersSort, throwIfNotValid } from '../utils' |
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) | |
51892fe0 | 263 | @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name')) |
3fd3ab2d C |
264 | @Column |
265 | username: string | |
266 | ||
267 | @AllowNull(false) | |
268 | @IsEmail | |
269 | @Column(DataType.STRING(400)) | |
270 | email: string | |
271 | ||
d1ab89de C |
272 | @AllowNull(true) |
273 | @IsEmail | |
274 | @Column(DataType.STRING(400)) | |
275 | pendingEmail: string | |
276 | ||
d9eaee39 JM |
277 | @AllowNull(true) |
278 | @Default(null) | |
1735c825 | 279 | @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true)) |
d9eaee39 JM |
280 | @Column |
281 | emailVerified: boolean | |
282 | ||
3fd3ab2d | 283 | @AllowNull(false) |
0883b324 | 284 | @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy')) |
690bb8f9 | 285 | @Column(DataType.ENUM(...Object.values(NSFW_POLICY_TYPES))) |
0883b324 | 286 | nsfwPolicy: NSFWPolicyType |
3fd3ab2d | 287 | |
64cc5e85 | 288 | @AllowNull(false) |
a9bfa85d | 289 | @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled')) |
ed638e53 | 290 | @Column |
a9bfa85d | 291 | p2pEnabled: boolean |
64cc5e85 | 292 | |
8b9a525a C |
293 | @AllowNull(false) |
294 | @Default(true) | |
295 | @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled')) | |
296 | @Column | |
297 | videosHistoryEnabled: boolean | |
298 | ||
7efe153b AL |
299 | @AllowNull(false) |
300 | @Default(true) | |
301 | @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean')) | |
302 | @Column | |
303 | autoPlayVideo: boolean | |
304 | ||
6aa54148 L |
305 | @AllowNull(false) |
306 | @Default(false) | |
307 | @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean')) | |
308 | @Column | |
309 | autoPlayNextVideo: boolean | |
310 | ||
bee29df8 RK |
311 | @AllowNull(false) |
312 | @Default(true) | |
a1587156 C |
313 | @Is( |
314 | 'UserAutoPlayNextVideoPlaylist', | |
315 | value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean') | |
316 | ) | |
bee29df8 RK |
317 | @Column |
318 | autoPlayNextVideoPlaylist: boolean | |
319 | ||
3caf77d3 C |
320 | @AllowNull(true) |
321 | @Default(null) | |
322 | @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages')) | |
323 | @Column(DataType.ARRAY(DataType.STRING)) | |
324 | videoLanguages: string[] | |
325 | ||
1eddc9a7 C |
326 | @AllowNull(false) |
327 | @Default(UserAdminFlag.NONE) | |
328 | @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags')) | |
329 | @Column | |
330 | adminFlags?: UserAdminFlag | |
331 | ||
e6921918 C |
332 | @AllowNull(false) |
333 | @Default(false) | |
334 | @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean')) | |
335 | @Column | |
336 | blocked: boolean | |
337 | ||
eacb25c4 C |
338 | @AllowNull(true) |
339 | @Default(null) | |
1735c825 | 340 | @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true)) |
eacb25c4 C |
341 | @Column |
342 | blockedReason: string | |
343 | ||
3fd3ab2d C |
344 | @AllowNull(false) |
345 | @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role')) | |
346 | @Column | |
347 | role: number | |
348 | ||
349 | @AllowNull(false) | |
350 | @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota')) | |
351 | @Column(DataType.BIGINT) | |
352 | videoQuota: number | |
353 | ||
bee0abff FA |
354 | @AllowNull(false) |
355 | @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily')) | |
356 | @Column(DataType.BIGINT) | |
357 | videoQuotaDaily: number | |
358 | ||
7cd4d2ba | 359 | @AllowNull(false) |
3f87a46f | 360 | @Default(DEFAULT_USER_THEME_NAME) |
503c6f44 | 361 | @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme')) |
7cd4d2ba C |
362 | @Column |
363 | theme: string | |
364 | ||
43d0ea7f C |
365 | @AllowNull(false) |
366 | @Default(false) | |
367 | @Is( | |
368 | 'UserNoInstanceConfigWarningModal', | |
8f581725 | 369 | value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal') |
43d0ea7f C |
370 | ) |
371 | @Column | |
372 | noInstanceConfigWarningModal: boolean | |
373 | ||
374 | @AllowNull(false) | |
375 | @Default(false) | |
376 | @Is( | |
8f581725 C |
377 | 'UserNoWelcomeModal', |
378 | value => throwIfNotValid(value, isUserNoModal, 'no welcome modal') | |
43d0ea7f C |
379 | ) |
380 | @Column | |
381 | noWelcomeModal: boolean | |
382 | ||
8f581725 C |
383 | @AllowNull(false) |
384 | @Default(false) | |
385 | @Is( | |
386 | 'UserNoAccountSetupWarningModal', | |
387 | value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal') | |
388 | ) | |
389 | @Column | |
390 | noAccountSetupWarningModal: boolean | |
391 | ||
7fed6375 C |
392 | @AllowNull(true) |
393 | @Default(null) | |
394 | @Column | |
395 | pluginAuth: string | |
396 | ||
afff310e RK |
397 | @AllowNull(false) |
398 | @Default(DataType.UUIDV4) | |
399 | @IsUUID(4) | |
400 | @Column(DataType.UUID) | |
401 | feedToken: string | |
402 | ||
3cc665f4 C |
403 | @AllowNull(true) |
404 | @Default(null) | |
405 | @Column | |
406 | lastLoginDate: Date | |
407 | ||
3fd3ab2d C |
408 | @CreatedAt |
409 | createdAt: Date | |
410 | ||
411 | @UpdatedAt | |
412 | updatedAt: Date | |
413 | ||
414 | @HasOne(() => AccountModel, { | |
415 | foreignKey: 'userId', | |
f05a1c30 C |
416 | onDelete: 'cascade', |
417 | hooks: true | |
3fd3ab2d C |
418 | }) |
419 | Account: AccountModel | |
69b0a27c | 420 | |
cef534ed C |
421 | @HasOne(() => UserNotificationSettingModel, { |
422 | foreignKey: 'userId', | |
423 | onDelete: 'cascade', | |
424 | hooks: true | |
425 | }) | |
426 | NotificationSetting: UserNotificationSettingModel | |
427 | ||
dc133480 C |
428 | @HasMany(() => VideoImportModel, { |
429 | foreignKey: 'userId', | |
430 | onDelete: 'cascade' | |
431 | }) | |
432 | VideoImports: VideoImportModel[] | |
433 | ||
3fd3ab2d C |
434 | @HasMany(() => OAuthTokenModel, { |
435 | foreignKey: 'userId', | |
436 | onDelete: 'cascade' | |
437 | }) | |
438 | OAuthTokens: OAuthTokenModel[] | |
439 | ||
440 | @BeforeCreate | |
441 | @BeforeUpdate | |
442 | static cryptPasswordIfNeeded (instance: UserModel) { | |
e1c55031 | 443 | if (instance.changed('password') && instance.password) { |
3fd3ab2d C |
444 | return cryptPassword(instance.password) |
445 | .then(hash => { | |
446 | instance.password = hash | |
447 | return undefined | |
448 | }) | |
449 | } | |
59557c46 | 450 | } |
26d7d31b | 451 | |
f201a749 | 452 | @AfterUpdate |
d175a6f7 | 453 | @AfterDestroy |
f201a749 | 454 | static removeTokenCache (instance: UserModel) { |
f43db2f4 | 455 | return TokensCache.Instance.clearCacheByUserId(instance.id) |
f201a749 C |
456 | } |
457 | ||
3fd3ab2d C |
458 | static countTotal () { |
459 | return this.count() | |
460 | } | |
954605a8 | 461 | |
87a0cac6 | 462 | static listForAdminApi (parameters: { |
8491293b RK |
463 | start: number |
464 | count: number | |
465 | sort: string | |
466 | search?: string | |
467 | blocked?: boolean | |
468 | }) { | |
469 | const { start, count, sort, search, blocked } = parameters | |
470 | const where: WhereOptions = {} | |
a1587156 | 471 | |
24b9417c | 472 | if (search) { |
8491293b | 473 | Object.assign(where, { |
3acc5084 | 474 | [Op.or]: [ |
24b9417c C |
475 | { |
476 | email: { | |
3acc5084 | 477 | [Op.iLike]: '%' + search + '%' |
24b9417c C |
478 | } |
479 | }, | |
480 | { | |
481 | username: { | |
a1587156 | 482 | [Op.iLike]: '%' + search + '%' |
24b9417c C |
483 | } |
484 | } | |
485 | ] | |
8491293b RK |
486 | }) |
487 | } | |
488 | ||
489 | if (blocked !== undefined) { | |
ba2684ce | 490 | Object.assign(where, { blocked }) |
24b9417c C |
491 | } |
492 | ||
3acc5084 | 493 | const query: FindOptions = { |
3fd3ab2d C |
494 | offset: start, |
495 | limit: count, | |
87a0cac6 | 496 | order: getAdminUsersSort(sort), |
24b9417c | 497 | where |
3fd3ab2d | 498 | } |
72c7248b | 499 | |
d0800f76 | 500 | return Promise.all([ |
501 | UserModel.unscoped().count(query), | |
9a82ce24 | 502 | UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query) |
d0800f76 | 503 | ]).then(([ total, data ]) => ({ total, data })) |
72c7248b C |
504 | } |
505 | ||
b49f22d8 | 506 | static listWithRight (right: UserRight): Promise<MUserDefault[]> { |
ba75d268 | 507 | const roles = Object.keys(USER_ROLE_LABELS) |
a1587156 C |
508 | .map(k => parseInt(k, 10) as UserRole) |
509 | .filter(role => hasUserRight(role, right)) | |
ba75d268 | 510 | |
ba75d268 | 511 | const query = { |
ba75d268 C |
512 | where: { |
513 | role: { | |
3acc5084 | 514 | [Op.in]: roles |
ba75d268 C |
515 | } |
516 | } | |
517 | } | |
518 | ||
cef534ed C |
519 | return UserModel.findAll(query) |
520 | } | |
521 | ||
b49f22d8 | 522 | static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> { |
cef534ed C |
523 | const query = { |
524 | include: [ | |
525 | { | |
526 | model: UserNotificationSettingModel.unscoped(), | |
527 | required: true | |
528 | }, | |
529 | { | |
530 | attributes: [ 'userId' ], | |
531 | model: AccountModel.unscoped(), | |
532 | required: true, | |
533 | include: [ | |
534 | { | |
a1587156 | 535 | attributes: [], |
cef534ed C |
536 | model: ActorModel.unscoped(), |
537 | required: true, | |
538 | where: { | |
539 | serverId: null | |
540 | }, | |
541 | include: [ | |
542 | { | |
a1587156 | 543 | attributes: [], |
cef534ed C |
544 | as: 'ActorFollowings', |
545 | model: ActorFollowModel.unscoped(), | |
546 | required: true, | |
547 | where: { | |
548 | targetActorId: actorId | |
549 | } | |
550 | } | |
551 | ] | |
552 | } | |
553 | ] | |
554 | } | |
555 | ] | |
556 | } | |
557 | ||
558 | return UserModel.unscoped().findAll(query) | |
ba75d268 C |
559 | } |
560 | ||
b49f22d8 | 561 | static listByUsernames (usernames: string[]): Promise<MUserDefault[]> { |
f7cc67b4 C |
562 | const query = { |
563 | where: { | |
564 | username: usernames | |
565 | } | |
566 | } | |
567 | ||
568 | return UserModel.findAll(query) | |
569 | } | |
570 | ||
b49f22d8 | 571 | static loadById (id: number): Promise<MUser> { |
fb719404 C |
572 | return UserModel.unscoped().findByPk(id) |
573 | } | |
574 | ||
b31d7262 C |
575 | static loadByIdFull (id: number): Promise<MUserDefault> { |
576 | return UserModel.findByPk(id) | |
577 | } | |
578 | ||
b49f22d8 | 579 | static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> { |
76314386 RK |
580 | const scopes = [ |
581 | ScopeNames.WITH_VIDEOCHANNELS | |
582 | ] | |
583 | ||
9a82ce24 C |
584 | if (withStats) { |
585 | scopes.push(ScopeNames.WITH_QUOTA) | |
586 | scopes.push(ScopeNames.WITH_STATS) | |
587 | } | |
76314386 RK |
588 | |
589 | return UserModel.scope(scopes).findByPk(id) | |
3fd3ab2d | 590 | } |
feb4bdfd | 591 | |
b49f22d8 | 592 | static loadByUsername (username: string): Promise<MUserDefault> { |
3fd3ab2d C |
593 | const query = { |
594 | where: { | |
1acb9475 | 595 | username |
d48ff09d | 596 | } |
3fd3ab2d | 597 | } |
089ff2f2 | 598 | |
3fd3ab2d | 599 | return UserModel.findOne(query) |
feb4bdfd C |
600 | } |
601 | ||
1acb9475 | 602 | static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> { |
3fd3ab2d C |
603 | const query = { |
604 | where: { | |
1acb9475 | 605 | id |
d48ff09d | 606 | } |
3fd3ab2d | 607 | } |
9bd26629 | 608 | |
ac0868bc | 609 | return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query) |
feb4bdfd C |
610 | } |
611 | ||
b49f22d8 | 612 | static loadByEmail (email: string): Promise<MUserDefault> { |
ecb4e35f C |
613 | const query = { |
614 | where: { | |
615 | ||
616 | } | |
617 | } | |
618 | ||
619 | return UserModel.findOne(query) | |
620 | } | |
621 | ||
b49f22d8 | 622 | static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> { |
ba12e8b3 C |
623 | if (!email) email = username |
624 | ||
3fd3ab2d | 625 | const query = { |
3fd3ab2d | 626 | where: { |
a1587156 | 627 | [Op.or]: [ |
9d8ef212 | 628 | where(fn('lower', col('username')), fn('lower', username) as any), |
c4a1811e C |
629 | |
630 | { email } | |
631 | ] | |
3fd3ab2d | 632 | } |
6fcd19ba | 633 | } |
69b0a27c | 634 | |
d48ff09d | 635 | return UserModel.findOne(query) |
72c7248b C |
636 | } |
637 | ||
b49f22d8 | 638 | static loadByVideoId (videoId: number): Promise<MUserDefault> { |
cef534ed C |
639 | const query = { |
640 | include: [ | |
641 | { | |
642 | required: true, | |
643 | attributes: [ 'id' ], | |
644 | model: AccountModel.unscoped(), | |
645 | include: [ | |
646 | { | |
647 | required: true, | |
648 | attributes: [ 'id' ], | |
649 | model: VideoChannelModel.unscoped(), | |
650 | include: [ | |
651 | { | |
652 | required: true, | |
653 | attributes: [ 'id' ], | |
654 | model: VideoModel.unscoped(), | |
655 | where: { | |
656 | id: videoId | |
657 | } | |
658 | } | |
659 | ] | |
660 | } | |
661 | ] | |
662 | } | |
663 | ] | |
664 | } | |
665 | ||
666 | return UserModel.findOne(query) | |
667 | } | |
668 | ||
b49f22d8 | 669 | static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> { |
dc133480 C |
670 | const query = { |
671 | include: [ | |
672 | { | |
673 | required: true, | |
674 | attributes: [ 'id' ], | |
675 | model: VideoImportModel.unscoped(), | |
676 | where: { | |
677 | id: videoImportId | |
678 | } | |
679 | } | |
680 | ] | |
681 | } | |
682 | ||
683 | return UserModel.findOne(query) | |
684 | } | |
685 | ||
b49f22d8 | 686 | static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> { |
f7cc67b4 C |
687 | const query = { |
688 | include: [ | |
689 | { | |
690 | required: true, | |
691 | attributes: [ 'id' ], | |
692 | model: AccountModel.unscoped(), | |
693 | include: [ | |
694 | { | |
695 | required: true, | |
696 | attributes: [ 'id' ], | |
697 | model: VideoChannelModel.unscoped(), | |
698 | where: { | |
699 | actorId: videoChannelActorId | |
700 | } | |
701 | } | |
702 | ] | |
703 | } | |
704 | ] | |
705 | } | |
706 | ||
707 | return UserModel.findOne(query) | |
708 | } | |
709 | ||
b49f22d8 | 710 | static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> { |
f7cc67b4 C |
711 | const query = { |
712 | include: [ | |
713 | { | |
714 | required: true, | |
715 | attributes: [ 'id' ], | |
716 | model: AccountModel.unscoped(), | |
717 | where: { | |
718 | actorId: accountActorId | |
719 | } | |
720 | } | |
721 | ] | |
722 | } | |
723 | ||
724 | return UserModel.findOne(query) | |
725 | } | |
726 | ||
b49f22d8 | 727 | static loadByLiveId (liveId: number): Promise<MUser> { |
fb719404 C |
728 | const query = { |
729 | include: [ | |
730 | { | |
731 | attributes: [ 'id' ], | |
732 | model: AccountModel.unscoped(), | |
733 | required: true, | |
734 | include: [ | |
735 | { | |
736 | attributes: [ 'id' ], | |
737 | model: VideoChannelModel.unscoped(), | |
738 | required: true, | |
739 | include: [ | |
740 | { | |
741 | attributes: [ 'id' ], | |
742 | model: VideoModel.unscoped(), | |
743 | required: true, | |
744 | include: [ | |
745 | { | |
31c82cd9 | 746 | attributes: [], |
fb719404 C |
747 | model: VideoLiveModel.unscoped(), |
748 | required: true, | |
749 | where: { | |
750 | id: liveId | |
751 | } | |
752 | } | |
753 | ] | |
754 | } | |
755 | ] | |
756 | } | |
757 | ] | |
758 | } | |
759 | ] | |
760 | } | |
761 | ||
31c82cd9 | 762 | return UserModel.unscoped().findOne(query) |
fb719404 C |
763 | } |
764 | ||
765 | static generateUserQuotaBaseSQL (options: { | |
766 | whereUserId: '$userId' | '"UserModel"."id"' | |
767 | withSelect: boolean | |
9a82ce24 | 768 | daily: boolean |
fb719404 | 769 | }) { |
9a82ce24 C |
770 | const andWhere = options.daily === true |
771 | ? 'AND "video"."createdAt" > now() - interval \'24 hours\'' | |
fb719404 C |
772 | : '' |
773 | ||
774 | const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
775 | 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' + | |
776 | `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}` | |
777 | ||
778 | const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
779 | 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' + | |
780 | videoChannelJoin | |
781 | ||
782 | const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
783 | 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' + | |
784 | 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' + | |
785 | videoChannelJoin | |
bee0abff | 786 | |
fb719404 C |
787 | return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' + |
788 | 'FROM (' + | |
789 | `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` + | |
790 | 'GROUP BY "t1"."videoId"' + | |
791 | ') t2' | |
bee0abff FA |
792 | } |
793 | ||
fb719404 C |
794 | static getTotalRawQuery (query: string, userId: number) { |
795 | const options = { | |
796 | bind: { userId }, | |
797 | type: QueryTypes.SELECT as QueryTypes.SELECT | |
798 | } | |
799 | ||
800 | return UserModel.sequelize.query<{ total: string }>(query, options) | |
801 | .then(([ { total } ]) => { | |
802 | if (total === null) return 0 | |
68a3b9f2 | 803 | |
fb719404 C |
804 | return parseInt(total, 10) |
805 | }) | |
72c7248b C |
806 | } |
807 | ||
09cababd | 808 | static async getStats () { |
3cc665f4 C |
809 | function getActiveUsers (days: number) { |
810 | const query = { | |
811 | where: { | |
812 | [Op.and]: [ | |
813 | literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`) | |
814 | ] | |
815 | } | |
816 | } | |
817 | ||
5e0dbb3e | 818 | return UserModel.unscoped().count(query) |
3cc665f4 C |
819 | } |
820 | ||
5e0dbb3e | 821 | const totalUsers = await UserModel.unscoped().count() |
3cc665f4 C |
822 | const totalDailyActiveUsers = await getActiveUsers(1) |
823 | const totalWeeklyActiveUsers = await getActiveUsers(7) | |
824 | const totalMonthlyActiveUsers = await getActiveUsers(30) | |
47d8e266 | 825 | const totalHalfYearActiveUsers = await getActiveUsers(180) |
09cababd C |
826 | |
827 | return { | |
3cc665f4 C |
828 | totalUsers, |
829 | totalDailyActiveUsers, | |
830 | totalWeeklyActiveUsers, | |
47d8e266 C |
831 | totalMonthlyActiveUsers, |
832 | totalHalfYearActiveUsers | |
09cababd C |
833 | } |
834 | } | |
835 | ||
5cf84858 C |
836 | static autoComplete (search: string) { |
837 | const query = { | |
838 | where: { | |
839 | username: { | |
a1587156 | 840 | [Op.like]: `%${search}%` |
5cf84858 C |
841 | } |
842 | }, | |
843 | limit: 10 | |
844 | } | |
845 | ||
846 | return UserModel.findAll(query) | |
847 | .then(u => u.map(u => u.username)) | |
848 | } | |
849 | ||
3fd3ab2d C |
850 | hasRight (right: UserRight) { |
851 | return hasUserRight(this.role, right) | |
852 | } | |
72c7248b | 853 | |
1eddc9a7 C |
854 | hasAdminFlag (flag: UserAdminFlag) { |
855 | return this.adminFlags & flag | |
856 | } | |
857 | ||
3fd3ab2d C |
858 | isPasswordMatch (password: string) { |
859 | return comparePassword(password, this.password) | |
feb4bdfd C |
860 | } |
861 | ||
ac0868bc | 862 | toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User { |
a76138ff | 863 | const videoQuotaUsed = this.get('videoQuotaUsed') |
bee0abff | 864 | const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily') |
76314386 | 865 | const videosCount = this.get('videosCount') |
4f32032f C |
866 | const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':') |
867 | const abusesCreatedCount = this.get('abusesCreatedCount') | |
76314386 | 868 | const videoCommentsCount = this.get('videoCommentsCount') |
a76138ff | 869 | |
ac0868bc | 870 | const json: User = { |
3fd3ab2d C |
871 | id: this.id, |
872 | username: this.username, | |
873 | email: this.email, | |
43d0ea7f C |
874 | theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME), |
875 | ||
d1ab89de | 876 | pendingEmail: this.pendingEmail, |
d9eaee39 | 877 | emailVerified: this.emailVerified, |
43d0ea7f | 878 | |
0883b324 | 879 | nsfwPolicy: this.nsfwPolicy, |
a9bfa85d C |
880 | |
881 | // FIXME: deprecated in 4.1 | |
882 | webTorrentEnabled: this.p2pEnabled, | |
883 | p2pEnabled: this.p2pEnabled, | |
884 | ||
276d9652 | 885 | videosHistoryEnabled: this.videosHistoryEnabled, |
7efe153b | 886 | autoPlayVideo: this.autoPlayVideo, |
6aa54148 | 887 | autoPlayNextVideo: this.autoPlayNextVideo, |
bee29df8 | 888 | autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist, |
3caf77d3 | 889 | videoLanguages: this.videoLanguages, |
43d0ea7f | 890 | |
3fd3ab2d | 891 | role: this.role, |
a1587156 | 892 | roleLabel: USER_ROLE_LABELS[this.role], |
43d0ea7f | 893 | |
3fd3ab2d | 894 | videoQuota: this.videoQuota, |
bee0abff | 895 | videoQuotaDaily: this.videoQuotaDaily, |
9a82ce24 | 896 | |
43d0ea7f | 897 | videoQuotaUsed: videoQuotaUsed !== undefined |
9a82ce24 | 898 | ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id) |
43d0ea7f | 899 | : undefined, |
9a82ce24 | 900 | |
43d0ea7f | 901 | videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined |
9a82ce24 | 902 | ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id) |
43d0ea7f | 903 | : undefined, |
9a82ce24 | 904 | |
76314386 RK |
905 | videosCount: videosCount !== undefined |
906 | ? parseInt(videosCount + '', 10) | |
907 | : undefined, | |
4f32032f C |
908 | abusesCount: abusesCount |
909 | ? parseInt(abusesCount, 10) | |
76314386 | 910 | : undefined, |
4f32032f C |
911 | abusesAcceptedCount: abusesAcceptedCount |
912 | ? parseInt(abusesAcceptedCount, 10) | |
76314386 | 913 | : undefined, |
4f32032f C |
914 | abusesCreatedCount: abusesCreatedCount !== undefined |
915 | ? parseInt(abusesCreatedCount + '', 10) | |
76314386 RK |
916 | : undefined, |
917 | videoCommentsCount: videoCommentsCount !== undefined | |
918 | ? parseInt(videoCommentsCount + '', 10) | |
919 | : undefined, | |
43d0ea7f C |
920 | |
921 | noInstanceConfigWarningModal: this.noInstanceConfigWarningModal, | |
922 | noWelcomeModal: this.noWelcomeModal, | |
8f581725 | 923 | noAccountSetupWarningModal: this.noAccountSetupWarningModal, |
43d0ea7f | 924 | |
eacb25c4 C |
925 | blocked: this.blocked, |
926 | blockedReason: this.blockedReason, | |
43d0ea7f | 927 | |
c5911fd3 | 928 | account: this.Account.toFormattedJSON(), |
43d0ea7f C |
929 | |
930 | notificationSettings: this.NotificationSetting | |
931 | ? this.NotificationSetting.toFormattedJSON() | |
932 | : undefined, | |
933 | ||
a76138ff | 934 | videoChannels: [], |
43d0ea7f | 935 | |
8bb71f2e C |
936 | createdAt: this.createdAt, |
937 | ||
3cc665f4 C |
938 | pluginAuth: this.pluginAuth, |
939 | ||
940 | lastLoginDate: this.lastLoginDate | |
3fd3ab2d C |
941 | } |
942 | ||
1eddc9a7 C |
943 | if (parameters.withAdminFlags) { |
944 | Object.assign(json, { adminFlags: this.adminFlags }) | |
945 | } | |
946 | ||
3fd3ab2d | 947 | if (Array.isArray(this.Account.VideoChannels) === true) { |
c5911fd3 | 948 | json.videoChannels = this.Account.VideoChannels |
a1587156 C |
949 | .map(c => c.toFormattedJSON()) |
950 | .sort((v1, v2) => { | |
951 | if (v1.createdAt < v2.createdAt) return -1 | |
952 | if (v1.createdAt === v2.createdAt) return 0 | |
ad4a8a1c | 953 | |
a1587156 C |
954 | return 1 |
955 | }) | |
ad4a8a1c | 956 | } |
3fd3ab2d C |
957 | |
958 | return json | |
ad4a8a1c C |
959 | } |
960 | ||
ac0868bc | 961 | toMeFormattedJSON (this: MMyUserFormattable): MyUser { |
4e1592da | 962 | const formatted = this.toFormattedJSON({ withAdminFlags: true }) |
ac0868bc C |
963 | |
964 | const specialPlaylists = this.Account.VideoPlaylists | |
a1587156 | 965 | .map(p => ({ id: p.id, name: p.name, type: p.type })) |
ac0868bc C |
966 | |
967 | return Object.assign(formatted, { specialPlaylists }) | |
968 | } | |
b0f9f39e | 969 | } |