]>
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/core-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 | isUserPasswordValid, | |
52 | isUserRoleValid, | |
53 | isUserUsernameValid, | |
54 | isUserVideoLanguages, | |
55 | isUserVideoQuotaDailyValid, | |
56 | isUserVideoQuotaValid, | |
57 | isUserVideosHistoryEnabledValid, | |
58 | isUserWebTorrentEnabledValid | |
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 | ||
76 | enum ScopeNames { | |
77 | FOR_ME_API = 'FOR_ME_API', | |
78 | WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS', | |
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: 'Banner', | |
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_STATS]: { | |
157 | attributes: { | |
158 | include: [ | |
159 | [ | |
160 | literal( | |
161 | '(' + | |
162 | UserModel.generateUserQuotaBaseSQL({ | |
163 | withSelect: false, | |
164 | whereUserId: '"UserModel"."id"' | |
165 | }) + | |
166 | ')' | |
167 | ), | |
168 | 'videoQuotaUsed' | |
169 | ], | |
170 | [ | |
171 | literal( | |
172 | '(' + | |
173 | 'SELECT COUNT("video"."id") ' + | |
174 | 'FROM "video" ' + | |
175 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
176 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
177 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
178 | ')' | |
179 | ), | |
180 | 'videosCount' | |
181 | ], | |
182 | [ | |
183 | literal( | |
184 | '(' + | |
185 | `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` + | |
186 | 'FROM (' + | |
187 | 'SELECT COUNT("abuse"."id") AS "abuses", ' + | |
188 | `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` + | |
189 | 'FROM "abuse" ' + | |
190 | 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' + | |
191 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
192 | ') t' + | |
193 | ')' | |
194 | ), | |
195 | 'abusesCount' | |
196 | ], | |
197 | [ | |
198 | literal( | |
199 | '(' + | |
200 | 'SELECT COUNT("abuse"."id") ' + | |
201 | 'FROM "abuse" ' + | |
202 | 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' + | |
203 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
204 | ')' | |
205 | ), | |
206 | 'abusesCreatedCount' | |
207 | ], | |
208 | [ | |
209 | literal( | |
210 | '(' + | |
211 | 'SELECT COUNT("videoComment"."id") ' + | |
212 | 'FROM "videoComment" ' + | |
213 | 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' + | |
214 | 'WHERE "account"."userId" = "UserModel"."id"' + | |
215 | ')' | |
216 | ), | |
217 | 'videoCommentsCount' | |
218 | ] | |
219 | ] | |
220 | } | |
221 | } | |
222 | })) | |
223 | @Table({ | |
224 | tableName: 'user', | |
225 | indexes: [ | |
226 | { | |
227 | fields: [ 'username' ], | |
228 | unique: true | |
229 | }, | |
230 | { | |
231 | fields: [ 'email' ], | |
232 | unique: true | |
233 | } | |
234 | ] | |
235 | }) | |
236 | export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> { | |
237 | ||
238 | @AllowNull(true) | |
239 | @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true)) | |
240 | @Column | |
241 | password: string | |
242 | ||
243 | @AllowNull(false) | |
244 | @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name')) | |
245 | @Column | |
246 | username: string | |
247 | ||
248 | @AllowNull(false) | |
249 | @IsEmail | |
250 | @Column(DataType.STRING(400)) | |
251 | email: string | |
252 | ||
253 | @AllowNull(true) | |
254 | @IsEmail | |
255 | @Column(DataType.STRING(400)) | |
256 | pendingEmail: string | |
257 | ||
258 | @AllowNull(true) | |
259 | @Default(null) | |
260 | @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true)) | |
261 | @Column | |
262 | emailVerified: boolean | |
263 | ||
264 | @AllowNull(false) | |
265 | @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy')) | |
266 | @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES))) | |
267 | nsfwPolicy: NSFWPolicyType | |
268 | ||
269 | @AllowNull(false) | |
270 | @Default(true) | |
271 | @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled')) | |
272 | @Column | |
273 | webTorrentEnabled: boolean | |
274 | ||
275 | @AllowNull(false) | |
276 | @Default(true) | |
277 | @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled')) | |
278 | @Column | |
279 | videosHistoryEnabled: boolean | |
280 | ||
281 | @AllowNull(false) | |
282 | @Default(true) | |
283 | @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean')) | |
284 | @Column | |
285 | autoPlayVideo: boolean | |
286 | ||
287 | @AllowNull(false) | |
288 | @Default(false) | |
289 | @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean')) | |
290 | @Column | |
291 | autoPlayNextVideo: boolean | |
292 | ||
293 | @AllowNull(false) | |
294 | @Default(true) | |
295 | @Is( | |
296 | 'UserAutoPlayNextVideoPlaylist', | |
297 | value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean') | |
298 | ) | |
299 | @Column | |
300 | autoPlayNextVideoPlaylist: boolean | |
301 | ||
302 | @AllowNull(true) | |
303 | @Default(null) | |
304 | @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages')) | |
305 | @Column(DataType.ARRAY(DataType.STRING)) | |
306 | videoLanguages: string[] | |
307 | ||
308 | @AllowNull(false) | |
309 | @Default(UserAdminFlag.NONE) | |
310 | @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags')) | |
311 | @Column | |
312 | adminFlags?: UserAdminFlag | |
313 | ||
314 | @AllowNull(false) | |
315 | @Default(false) | |
316 | @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean')) | |
317 | @Column | |
318 | blocked: boolean | |
319 | ||
320 | @AllowNull(true) | |
321 | @Default(null) | |
322 | @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true)) | |
323 | @Column | |
324 | blockedReason: string | |
325 | ||
326 | @AllowNull(false) | |
327 | @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role')) | |
328 | @Column | |
329 | role: number | |
330 | ||
331 | @AllowNull(false) | |
332 | @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota')) | |
333 | @Column(DataType.BIGINT) | |
334 | videoQuota: number | |
335 | ||
336 | @AllowNull(false) | |
337 | @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily')) | |
338 | @Column(DataType.BIGINT) | |
339 | videoQuotaDaily: number | |
340 | ||
341 | @AllowNull(false) | |
342 | @Default(DEFAULT_USER_THEME_NAME) | |
343 | @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme')) | |
344 | @Column | |
345 | theme: string | |
346 | ||
347 | @AllowNull(false) | |
348 | @Default(false) | |
349 | @Is( | |
350 | 'UserNoInstanceConfigWarningModal', | |
351 | value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal') | |
352 | ) | |
353 | @Column | |
354 | noInstanceConfigWarningModal: boolean | |
355 | ||
356 | @AllowNull(false) | |
357 | @Default(false) | |
358 | @Is( | |
359 | 'UserNoWelcomeModal', | |
360 | value => throwIfNotValid(value, isUserNoModal, 'no welcome modal') | |
361 | ) | |
362 | @Column | |
363 | noWelcomeModal: boolean | |
364 | ||
365 | @AllowNull(false) | |
366 | @Default(false) | |
367 | @Is( | |
368 | 'UserNoAccountSetupWarningModal', | |
369 | value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal') | |
370 | ) | |
371 | @Column | |
372 | noAccountSetupWarningModal: boolean | |
373 | ||
374 | @AllowNull(true) | |
375 | @Default(null) | |
376 | @Column | |
377 | pluginAuth: string | |
378 | ||
379 | @AllowNull(false) | |
380 | @Default(DataType.UUIDV4) | |
381 | @IsUUID(4) | |
382 | @Column(DataType.UUID) | |
383 | feedToken: string | |
384 | ||
385 | @AllowNull(true) | |
386 | @Default(null) | |
387 | @Column | |
388 | lastLoginDate: Date | |
389 | ||
390 | @CreatedAt | |
391 | createdAt: Date | |
392 | ||
393 | @UpdatedAt | |
394 | updatedAt: Date | |
395 | ||
396 | @HasOne(() => AccountModel, { | |
397 | foreignKey: 'userId', | |
398 | onDelete: 'cascade', | |
399 | hooks: true | |
400 | }) | |
401 | Account: AccountModel | |
402 | ||
403 | @HasOne(() => UserNotificationSettingModel, { | |
404 | foreignKey: 'userId', | |
405 | onDelete: 'cascade', | |
406 | hooks: true | |
407 | }) | |
408 | NotificationSetting: UserNotificationSettingModel | |
409 | ||
410 | @HasMany(() => VideoImportModel, { | |
411 | foreignKey: 'userId', | |
412 | onDelete: 'cascade' | |
413 | }) | |
414 | VideoImports: VideoImportModel[] | |
415 | ||
416 | @HasMany(() => OAuthTokenModel, { | |
417 | foreignKey: 'userId', | |
418 | onDelete: 'cascade' | |
419 | }) | |
420 | OAuthTokens: OAuthTokenModel[] | |
421 | ||
422 | @BeforeCreate | |
423 | @BeforeUpdate | |
424 | static cryptPasswordIfNeeded (instance: UserModel) { | |
425 | if (instance.changed('password') && instance.password) { | |
426 | return cryptPassword(instance.password) | |
427 | .then(hash => { | |
428 | instance.password = hash | |
429 | return undefined | |
430 | }) | |
431 | } | |
432 | } | |
433 | ||
434 | @AfterUpdate | |
435 | @AfterDestroy | |
436 | static removeTokenCache (instance: UserModel) { | |
437 | return TokensCache.Instance.clearCacheByUserId(instance.id) | |
438 | } | |
439 | ||
440 | static countTotal () { | |
441 | return this.count() | |
442 | } | |
443 | ||
444 | static listForApi (parameters: { | |
445 | start: number | |
446 | count: number | |
447 | sort: string | |
448 | search?: string | |
449 | blocked?: boolean | |
450 | }) { | |
451 | const { start, count, sort, search, blocked } = parameters | |
452 | const where: WhereOptions = {} | |
453 | ||
454 | if (search) { | |
455 | Object.assign(where, { | |
456 | [Op.or]: [ | |
457 | { | |
458 | email: { | |
459 | [Op.iLike]: '%' + search + '%' | |
460 | } | |
461 | }, | |
462 | { | |
463 | username: { | |
464 | [Op.iLike]: '%' + search + '%' | |
465 | } | |
466 | } | |
467 | ] | |
468 | }) | |
469 | } | |
470 | ||
471 | if (blocked !== undefined) { | |
472 | Object.assign(where, { | |
473 | blocked: blocked | |
474 | }) | |
475 | } | |
476 | ||
477 | const query: FindOptions = { | |
478 | attributes: { | |
479 | include: [ | |
480 | [ | |
481 | literal( | |
482 | '(' + | |
483 | UserModel.generateUserQuotaBaseSQL({ | |
484 | withSelect: false, | |
485 | whereUserId: '"UserModel"."id"' | |
486 | }) + | |
487 | ')' | |
488 | ), | |
489 | 'videoQuotaUsed' | |
490 | ] | |
491 | ] | |
492 | }, | |
493 | offset: start, | |
494 | limit: count, | |
495 | order: getSort(sort), | |
496 | where | |
497 | } | |
498 | ||
499 | return UserModel.findAndCountAll(query) | |
500 | .then(({ rows, count }) => { | |
501 | return { | |
502 | data: rows, | |
503 | total: count | |
504 | } | |
505 | }) | |
506 | } | |
507 | ||
508 | static listWithRight (right: UserRight): Promise<MUserDefault[]> { | |
509 | const roles = Object.keys(USER_ROLE_LABELS) | |
510 | .map(k => parseInt(k, 10) as UserRole) | |
511 | .filter(role => hasUserRight(role, right)) | |
512 | ||
513 | const query = { | |
514 | where: { | |
515 | role: { | |
516 | [Op.in]: roles | |
517 | } | |
518 | } | |
519 | } | |
520 | ||
521 | return UserModel.findAll(query) | |
522 | } | |
523 | ||
524 | static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> { | |
525 | const query = { | |
526 | include: [ | |
527 | { | |
528 | model: UserNotificationSettingModel.unscoped(), | |
529 | required: true | |
530 | }, | |
531 | { | |
532 | attributes: [ 'userId' ], | |
533 | model: AccountModel.unscoped(), | |
534 | required: true, | |
535 | include: [ | |
536 | { | |
537 | attributes: [], | |
538 | model: ActorModel.unscoped(), | |
539 | required: true, | |
540 | where: { | |
541 | serverId: null | |
542 | }, | |
543 | include: [ | |
544 | { | |
545 | attributes: [], | |
546 | as: 'ActorFollowings', | |
547 | model: ActorFollowModel.unscoped(), | |
548 | required: true, | |
549 | where: { | |
550 | targetActorId: actorId | |
551 | } | |
552 | } | |
553 | ] | |
554 | } | |
555 | ] | |
556 | } | |
557 | ] | |
558 | } | |
559 | ||
560 | return UserModel.unscoped().findAll(query) | |
561 | } | |
562 | ||
563 | static listByUsernames (usernames: string[]): Promise<MUserDefault[]> { | |
564 | const query = { | |
565 | where: { | |
566 | username: usernames | |
567 | } | |
568 | } | |
569 | ||
570 | return UserModel.findAll(query) | |
571 | } | |
572 | ||
573 | static loadById (id: number): Promise<MUser> { | |
574 | return UserModel.unscoped().findByPk(id) | |
575 | } | |
576 | ||
577 | static loadByIdFull (id: number): Promise<MUserDefault> { | |
578 | return UserModel.findByPk(id) | |
579 | } | |
580 | ||
581 | static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> { | |
582 | const scopes = [ | |
583 | ScopeNames.WITH_VIDEOCHANNELS | |
584 | ] | |
585 | ||
586 | if (withStats) scopes.push(ScopeNames.WITH_STATS) | |
587 | ||
588 | return UserModel.scope(scopes).findByPk(id) | |
589 | } | |
590 | ||
591 | static loadByUsername (username: string): Promise<MUserDefault> { | |
592 | const query = { | |
593 | where: { | |
594 | username | |
595 | } | |
596 | } | |
597 | ||
598 | return UserModel.findOne(query) | |
599 | } | |
600 | ||
601 | static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> { | |
602 | const query = { | |
603 | where: { | |
604 | id | |
605 | } | |
606 | } | |
607 | ||
608 | return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query) | |
609 | } | |
610 | ||
611 | static loadByEmail (email: string): Promise<MUserDefault> { | |
612 | const query = { | |
613 | where: { | |
614 | ||
615 | } | |
616 | } | |
617 | ||
618 | return UserModel.findOne(query) | |
619 | } | |
620 | ||
621 | static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> { | |
622 | if (!email) email = username | |
623 | ||
624 | const query = { | |
625 | where: { | |
626 | [Op.or]: [ | |
627 | where(fn('lower', col('username')), fn('lower', username)), | |
628 | ||
629 | { email } | |
630 | ] | |
631 | } | |
632 | } | |
633 | ||
634 | return UserModel.findOne(query) | |
635 | } | |
636 | ||
637 | static loadByVideoId (videoId: number): Promise<MUserDefault> { | |
638 | const query = { | |
639 | include: [ | |
640 | { | |
641 | required: true, | |
642 | attributes: [ 'id' ], | |
643 | model: AccountModel.unscoped(), | |
644 | include: [ | |
645 | { | |
646 | required: true, | |
647 | attributes: [ 'id' ], | |
648 | model: VideoChannelModel.unscoped(), | |
649 | include: [ | |
650 | { | |
651 | required: true, | |
652 | attributes: [ 'id' ], | |
653 | model: VideoModel.unscoped(), | |
654 | where: { | |
655 | id: videoId | |
656 | } | |
657 | } | |
658 | ] | |
659 | } | |
660 | ] | |
661 | } | |
662 | ] | |
663 | } | |
664 | ||
665 | return UserModel.findOne(query) | |
666 | } | |
667 | ||
668 | static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> { | |
669 | const query = { | |
670 | include: [ | |
671 | { | |
672 | required: true, | |
673 | attributes: [ 'id' ], | |
674 | model: VideoImportModel.unscoped(), | |
675 | where: { | |
676 | id: videoImportId | |
677 | } | |
678 | } | |
679 | ] | |
680 | } | |
681 | ||
682 | return UserModel.findOne(query) | |
683 | } | |
684 | ||
685 | static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> { | |
686 | const query = { | |
687 | include: [ | |
688 | { | |
689 | required: true, | |
690 | attributes: [ 'id' ], | |
691 | model: AccountModel.unscoped(), | |
692 | include: [ | |
693 | { | |
694 | required: true, | |
695 | attributes: [ 'id' ], | |
696 | model: VideoChannelModel.unscoped(), | |
697 | where: { | |
698 | actorId: videoChannelActorId | |
699 | } | |
700 | } | |
701 | ] | |
702 | } | |
703 | ] | |
704 | } | |
705 | ||
706 | return UserModel.findOne(query) | |
707 | } | |
708 | ||
709 | static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> { | |
710 | const query = { | |
711 | include: [ | |
712 | { | |
713 | required: true, | |
714 | attributes: [ 'id' ], | |
715 | model: AccountModel.unscoped(), | |
716 | where: { | |
717 | actorId: accountActorId | |
718 | } | |
719 | } | |
720 | ] | |
721 | } | |
722 | ||
723 | return UserModel.findOne(query) | |
724 | } | |
725 | ||
726 | static loadByLiveId (liveId: number): Promise<MUser> { | |
727 | const query = { | |
728 | include: [ | |
729 | { | |
730 | attributes: [ 'id' ], | |
731 | model: AccountModel.unscoped(), | |
732 | required: true, | |
733 | include: [ | |
734 | { | |
735 | attributes: [ 'id' ], | |
736 | model: VideoChannelModel.unscoped(), | |
737 | required: true, | |
738 | include: [ | |
739 | { | |
740 | attributes: [ 'id' ], | |
741 | model: VideoModel.unscoped(), | |
742 | required: true, | |
743 | include: [ | |
744 | { | |
745 | attributes: [], | |
746 | model: VideoLiveModel.unscoped(), | |
747 | required: true, | |
748 | where: { | |
749 | id: liveId | |
750 | } | |
751 | } | |
752 | ] | |
753 | } | |
754 | ] | |
755 | } | |
756 | ] | |
757 | } | |
758 | ] | |
759 | } | |
760 | ||
761 | return UserModel.unscoped().findOne(query) | |
762 | } | |
763 | ||
764 | static generateUserQuotaBaseSQL (options: { | |
765 | whereUserId: '$userId' | '"UserModel"."id"' | |
766 | withSelect: boolean | |
767 | where?: string | |
768 | }) { | |
769 | const andWhere = options.where | |
770 | ? 'AND ' + options.where | |
771 | : '' | |
772 | ||
773 | const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
774 | 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' + | |
775 | `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}` | |
776 | ||
777 | const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
778 | 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' + | |
779 | videoChannelJoin | |
780 | ||
781 | const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
782 | 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' + | |
783 | 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' + | |
784 | videoChannelJoin | |
785 | ||
786 | return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' + | |
787 | 'FROM (' + | |
788 | `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` + | |
789 | 'GROUP BY "t1"."videoId"' + | |
790 | ') t2' | |
791 | } | |
792 | ||
793 | static getTotalRawQuery (query: string, userId: number) { | |
794 | const options = { | |
795 | bind: { userId }, | |
796 | type: QueryTypes.SELECT as QueryTypes.SELECT | |
797 | } | |
798 | ||
799 | return UserModel.sequelize.query<{ total: string }>(query, options) | |
800 | .then(([ { total } ]) => { | |
801 | if (total === null) return 0 | |
802 | ||
803 | return parseInt(total, 10) | |
804 | }) | |
805 | } | |
806 | ||
807 | static async getStats () { | |
808 | function getActiveUsers (days: number) { | |
809 | const query = { | |
810 | where: { | |
811 | [Op.and]: [ | |
812 | literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`) | |
813 | ] | |
814 | } | |
815 | } | |
816 | ||
817 | return UserModel.count(query) | |
818 | } | |
819 | ||
820 | const totalUsers = await UserModel.count() | |
821 | const totalDailyActiveUsers = await getActiveUsers(1) | |
822 | const totalWeeklyActiveUsers = await getActiveUsers(7) | |
823 | const totalMonthlyActiveUsers = await getActiveUsers(30) | |
824 | const totalHalfYearActiveUsers = await getActiveUsers(180) | |
825 | ||
826 | return { | |
827 | totalUsers, | |
828 | totalDailyActiveUsers, | |
829 | totalWeeklyActiveUsers, | |
830 | totalMonthlyActiveUsers, | |
831 | totalHalfYearActiveUsers | |
832 | } | |
833 | } | |
834 | ||
835 | static autoComplete (search: string) { | |
836 | const query = { | |
837 | where: { | |
838 | username: { | |
839 | [Op.like]: `%${search}%` | |
840 | } | |
841 | }, | |
842 | limit: 10 | |
843 | } | |
844 | ||
845 | return UserModel.findAll(query) | |
846 | .then(u => u.map(u => u.username)) | |
847 | } | |
848 | ||
849 | canGetVideo (video: MVideoWithRights) { | |
850 | const videoUserId = video.VideoChannel.Account.userId | |
851 | ||
852 | if (video.isBlacklisted()) { | |
853 | return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | |
854 | } | |
855 | ||
856 | if (video.privacy === VideoPrivacy.PRIVATE) { | |
857 | return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | |
858 | } | |
859 | ||
860 | if (video.privacy === VideoPrivacy.INTERNAL) return true | |
861 | ||
862 | return false | |
863 | } | |
864 | ||
865 | hasRight (right: UserRight) { | |
866 | return hasUserRight(this.role, right) | |
867 | } | |
868 | ||
869 | hasAdminFlag (flag: UserAdminFlag) { | |
870 | return this.adminFlags & flag | |
871 | } | |
872 | ||
873 | isPasswordMatch (password: string) { | |
874 | return comparePassword(password, this.password) | |
875 | } | |
876 | ||
877 | toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User { | |
878 | const videoQuotaUsed = this.get('videoQuotaUsed') | |
879 | const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily') | |
880 | const videosCount = this.get('videosCount') | |
881 | const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':') | |
882 | const abusesCreatedCount = this.get('abusesCreatedCount') | |
883 | const videoCommentsCount = this.get('videoCommentsCount') | |
884 | ||
885 | const json: User = { | |
886 | id: this.id, | |
887 | username: this.username, | |
888 | email: this.email, | |
889 | theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME), | |
890 | ||
891 | pendingEmail: this.pendingEmail, | |
892 | emailVerified: this.emailVerified, | |
893 | ||
894 | nsfwPolicy: this.nsfwPolicy, | |
895 | webTorrentEnabled: this.webTorrentEnabled, | |
896 | videosHistoryEnabled: this.videosHistoryEnabled, | |
897 | autoPlayVideo: this.autoPlayVideo, | |
898 | autoPlayNextVideo: this.autoPlayNextVideo, | |
899 | autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist, | |
900 | videoLanguages: this.videoLanguages, | |
901 | ||
902 | role: this.role, | |
903 | roleLabel: USER_ROLE_LABELS[this.role], | |
904 | ||
905 | videoQuota: this.videoQuota, | |
906 | videoQuotaDaily: this.videoQuotaDaily, | |
907 | videoQuotaUsed: videoQuotaUsed !== undefined | |
908 | ? parseInt(videoQuotaUsed + '', 10) | |
909 | : undefined, | |
910 | videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined | |
911 | ? parseInt(videoQuotaUsedDaily + '', 10) | |
912 | : undefined, | |
913 | videosCount: videosCount !== undefined | |
914 | ? parseInt(videosCount + '', 10) | |
915 | : undefined, | |
916 | abusesCount: abusesCount | |
917 | ? parseInt(abusesCount, 10) | |
918 | : undefined, | |
919 | abusesAcceptedCount: abusesAcceptedCount | |
920 | ? parseInt(abusesAcceptedCount, 10) | |
921 | : undefined, | |
922 | abusesCreatedCount: abusesCreatedCount !== undefined | |
923 | ? parseInt(abusesCreatedCount + '', 10) | |
924 | : undefined, | |
925 | videoCommentsCount: videoCommentsCount !== undefined | |
926 | ? parseInt(videoCommentsCount + '', 10) | |
927 | : undefined, | |
928 | ||
929 | noInstanceConfigWarningModal: this.noInstanceConfigWarningModal, | |
930 | noWelcomeModal: this.noWelcomeModal, | |
931 | noAccountSetupWarningModal: this.noAccountSetupWarningModal, | |
932 | ||
933 | blocked: this.blocked, | |
934 | blockedReason: this.blockedReason, | |
935 | ||
936 | account: this.Account.toFormattedJSON(), | |
937 | ||
938 | notificationSettings: this.NotificationSetting | |
939 | ? this.NotificationSetting.toFormattedJSON() | |
940 | : undefined, | |
941 | ||
942 | videoChannels: [], | |
943 | ||
944 | createdAt: this.createdAt, | |
945 | ||
946 | pluginAuth: this.pluginAuth, | |
947 | ||
948 | lastLoginDate: this.lastLoginDate | |
949 | } | |
950 | ||
951 | if (parameters.withAdminFlags) { | |
952 | Object.assign(json, { adminFlags: this.adminFlags }) | |
953 | } | |
954 | ||
955 | if (Array.isArray(this.Account.VideoChannels) === true) { | |
956 | json.videoChannels = this.Account.VideoChannels | |
957 | .map(c => c.toFormattedJSON()) | |
958 | .sort((v1, v2) => { | |
959 | if (v1.createdAt < v2.createdAt) return -1 | |
960 | if (v1.createdAt === v2.createdAt) return 0 | |
961 | ||
962 | return 1 | |
963 | }) | |
964 | } | |
965 | ||
966 | return json | |
967 | } | |
968 | ||
969 | toMeFormattedJSON (this: MMyUserFormattable): MyUser { | |
970 | const formatted = this.toFormattedJSON({ withAdminFlags: true }) | |
971 | ||
972 | const specialPlaylists = this.Account.VideoPlaylists | |
973 | .map(p => ({ id: p.id, name: p.name, type: p.type })) | |
974 | ||
975 | return Object.assign(formatted, { specialPlaylists }) | |
976 | } | |
977 | } |