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