]>
Commit | Line | Data |
---|---|---|
1 | import { values } from 'lodash' | |
2 | import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize' | |
3 | import { | |
4 | AfterDestroy, | |
5 | AfterUpdate, | |
6 | AllowNull, | |
7 | BeforeCreate, | |
8 | BeforeUpdate, | |
9 | Column, | |
10 | CreatedAt, | |
11 | DataType, | |
12 | Default, | |
13 | DefaultScope, | |
14 | HasMany, | |
15 | HasOne, | |
16 | Is, | |
17 | IsEmail, | |
18 | IsUUID, | |
19 | Model, | |
20 | Scopes, | |
21 | Table, | |
22 | UpdatedAt | |
23 | } from 'sequelize-typescript' | |
24 | import { TokensCache } from '@server/lib/auth/tokens-cache' | |
25 | import { | |
26 | MMyUserFormattable, | |
27 | MUser, | |
28 | MUserDefault, | |
29 | MUserFormattable, | |
30 | MUserNotifSettingChannelDefault, | |
31 | MUserWithNotificationSetting, | |
32 | MVideoWithRights | |
33 | } from '@server/types/models' | |
34 | import { AttributesOnly } from '@shared/typescript-utils' | |
35 | import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users' | |
36 | import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } 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 | isUserUsernameValid, | |
55 | isUserVideoLanguages, | |
56 | isUserVideoQuotaDailyValid, | |
57 | isUserVideoQuotaValid, | |
58 | isUserVideosHistoryEnabledValid | |
59 | } from '../../helpers/custom-validators/users' | |
60 | import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto' | |
61 | import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants' | |
62 | import { getThemeOrDefault } from '../../lib/plugins/theme-utils' | |
63 | import { AccountModel } from '../account/account' | |
64 | import { ActorModel } from '../actor/actor' | |
65 | import { ActorFollowModel } from '../actor/actor-follow' | |
66 | import { ActorImageModel } from '../actor/actor-image' | |
67 | import { OAuthTokenModel } from '../oauth/oauth-token' | |
68 | import { getSort, throwIfNotValid } from '../utils' | |
69 | import { VideoModel } from '../video/video' | |
70 | import { VideoChannelModel } from '../video/video-channel' | |
71 | import { VideoImportModel } from '../video/video-import' | |
72 | import { VideoLiveModel } from '../video/video-live' | |
73 | import { VideoPlaylistModel } from '../video/video-playlist' | |
74 | import { UserNotificationSettingModel } from './user-notification-setting' | |
75 | import { LiveQuotaStore } from '@server/lib/live' | |
76 | import { logger } from '@server/helpers/logger' | |
77 | ||
78 | enum ScopeNames { | |
79 | FOR_ME_API = 'FOR_ME_API', | |
80 | WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS', | |
81 | WITH_QUOTA = 'WITH_QUOTA', | |
82 | WITH_STATS = 'WITH_STATS' | |
83 | } | |
84 | ||
85 | @DefaultScope(() => ({ | |
86 | include: [ | |
87 | { | |
88 | model: AccountModel, | |
89 | required: true | |
90 | }, | |
91 | { | |
92 | model: UserNotificationSettingModel, | |
93 | required: true | |
94 | } | |
95 | ] | |
96 | })) | |
97 | @Scopes(() => ({ | |
98 | [ScopeNames.FOR_ME_API]: { | |
99 | include: [ | |
100 | { | |
101 | model: AccountModel, | |
102 | include: [ | |
103 | { | |
104 | model: VideoChannelModel.unscoped(), | |
105 | include: [ | |
106 | { | |
107 | model: ActorModel, | |
108 | required: true, | |
109 | include: [ | |
110 | { | |
111 | model: ActorImageModel, | |
112 | as: 'Banners', | |
113 | required: false | |
114 | } | |
115 | ] | |
116 | } | |
117 | ] | |
118 | }, | |
119 | { | |
120 | attributes: [ 'id', 'name', 'type' ], | |
121 | model: VideoPlaylistModel.unscoped(), | |
122 | required: true, | |
123 | where: { | |
124 | type: { | |
125 | [Op.ne]: VideoPlaylistType.REGULAR | |
126 | } | |
127 | } | |
128 | } | |
129 | ] | |
130 | }, | |
131 | { | |
132 | model: UserNotificationSettingModel, | |
133 | required: true | |
134 | } | |
135 | ] | |
136 | }, | |
137 | [ScopeNames.WITH_VIDEOCHANNELS]: { | |
138 | include: [ | |
139 | { | |
140 | model: AccountModel, | |
141 | include: [ | |
142 | { | |
143 | model: VideoChannelModel | |
144 | }, | |
145 | { | |
146 | attributes: [ 'id', 'name', 'type' ], | |
147 | model: VideoPlaylistModel.unscoped(), | |
148 | required: true, | |
149 | where: { | |
150 | type: { | |
151 | [Op.ne]: VideoPlaylistType.REGULAR | |
152 | } | |
153 | } | |
154 | } | |
155 | ] | |
156 | } | |
157 | ] | |
158 | }, | |
159 | [ScopeNames.WITH_QUOTA]: { | |
160 | attributes: { | |
161 | include: [ | |
162 | [ | |
163 | literal( | |
164 | '(' + | |
165 | UserModel.generateUserQuotaBaseSQL({ | |
166 | withSelect: false, | |
167 | whereUserId: '"UserModel"."id"', | |
168 | daily: false | |
169 | }) + | |
170 | ')' | |
171 | ), | |
172 | 'videoQuotaUsed' | |
173 | ], | |
174 | [ | |
175 | literal( | |
176 | '(' + | |
177 | UserModel.generateUserQuotaBaseSQL({ | |
178 | withSelect: false, | |
179 | whereUserId: '"UserModel"."id"', | |
180 | daily: true | |
181 | }) + | |
182 | ')' | |
183 | ), | |
184 | 'videoQuotaUsedDaily' | |
185 | ] | |
186 | ] | |
187 | } | |
188 | }, | |
189 | [ScopeNames.WITH_STATS]: { | |
190 | attributes: { | |
191 | include: [ | |
192 | [ | |
193 | literal( | |
194 | '(' + | |
195 | 'SELECT COUNT("video"."id") ' + | |
196 | 'FROM "video" ' + | |
197 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
198 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
199 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
200 | ')' | |
201 | ), | |
202 | 'videosCount' | |
203 | ], | |
204 | [ | |
205 | literal( | |
206 | '(' + | |
207 | `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` + | |
208 | 'FROM (' + | |
209 | 'SELECT COUNT("abuse"."id") AS "abuses", ' + | |
210 | `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` + | |
211 | 'FROM "abuse" ' + | |
212 | 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' + | |
213 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
214 | ') t' + | |
215 | ')' | |
216 | ), | |
217 | 'abusesCount' | |
218 | ], | |
219 | [ | |
220 | literal( | |
221 | '(' + | |
222 | 'SELECT COUNT("abuse"."id") ' + | |
223 | 'FROM "abuse" ' + | |
224 | 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' + | |
225 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
226 | ')' | |
227 | ), | |
228 | 'abusesCreatedCount' | |
229 | ], | |
230 | [ | |
231 | literal( | |
232 | '(' + | |
233 | 'SELECT COUNT("videoComment"."id") ' + | |
234 | 'FROM "videoComment" ' + | |
235 | 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' + | |
236 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
237 | ')' | |
238 | ), | |
239 | 'videoCommentsCount' | |
240 | ] | |
241 | ] | |
242 | } | |
243 | } | |
244 | })) | |
245 | @Table({ | |
246 | tableName: 'user', | |
247 | indexes: [ | |
248 | { | |
249 | fields: [ 'username' ], | |
250 | unique: true | |
251 | }, | |
252 | { | |
253 | fields: [ 'email' ], | |
254 | unique: true | |
255 | } | |
256 | ] | |
257 | }) | |
258 | export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> { | |
259 | ||
260 | @AllowNull(true) | |
261 | @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true)) | |
262 | @Column | |
263 | password: string | |
264 | ||
265 | @AllowNull(false) | |
266 | @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name')) | |
267 | @Column | |
268 | username: string | |
269 | ||
270 | @AllowNull(false) | |
271 | @IsEmail | |
272 | @Column(DataType.STRING(400)) | |
273 | email: string | |
274 | ||
275 | @AllowNull(true) | |
276 | @IsEmail | |
277 | @Column(DataType.STRING(400)) | |
278 | pendingEmail: string | |
279 | ||
280 | @AllowNull(true) | |
281 | @Default(null) | |
282 | @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true)) | |
283 | @Column | |
284 | emailVerified: boolean | |
285 | ||
286 | @AllowNull(false) | |
287 | @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy')) | |
288 | @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES))) | |
289 | nsfwPolicy: NSFWPolicyType | |
290 | ||
291 | @AllowNull(false) | |
292 | @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled')) | |
293 | @Column | |
294 | p2pEnabled: boolean | |
295 | ||
296 | @AllowNull(false) | |
297 | @Default(true) | |
298 | @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled')) | |
299 | @Column | |
300 | videosHistoryEnabled: boolean | |
301 | ||
302 | @AllowNull(false) | |
303 | @Default(true) | |
304 | @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean')) | |
305 | @Column | |
306 | autoPlayVideo: boolean | |
307 | ||
308 | @AllowNull(false) | |
309 | @Default(false) | |
310 | @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean')) | |
311 | @Column | |
312 | autoPlayNextVideo: boolean | |
313 | ||
314 | @AllowNull(false) | |
315 | @Default(true) | |
316 | @Is( | |
317 | 'UserAutoPlayNextVideoPlaylist', | |
318 | value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean') | |
319 | ) | |
320 | @Column | |
321 | autoPlayNextVideoPlaylist: boolean | |
322 | ||
323 | @AllowNull(true) | |
324 | @Default(null) | |
325 | @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages')) | |
326 | @Column(DataType.ARRAY(DataType.STRING)) | |
327 | videoLanguages: string[] | |
328 | ||
329 | @AllowNull(false) | |
330 | @Default(UserAdminFlag.NONE) | |
331 | @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags')) | |
332 | @Column | |
333 | adminFlags?: UserAdminFlag | |
334 | ||
335 | @AllowNull(false) | |
336 | @Default(false) | |
337 | @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean')) | |
338 | @Column | |
339 | blocked: boolean | |
340 | ||
341 | @AllowNull(true) | |
342 | @Default(null) | |
343 | @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true)) | |
344 | @Column | |
345 | blockedReason: string | |
346 | ||
347 | @AllowNull(false) | |
348 | @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role')) | |
349 | @Column | |
350 | role: number | |
351 | ||
352 | @AllowNull(false) | |
353 | @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota')) | |
354 | @Column(DataType.BIGINT) | |
355 | videoQuota: number | |
356 | ||
357 | @AllowNull(false) | |
358 | @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily')) | |
359 | @Column(DataType.BIGINT) | |
360 | videoQuotaDaily: number | |
361 | ||
362 | @AllowNull(false) | |
363 | @Default(DEFAULT_USER_THEME_NAME) | |
364 | @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme')) | |
365 | @Column | |
366 | theme: string | |
367 | ||
368 | @AllowNull(false) | |
369 | @Default(false) | |
370 | @Is( | |
371 | 'UserNoInstanceConfigWarningModal', | |
372 | value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal') | |
373 | ) | |
374 | @Column | |
375 | noInstanceConfigWarningModal: boolean | |
376 | ||
377 | @AllowNull(false) | |
378 | @Default(false) | |
379 | @Is( | |
380 | 'UserNoWelcomeModal', | |
381 | value => throwIfNotValid(value, isUserNoModal, 'no welcome modal') | |
382 | ) | |
383 | @Column | |
384 | noWelcomeModal: boolean | |
385 | ||
386 | @AllowNull(false) | |
387 | @Default(false) | |
388 | @Is( | |
389 | 'UserNoAccountSetupWarningModal', | |
390 | value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal') | |
391 | ) | |
392 | @Column | |
393 | noAccountSetupWarningModal: boolean | |
394 | ||
395 | @AllowNull(true) | |
396 | @Default(null) | |
397 | @Column | |
398 | pluginAuth: string | |
399 | ||
400 | @AllowNull(false) | |
401 | @Default(DataType.UUIDV4) | |
402 | @IsUUID(4) | |
403 | @Column(DataType.UUID) | |
404 | feedToken: string | |
405 | ||
406 | @AllowNull(true) | |
407 | @Default(null) | |
408 | @Column | |
409 | lastLoginDate: Date | |
410 | ||
411 | @CreatedAt | |
412 | createdAt: Date | |
413 | ||
414 | @UpdatedAt | |
415 | updatedAt: Date | |
416 | ||
417 | @HasOne(() => AccountModel, { | |
418 | foreignKey: 'userId', | |
419 | onDelete: 'cascade', | |
420 | hooks: true | |
421 | }) | |
422 | Account: AccountModel | |
423 | ||
424 | @HasOne(() => UserNotificationSettingModel, { | |
425 | foreignKey: 'userId', | |
426 | onDelete: 'cascade', | |
427 | hooks: true | |
428 | }) | |
429 | NotificationSetting: UserNotificationSettingModel | |
430 | ||
431 | @HasMany(() => VideoImportModel, { | |
432 | foreignKey: 'userId', | |
433 | onDelete: 'cascade' | |
434 | }) | |
435 | VideoImports: VideoImportModel[] | |
436 | ||
437 | @HasMany(() => OAuthTokenModel, { | |
438 | foreignKey: 'userId', | |
439 | onDelete: 'cascade' | |
440 | }) | |
441 | OAuthTokens: OAuthTokenModel[] | |
442 | ||
443 | @BeforeCreate | |
444 | @BeforeUpdate | |
445 | static cryptPasswordIfNeeded (instance: UserModel) { | |
446 | if (instance.changed('password') && instance.password) { | |
447 | return cryptPassword(instance.password) | |
448 | .then(hash => { | |
449 | instance.password = hash | |
450 | return undefined | |
451 | }) | |
452 | } | |
453 | } | |
454 | ||
455 | @AfterUpdate | |
456 | @AfterDestroy | |
457 | static removeTokenCache (instance: UserModel) { | |
458 | return TokensCache.Instance.clearCacheByUserId(instance.id) | |
459 | } | |
460 | ||
461 | static countTotal () { | |
462 | return this.count() | |
463 | } | |
464 | ||
465 | static listForApi (parameters: { | |
466 | start: number | |
467 | count: number | |
468 | sort: string | |
469 | search?: string | |
470 | blocked?: boolean | |
471 | }) { | |
472 | const { start, count, sort, search, blocked } = parameters | |
473 | const where: WhereOptions = {} | |
474 | ||
475 | if (search) { | |
476 | Object.assign(where, { | |
477 | [Op.or]: [ | |
478 | { | |
479 | email: { | |
480 | [Op.iLike]: '%' + search + '%' | |
481 | } | |
482 | }, | |
483 | { | |
484 | username: { | |
485 | [Op.iLike]: '%' + search + '%' | |
486 | } | |
487 | } | |
488 | ] | |
489 | }) | |
490 | } | |
491 | ||
492 | if (blocked !== undefined) { | |
493 | Object.assign(where, { | |
494 | blocked: blocked | |
495 | }) | |
496 | } | |
497 | ||
498 | const query: FindOptions = { | |
499 | offset: start, | |
500 | limit: count, | |
501 | order: getSort(sort), | |
502 | where | |
503 | } | |
504 | ||
505 | return Promise.all([ | |
506 | UserModel.unscoped().count(query), | |
507 | UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query) | |
508 | ]).then(([ total, data ]) => ({ total, data })) | |
509 | } | |
510 | ||
511 | static listWithRight (right: UserRight): Promise<MUserDefault[]> { | |
512 | const roles = Object.keys(USER_ROLE_LABELS) | |
513 | .map(k => parseInt(k, 10) as UserRole) | |
514 | .filter(role => hasUserRight(role, right)) | |
515 | ||
516 | const query = { | |
517 | where: { | |
518 | role: { | |
519 | [Op.in]: roles | |
520 | } | |
521 | } | |
522 | } | |
523 | ||
524 | return UserModel.findAll(query) | |
525 | } | |
526 | ||
527 | static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> { | |
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 | { | |
540 | attributes: [], | |
541 | model: ActorModel.unscoped(), | |
542 | required: true, | |
543 | where: { | |
544 | serverId: null | |
545 | }, | |
546 | include: [ | |
547 | { | |
548 | attributes: [], | |
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) | |
564 | } | |
565 | ||
566 | static listByUsernames (usernames: string[]): Promise<MUserDefault[]> { | |
567 | const query = { | |
568 | where: { | |
569 | username: usernames | |
570 | } | |
571 | } | |
572 | ||
573 | return UserModel.findAll(query) | |
574 | } | |
575 | ||
576 | static loadById (id: number): Promise<MUser> { | |
577 | return UserModel.unscoped().findByPk(id) | |
578 | } | |
579 | ||
580 | static loadByIdFull (id: number): Promise<MUserDefault> { | |
581 | return UserModel.findByPk(id) | |
582 | } | |
583 | ||
584 | static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> { | |
585 | const scopes = [ | |
586 | ScopeNames.WITH_VIDEOCHANNELS | |
587 | ] | |
588 | ||
589 | if (withStats) { | |
590 | scopes.push(ScopeNames.WITH_QUOTA) | |
591 | scopes.push(ScopeNames.WITH_STATS) | |
592 | } | |
593 | ||
594 | return UserModel.scope(scopes).findByPk(id) | |
595 | } | |
596 | ||
597 | static loadByUsername (username: string): Promise<MUserDefault> { | |
598 | const query = { | |
599 | where: { | |
600 | username | |
601 | } | |
602 | } | |
603 | ||
604 | return UserModel.findOne(query) | |
605 | } | |
606 | ||
607 | static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> { | |
608 | const query = { | |
609 | where: { | |
610 | id | |
611 | } | |
612 | } | |
613 | ||
614 | return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query) | |
615 | } | |
616 | ||
617 | static loadByEmail (email: string): Promise<MUserDefault> { | |
618 | const query = { | |
619 | where: { | |
620 | ||
621 | } | |
622 | } | |
623 | ||
624 | return UserModel.findOne(query) | |
625 | } | |
626 | ||
627 | static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> { | |
628 | if (!email) email = username | |
629 | ||
630 | const query = { | |
631 | where: { | |
632 | [Op.or]: [ | |
633 | where(fn('lower', col('username')), fn('lower', username) as any), | |
634 | ||
635 | { email } | |
636 | ] | |
637 | } | |
638 | } | |
639 | ||
640 | return UserModel.findOne(query) | |
641 | } | |
642 | ||
643 | static loadByVideoId (videoId: number): Promise<MUserDefault> { | |
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 | ||
674 | static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> { | |
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 | ||
691 | static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> { | |
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 | ||
715 | static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> { | |
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 | ||
732 | static loadByLiveId (liveId: number): Promise<MUser> { | |
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 | { | |
751 | attributes: [], | |
752 | model: VideoLiveModel.unscoped(), | |
753 | required: true, | |
754 | where: { | |
755 | id: liveId | |
756 | } | |
757 | } | |
758 | ] | |
759 | } | |
760 | ] | |
761 | } | |
762 | ] | |
763 | } | |
764 | ] | |
765 | } | |
766 | ||
767 | return UserModel.unscoped().findOne(query) | |
768 | } | |
769 | ||
770 | static generateUserQuotaBaseSQL (options: { | |
771 | whereUserId: '$userId' | '"UserModel"."id"' | |
772 | withSelect: boolean | |
773 | daily: boolean | |
774 | }) { | |
775 | const andWhere = options.daily === true | |
776 | ? 'AND "video"."createdAt" > now() - interval \'24 hours\'' | |
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" ' + | |
784 | 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' + | |
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 ' + | |
789 | 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' + | |
790 | videoChannelJoin | |
791 | ||
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' | |
797 | } | |
798 | ||
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 | |
808 | ||
809 | return parseInt(total, 10) | |
810 | }) | |
811 | } | |
812 | ||
813 | static async getStats () { | |
814 | function getActiveUsers (days: number) { | |
815 | const query = { | |
816 | where: { | |
817 | [Op.and]: [ | |
818 | literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`) | |
819 | ] | |
820 | } | |
821 | } | |
822 | ||
823 | return UserModel.count(query) | |
824 | } | |
825 | ||
826 | const totalUsers = await UserModel.count() | |
827 | const totalDailyActiveUsers = await getActiveUsers(1) | |
828 | const totalWeeklyActiveUsers = await getActiveUsers(7) | |
829 | const totalMonthlyActiveUsers = await getActiveUsers(30) | |
830 | const totalHalfYearActiveUsers = await getActiveUsers(180) | |
831 | ||
832 | return { | |
833 | totalUsers, | |
834 | totalDailyActiveUsers, | |
835 | totalWeeklyActiveUsers, | |
836 | totalMonthlyActiveUsers, | |
837 | totalHalfYearActiveUsers | |
838 | } | |
839 | } | |
840 | ||
841 | static autoComplete (search: string) { | |
842 | const query = { | |
843 | where: { | |
844 | username: { | |
845 | [Op.like]: `%${search}%` | |
846 | } | |
847 | }, | |
848 | limit: 10 | |
849 | } | |
850 | ||
851 | return UserModel.findAll(query) | |
852 | .then(u => u.map(u => u.username)) | |
853 | } | |
854 | ||
855 | canGetVideo (video: MVideoWithRights) { | |
856 | const videoUserId = video.VideoChannel.Account.userId | |
857 | ||
858 | if (video.isBlacklisted()) { | |
859 | return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | |
860 | } | |
861 | ||
862 | if (video.privacy === VideoPrivacy.PRIVATE) { | |
863 | return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | |
864 | } | |
865 | ||
866 | if (video.privacy === VideoPrivacy.INTERNAL) return true | |
867 | ||
868 | return false | |
869 | } | |
870 | ||
871 | hasRight (right: UserRight) { | |
872 | return hasUserRight(this.role, right) | |
873 | } | |
874 | ||
875 | hasAdminFlag (flag: UserAdminFlag) { | |
876 | return this.adminFlags & flag | |
877 | } | |
878 | ||
879 | isPasswordMatch (password: string) { | |
880 | return comparePassword(password, this.password) | |
881 | } | |
882 | ||
883 | toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User { | |
884 | const videoQuotaUsed = this.get('videoQuotaUsed') | |
885 | const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily') | |
886 | const videosCount = this.get('videosCount') | |
887 | const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':') | |
888 | const abusesCreatedCount = this.get('abusesCreatedCount') | |
889 | const videoCommentsCount = this.get('videoCommentsCount') | |
890 | ||
891 | const json: User = { | |
892 | id: this.id, | |
893 | username: this.username, | |
894 | email: this.email, | |
895 | theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME), | |
896 | ||
897 | pendingEmail: this.pendingEmail, | |
898 | emailVerified: this.emailVerified, | |
899 | ||
900 | nsfwPolicy: this.nsfwPolicy, | |
901 | ||
902 | // FIXME: deprecated in 4.1 | |
903 | webTorrentEnabled: this.p2pEnabled, | |
904 | p2pEnabled: this.p2pEnabled, | |
905 | ||
906 | videosHistoryEnabled: this.videosHistoryEnabled, | |
907 | autoPlayVideo: this.autoPlayVideo, | |
908 | autoPlayNextVideo: this.autoPlayNextVideo, | |
909 | autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist, | |
910 | videoLanguages: this.videoLanguages, | |
911 | ||
912 | role: this.role, | |
913 | roleLabel: USER_ROLE_LABELS[this.role], | |
914 | ||
915 | videoQuota: this.videoQuota, | |
916 | videoQuotaDaily: this.videoQuotaDaily, | |
917 | ||
918 | videoQuotaUsed: videoQuotaUsed !== undefined | |
919 | ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id) | |
920 | : undefined, | |
921 | ||
922 | videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined | |
923 | ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id) | |
924 | : undefined, | |
925 | ||
926 | videosCount: videosCount !== undefined | |
927 | ? parseInt(videosCount + '', 10) | |
928 | : undefined, | |
929 | abusesCount: abusesCount | |
930 | ? parseInt(abusesCount, 10) | |
931 | : undefined, | |
932 | abusesAcceptedCount: abusesAcceptedCount | |
933 | ? parseInt(abusesAcceptedCount, 10) | |
934 | : undefined, | |
935 | abusesCreatedCount: abusesCreatedCount !== undefined | |
936 | ? parseInt(abusesCreatedCount + '', 10) | |
937 | : undefined, | |
938 | videoCommentsCount: videoCommentsCount !== undefined | |
939 | ? parseInt(videoCommentsCount + '', 10) | |
940 | : undefined, | |
941 | ||
942 | noInstanceConfigWarningModal: this.noInstanceConfigWarningModal, | |
943 | noWelcomeModal: this.noWelcomeModal, | |
944 | noAccountSetupWarningModal: this.noAccountSetupWarningModal, | |
945 | ||
946 | blocked: this.blocked, | |
947 | blockedReason: this.blockedReason, | |
948 | ||
949 | account: this.Account.toFormattedJSON(), | |
950 | ||
951 | notificationSettings: this.NotificationSetting | |
952 | ? this.NotificationSetting.toFormattedJSON() | |
953 | : undefined, | |
954 | ||
955 | videoChannels: [], | |
956 | ||
957 | createdAt: this.createdAt, | |
958 | ||
959 | pluginAuth: this.pluginAuth, | |
960 | ||
961 | lastLoginDate: this.lastLoginDate | |
962 | } | |
963 | ||
964 | if (parameters.withAdminFlags) { | |
965 | Object.assign(json, { adminFlags: this.adminFlags }) | |
966 | } | |
967 | ||
968 | if (Array.isArray(this.Account.VideoChannels) === true) { | |
969 | json.videoChannels = this.Account.VideoChannels | |
970 | .map(c => c.toFormattedJSON()) | |
971 | .sort((v1, v2) => { | |
972 | if (v1.createdAt < v2.createdAt) return -1 | |
973 | if (v1.createdAt === v2.createdAt) return 0 | |
974 | ||
975 | return 1 | |
976 | }) | |
977 | } | |
978 | ||
979 | return json | |
980 | } | |
981 | ||
982 | toMeFormattedJSON (this: MMyUserFormattable): MyUser { | |
983 | const formatted = this.toFormattedJSON({ withAdminFlags: true }) | |
984 | ||
985 | const specialPlaylists = this.Account.VideoPlaylists | |
986 | .map(p => ({ id: p.id, name: p.name, type: p.type })) | |
987 | ||
988 | return Object.assign(formatted, { specialPlaylists }) | |
989 | } | |
990 | } |