]>
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 | ||
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: '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_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 | @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled')) | |
271 | @Column | |
272 | p2pEnabled: boolean | |
273 | ||
274 | @AllowNull(false) | |
275 | @Default(true) | |
276 | @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled')) | |
277 | @Column | |
278 | videosHistoryEnabled: boolean | |
279 | ||
280 | @AllowNull(false) | |
281 | @Default(true) | |
282 | @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean')) | |
283 | @Column | |
284 | autoPlayVideo: boolean | |
285 | ||
286 | @AllowNull(false) | |
287 | @Default(false) | |
288 | @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean')) | |
289 | @Column | |
290 | autoPlayNextVideo: boolean | |
291 | ||
292 | @AllowNull(false) | |
293 | @Default(true) | |
294 | @Is( | |
295 | 'UserAutoPlayNextVideoPlaylist', | |
296 | value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean') | |
297 | ) | |
298 | @Column | |
299 | autoPlayNextVideoPlaylist: boolean | |
300 | ||
301 | @AllowNull(true) | |
302 | @Default(null) | |
303 | @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages')) | |
304 | @Column(DataType.ARRAY(DataType.STRING)) | |
305 | videoLanguages: string[] | |
306 | ||
307 | @AllowNull(false) | |
308 | @Default(UserAdminFlag.NONE) | |
309 | @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags')) | |
310 | @Column | |
311 | adminFlags?: UserAdminFlag | |
312 | ||
313 | @AllowNull(false) | |
314 | @Default(false) | |
315 | @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean')) | |
316 | @Column | |
317 | blocked: boolean | |
318 | ||
319 | @AllowNull(true) | |
320 | @Default(null) | |
321 | @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true)) | |
322 | @Column | |
323 | blockedReason: string | |
324 | ||
325 | @AllowNull(false) | |
326 | @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role')) | |
327 | @Column | |
328 | role: number | |
329 | ||
330 | @AllowNull(false) | |
331 | @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota')) | |
332 | @Column(DataType.BIGINT) | |
333 | videoQuota: number | |
334 | ||
335 | @AllowNull(false) | |
336 | @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily')) | |
337 | @Column(DataType.BIGINT) | |
338 | videoQuotaDaily: number | |
339 | ||
340 | @AllowNull(false) | |
341 | @Default(DEFAULT_USER_THEME_NAME) | |
342 | @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme')) | |
343 | @Column | |
344 | theme: string | |
345 | ||
346 | @AllowNull(false) | |
347 | @Default(false) | |
348 | @Is( | |
349 | 'UserNoInstanceConfigWarningModal', | |
350 | value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal') | |
351 | ) | |
352 | @Column | |
353 | noInstanceConfigWarningModal: boolean | |
354 | ||
355 | @AllowNull(false) | |
356 | @Default(false) | |
357 | @Is( | |
358 | 'UserNoWelcomeModal', | |
359 | value => throwIfNotValid(value, isUserNoModal, 'no welcome modal') | |
360 | ) | |
361 | @Column | |
362 | noWelcomeModal: boolean | |
363 | ||
364 | @AllowNull(false) | |
365 | @Default(false) | |
366 | @Is( | |
367 | 'UserNoAccountSetupWarningModal', | |
368 | value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal') | |
369 | ) | |
370 | @Column | |
371 | noAccountSetupWarningModal: boolean | |
372 | ||
373 | @AllowNull(true) | |
374 | @Default(null) | |
375 | @Column | |
376 | pluginAuth: string | |
377 | ||
378 | @AllowNull(false) | |
379 | @Default(DataType.UUIDV4) | |
380 | @IsUUID(4) | |
381 | @Column(DataType.UUID) | |
382 | feedToken: string | |
383 | ||
384 | @AllowNull(true) | |
385 | @Default(null) | |
386 | @Column | |
387 | lastLoginDate: Date | |
388 | ||
389 | @CreatedAt | |
390 | createdAt: Date | |
391 | ||
392 | @UpdatedAt | |
393 | updatedAt: Date | |
394 | ||
395 | @HasOne(() => AccountModel, { | |
396 | foreignKey: 'userId', | |
397 | onDelete: 'cascade', | |
398 | hooks: true | |
399 | }) | |
400 | Account: AccountModel | |
401 | ||
402 | @HasOne(() => UserNotificationSettingModel, { | |
403 | foreignKey: 'userId', | |
404 | onDelete: 'cascade', | |
405 | hooks: true | |
406 | }) | |
407 | NotificationSetting: UserNotificationSettingModel | |
408 | ||
409 | @HasMany(() => VideoImportModel, { | |
410 | foreignKey: 'userId', | |
411 | onDelete: 'cascade' | |
412 | }) | |
413 | VideoImports: VideoImportModel[] | |
414 | ||
415 | @HasMany(() => OAuthTokenModel, { | |
416 | foreignKey: 'userId', | |
417 | onDelete: 'cascade' | |
418 | }) | |
419 | OAuthTokens: OAuthTokenModel[] | |
420 | ||
421 | @BeforeCreate | |
422 | @BeforeUpdate | |
423 | static cryptPasswordIfNeeded (instance: UserModel) { | |
424 | if (instance.changed('password') && instance.password) { | |
425 | return cryptPassword(instance.password) | |
426 | .then(hash => { | |
427 | instance.password = hash | |
428 | return undefined | |
429 | }) | |
430 | } | |
431 | } | |
432 | ||
433 | @AfterUpdate | |
434 | @AfterDestroy | |
435 | static removeTokenCache (instance: UserModel) { | |
436 | return TokensCache.Instance.clearCacheByUserId(instance.id) | |
437 | } | |
438 | ||
439 | static countTotal () { | |
440 | return this.count() | |
441 | } | |
442 | ||
443 | static listForApi (parameters: { | |
444 | start: number | |
445 | count: number | |
446 | sort: string | |
447 | search?: string | |
448 | blocked?: boolean | |
449 | }) { | |
450 | const { start, count, sort, search, blocked } = parameters | |
451 | const where: WhereOptions = {} | |
452 | ||
453 | if (search) { | |
454 | Object.assign(where, { | |
455 | [Op.or]: [ | |
456 | { | |
457 | email: { | |
458 | [Op.iLike]: '%' + search + '%' | |
459 | } | |
460 | }, | |
461 | { | |
462 | username: { | |
463 | [Op.iLike]: '%' + search + '%' | |
464 | } | |
465 | } | |
466 | ] | |
467 | }) | |
468 | } | |
469 | ||
470 | if (blocked !== undefined) { | |
471 | Object.assign(where, { | |
472 | blocked: blocked | |
473 | }) | |
474 | } | |
475 | ||
476 | const query: FindOptions = { | |
477 | attributes: { | |
478 | include: [ | |
479 | [ | |
480 | literal( | |
481 | '(' + | |
482 | UserModel.generateUserQuotaBaseSQL({ | |
483 | withSelect: false, | |
484 | whereUserId: '"UserModel"."id"' | |
485 | }) + | |
486 | ')' | |
487 | ), | |
488 | 'videoQuotaUsed' | |
489 | ] | |
490 | ] | |
491 | }, | |
492 | offset: start, | |
493 | limit: count, | |
494 | order: getSort(sort), | |
495 | where | |
496 | } | |
497 | ||
498 | return Promise.all([ | |
499 | UserModel.unscoped().count(query), | |
500 | UserModel.findAll(query) | |
501 | ]).then(([ total, data ]) => ({ total, data })) | |
502 | } | |
503 | ||
504 | static listWithRight (right: UserRight): Promise<MUserDefault[]> { | |
505 | const roles = Object.keys(USER_ROLE_LABELS) | |
506 | .map(k => parseInt(k, 10) as UserRole) | |
507 | .filter(role => hasUserRight(role, right)) | |
508 | ||
509 | const query = { | |
510 | where: { | |
511 | role: { | |
512 | [Op.in]: roles | |
513 | } | |
514 | } | |
515 | } | |
516 | ||
517 | return UserModel.findAll(query) | |
518 | } | |
519 | ||
520 | static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> { | |
521 | const query = { | |
522 | include: [ | |
523 | { | |
524 | model: UserNotificationSettingModel.unscoped(), | |
525 | required: true | |
526 | }, | |
527 | { | |
528 | attributes: [ 'userId' ], | |
529 | model: AccountModel.unscoped(), | |
530 | required: true, | |
531 | include: [ | |
532 | { | |
533 | attributes: [], | |
534 | model: ActorModel.unscoped(), | |
535 | required: true, | |
536 | where: { | |
537 | serverId: null | |
538 | }, | |
539 | include: [ | |
540 | { | |
541 | attributes: [], | |
542 | as: 'ActorFollowings', | |
543 | model: ActorFollowModel.unscoped(), | |
544 | required: true, | |
545 | where: { | |
546 | targetActorId: actorId | |
547 | } | |
548 | } | |
549 | ] | |
550 | } | |
551 | ] | |
552 | } | |
553 | ] | |
554 | } | |
555 | ||
556 | return UserModel.unscoped().findAll(query) | |
557 | } | |
558 | ||
559 | static listByUsernames (usernames: string[]): Promise<MUserDefault[]> { | |
560 | const query = { | |
561 | where: { | |
562 | username: usernames | |
563 | } | |
564 | } | |
565 | ||
566 | return UserModel.findAll(query) | |
567 | } | |
568 | ||
569 | static loadById (id: number): Promise<MUser> { | |
570 | return UserModel.unscoped().findByPk(id) | |
571 | } | |
572 | ||
573 | static loadByIdFull (id: number): Promise<MUserDefault> { | |
574 | return UserModel.findByPk(id) | |
575 | } | |
576 | ||
577 | static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> { | |
578 | const scopes = [ | |
579 | ScopeNames.WITH_VIDEOCHANNELS | |
580 | ] | |
581 | ||
582 | if (withStats) scopes.push(ScopeNames.WITH_STATS) | |
583 | ||
584 | return UserModel.scope(scopes).findByPk(id) | |
585 | } | |
586 | ||
587 | static loadByUsername (username: string): Promise<MUserDefault> { | |
588 | const query = { | |
589 | where: { | |
590 | username | |
591 | } | |
592 | } | |
593 | ||
594 | return UserModel.findOne(query) | |
595 | } | |
596 | ||
597 | static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> { | |
598 | const query = { | |
599 | where: { | |
600 | id | |
601 | } | |
602 | } | |
603 | ||
604 | return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query) | |
605 | } | |
606 | ||
607 | static loadByEmail (email: string): Promise<MUserDefault> { | |
608 | const query = { | |
609 | where: { | |
610 | ||
611 | } | |
612 | } | |
613 | ||
614 | return UserModel.findOne(query) | |
615 | } | |
616 | ||
617 | static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> { | |
618 | if (!email) email = username | |
619 | ||
620 | const query = { | |
621 | where: { | |
622 | [Op.or]: [ | |
623 | where(fn('lower', col('username')), fn('lower', username) as any), | |
624 | ||
625 | { email } | |
626 | ] | |
627 | } | |
628 | } | |
629 | ||
630 | return UserModel.findOne(query) | |
631 | } | |
632 | ||
633 | static loadByVideoId (videoId: number): Promise<MUserDefault> { | |
634 | const query = { | |
635 | include: [ | |
636 | { | |
637 | required: true, | |
638 | attributes: [ 'id' ], | |
639 | model: AccountModel.unscoped(), | |
640 | include: [ | |
641 | { | |
642 | required: true, | |
643 | attributes: [ 'id' ], | |
644 | model: VideoChannelModel.unscoped(), | |
645 | include: [ | |
646 | { | |
647 | required: true, | |
648 | attributes: [ 'id' ], | |
649 | model: VideoModel.unscoped(), | |
650 | where: { | |
651 | id: videoId | |
652 | } | |
653 | } | |
654 | ] | |
655 | } | |
656 | ] | |
657 | } | |
658 | ] | |
659 | } | |
660 | ||
661 | return UserModel.findOne(query) | |
662 | } | |
663 | ||
664 | static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> { | |
665 | const query = { | |
666 | include: [ | |
667 | { | |
668 | required: true, | |
669 | attributes: [ 'id' ], | |
670 | model: VideoImportModel.unscoped(), | |
671 | where: { | |
672 | id: videoImportId | |
673 | } | |
674 | } | |
675 | ] | |
676 | } | |
677 | ||
678 | return UserModel.findOne(query) | |
679 | } | |
680 | ||
681 | static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> { | |
682 | const query = { | |
683 | include: [ | |
684 | { | |
685 | required: true, | |
686 | attributes: [ 'id' ], | |
687 | model: AccountModel.unscoped(), | |
688 | include: [ | |
689 | { | |
690 | required: true, | |
691 | attributes: [ 'id' ], | |
692 | model: VideoChannelModel.unscoped(), | |
693 | where: { | |
694 | actorId: videoChannelActorId | |
695 | } | |
696 | } | |
697 | ] | |
698 | } | |
699 | ] | |
700 | } | |
701 | ||
702 | return UserModel.findOne(query) | |
703 | } | |
704 | ||
705 | static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> { | |
706 | const query = { | |
707 | include: [ | |
708 | { | |
709 | required: true, | |
710 | attributes: [ 'id' ], | |
711 | model: AccountModel.unscoped(), | |
712 | where: { | |
713 | actorId: accountActorId | |
714 | } | |
715 | } | |
716 | ] | |
717 | } | |
718 | ||
719 | return UserModel.findOne(query) | |
720 | } | |
721 | ||
722 | static loadByLiveId (liveId: number): Promise<MUser> { | |
723 | const query = { | |
724 | include: [ | |
725 | { | |
726 | attributes: [ 'id' ], | |
727 | model: AccountModel.unscoped(), | |
728 | required: true, | |
729 | include: [ | |
730 | { | |
731 | attributes: [ 'id' ], | |
732 | model: VideoChannelModel.unscoped(), | |
733 | required: true, | |
734 | include: [ | |
735 | { | |
736 | attributes: [ 'id' ], | |
737 | model: VideoModel.unscoped(), | |
738 | required: true, | |
739 | include: [ | |
740 | { | |
741 | attributes: [], | |
742 | model: VideoLiveModel.unscoped(), | |
743 | required: true, | |
744 | where: { | |
745 | id: liveId | |
746 | } | |
747 | } | |
748 | ] | |
749 | } | |
750 | ] | |
751 | } | |
752 | ] | |
753 | } | |
754 | ] | |
755 | } | |
756 | ||
757 | return UserModel.unscoped().findOne(query) | |
758 | } | |
759 | ||
760 | static generateUserQuotaBaseSQL (options: { | |
761 | whereUserId: '$userId' | '"UserModel"."id"' | |
762 | withSelect: boolean | |
763 | where?: string | |
764 | }) { | |
765 | const andWhere = options.where | |
766 | ? 'AND ' + options.where | |
767 | : '' | |
768 | ||
769 | const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
770 | 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' + | |
771 | `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}` | |
772 | ||
773 | const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
774 | 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' + | |
775 | videoChannelJoin | |
776 | ||
777 | const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | |
778 | 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' + | |
779 | 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' + | |
780 | videoChannelJoin | |
781 | ||
782 | return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' + | |
783 | 'FROM (' + | |
784 | `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` + | |
785 | 'GROUP BY "t1"."videoId"' + | |
786 | ') t2' | |
787 | } | |
788 | ||
789 | static getTotalRawQuery (query: string, userId: number) { | |
790 | const options = { | |
791 | bind: { userId }, | |
792 | type: QueryTypes.SELECT as QueryTypes.SELECT | |
793 | } | |
794 | ||
795 | return UserModel.sequelize.query<{ total: string }>(query, options) | |
796 | .then(([ { total } ]) => { | |
797 | if (total === null) return 0 | |
798 | ||
799 | return parseInt(total, 10) | |
800 | }) | |
801 | } | |
802 | ||
803 | static async getStats () { | |
804 | function getActiveUsers (days: number) { | |
805 | const query = { | |
806 | where: { | |
807 | [Op.and]: [ | |
808 | literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`) | |
809 | ] | |
810 | } | |
811 | } | |
812 | ||
813 | return UserModel.count(query) | |
814 | } | |
815 | ||
816 | const totalUsers = await UserModel.count() | |
817 | const totalDailyActiveUsers = await getActiveUsers(1) | |
818 | const totalWeeklyActiveUsers = await getActiveUsers(7) | |
819 | const totalMonthlyActiveUsers = await getActiveUsers(30) | |
820 | const totalHalfYearActiveUsers = await getActiveUsers(180) | |
821 | ||
822 | return { | |
823 | totalUsers, | |
824 | totalDailyActiveUsers, | |
825 | totalWeeklyActiveUsers, | |
826 | totalMonthlyActiveUsers, | |
827 | totalHalfYearActiveUsers | |
828 | } | |
829 | } | |
830 | ||
831 | static autoComplete (search: string) { | |
832 | const query = { | |
833 | where: { | |
834 | username: { | |
835 | [Op.like]: `%${search}%` | |
836 | } | |
837 | }, | |
838 | limit: 10 | |
839 | } | |
840 | ||
841 | return UserModel.findAll(query) | |
842 | .then(u => u.map(u => u.username)) | |
843 | } | |
844 | ||
845 | canGetVideo (video: MVideoWithRights) { | |
846 | const videoUserId = video.VideoChannel.Account.userId | |
847 | ||
848 | if (video.isBlacklisted()) { | |
849 | return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | |
850 | } | |
851 | ||
852 | if (video.privacy === VideoPrivacy.PRIVATE) { | |
853 | return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | |
854 | } | |
855 | ||
856 | if (video.privacy === VideoPrivacy.INTERNAL) return true | |
857 | ||
858 | return false | |
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 | emailVerified: this.emailVerified, | |
889 | ||
890 | nsfwPolicy: this.nsfwPolicy, | |
891 | ||
892 | // FIXME: deprecated in 4.1 | |
893 | webTorrentEnabled: this.p2pEnabled, | |
894 | p2pEnabled: this.p2pEnabled, | |
895 | ||
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 | } |