diff options
Diffstat (limited to 'server/models/account/user.ts')
-rw-r--r-- | server/models/account/user.ts | 963 |
1 files changed, 0 insertions, 963 deletions
diff --git a/server/models/account/user.ts b/server/models/account/user.ts deleted file mode 100644 index 00c6d73aa..000000000 --- a/server/models/account/user.ts +++ /dev/null | |||
@@ -1,963 +0,0 @@ | |||
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 { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users' | ||
35 | import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared/models' | ||
36 | import { User, UserRole } from '../../../shared/models/users' | ||
37 | import { UserAdminFlag } from '../../../shared/models/users/user-flag.model' | ||
38 | import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type' | ||
39 | import { isThemeNameValid } from '../../helpers/custom-validators/plugins' | ||
40 | import { | ||
41 | isNoInstanceConfigWarningModal, | ||
42 | isNoWelcomeModal, | ||
43 | isUserAdminFlagsValid, | ||
44 | isUserAutoPlayNextVideoPlaylistValid, | ||
45 | isUserAutoPlayNextVideoValid, | ||
46 | isUserAutoPlayVideoValid, | ||
47 | isUserBlockedReasonValid, | ||
48 | isUserBlockedValid, | ||
49 | isUserEmailVerifiedValid, | ||
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 { ActorModel } from '../activitypub/actor' | ||
64 | import { ActorFollowModel } from '../activitypub/actor-follow' | ||
65 | import { OAuthTokenModel } from '../oauth/oauth-token' | ||
66 | import { getSort, throwIfNotValid } from '../utils' | ||
67 | import { VideoModel } from '../video/video' | ||
68 | import { VideoChannelModel } from '../video/video-channel' | ||
69 | import { VideoImportModel } from '../video/video-import' | ||
70 | import { VideoLiveModel } from '../video/video-live' | ||
71 | import { VideoPlaylistModel } from '../video/video-playlist' | ||
72 | import { AccountModel } from './account' | ||
73 | import { UserNotificationSettingModel } from './user-notification-setting' | ||
74 | import { ActorImageModel } from './actor-image' | ||
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 { | ||
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, isNoInstanceConfigWarningModal, 'no instance config warning modal') | ||
352 | ) | ||
353 | @Column | ||
354 | noInstanceConfigWarningModal: boolean | ||
355 | |||
356 | @AllowNull(false) | ||
357 | @Default(false) | ||
358 | @Is( | ||
359 | 'UserNoInstanceConfigWarningModal', | ||
360 | value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal') | ||
361 | ) | ||
362 | @Column | ||
363 | noWelcomeModal: boolean | ||
364 | |||
365 | @AllowNull(true) | ||
366 | @Default(null) | ||
367 | @Column | ||
368 | pluginAuth: string | ||
369 | |||
370 | @AllowNull(false) | ||
371 | @Default(DataType.UUIDV4) | ||
372 | @IsUUID(4) | ||
373 | @Column(DataType.UUID) | ||
374 | feedToken: string | ||
375 | |||
376 | @AllowNull(true) | ||
377 | @Default(null) | ||
378 | @Column | ||
379 | lastLoginDate: Date | ||
380 | |||
381 | @CreatedAt | ||
382 | createdAt: Date | ||
383 | |||
384 | @UpdatedAt | ||
385 | updatedAt: Date | ||
386 | |||
387 | @HasOne(() => AccountModel, { | ||
388 | foreignKey: 'userId', | ||
389 | onDelete: 'cascade', | ||
390 | hooks: true | ||
391 | }) | ||
392 | Account: AccountModel | ||
393 | |||
394 | @HasOne(() => UserNotificationSettingModel, { | ||
395 | foreignKey: 'userId', | ||
396 | onDelete: 'cascade', | ||
397 | hooks: true | ||
398 | }) | ||
399 | NotificationSetting: UserNotificationSettingModel | ||
400 | |||
401 | @HasMany(() => VideoImportModel, { | ||
402 | foreignKey: 'userId', | ||
403 | onDelete: 'cascade' | ||
404 | }) | ||
405 | VideoImports: VideoImportModel[] | ||
406 | |||
407 | @HasMany(() => OAuthTokenModel, { | ||
408 | foreignKey: 'userId', | ||
409 | onDelete: 'cascade' | ||
410 | }) | ||
411 | OAuthTokens: OAuthTokenModel[] | ||
412 | |||
413 | @BeforeCreate | ||
414 | @BeforeUpdate | ||
415 | static cryptPasswordIfNeeded (instance: UserModel) { | ||
416 | if (instance.changed('password') && instance.password) { | ||
417 | return cryptPassword(instance.password) | ||
418 | .then(hash => { | ||
419 | instance.password = hash | ||
420 | return undefined | ||
421 | }) | ||
422 | } | ||
423 | } | ||
424 | |||
425 | @AfterUpdate | ||
426 | @AfterDestroy | ||
427 | static removeTokenCache (instance: UserModel) { | ||
428 | return TokensCache.Instance.clearCacheByUserId(instance.id) | ||
429 | } | ||
430 | |||
431 | static countTotal () { | ||
432 | return this.count() | ||
433 | } | ||
434 | |||
435 | static listForApi (parameters: { | ||
436 | start: number | ||
437 | count: number | ||
438 | sort: string | ||
439 | search?: string | ||
440 | blocked?: boolean | ||
441 | }) { | ||
442 | const { start, count, sort, search, blocked } = parameters | ||
443 | const where: WhereOptions = {} | ||
444 | |||
445 | if (search) { | ||
446 | Object.assign(where, { | ||
447 | [Op.or]: [ | ||
448 | { | ||
449 | email: { | ||
450 | [Op.iLike]: '%' + search + '%' | ||
451 | } | ||
452 | }, | ||
453 | { | ||
454 | username: { | ||
455 | [Op.iLike]: '%' + search + '%' | ||
456 | } | ||
457 | } | ||
458 | ] | ||
459 | }) | ||
460 | } | ||
461 | |||
462 | if (blocked !== undefined) { | ||
463 | Object.assign(where, { | ||
464 | blocked: blocked | ||
465 | }) | ||
466 | } | ||
467 | |||
468 | const query: FindOptions = { | ||
469 | attributes: { | ||
470 | include: [ | ||
471 | [ | ||
472 | literal( | ||
473 | '(' + | ||
474 | UserModel.generateUserQuotaBaseSQL({ | ||
475 | withSelect: false, | ||
476 | whereUserId: '"UserModel"."id"' | ||
477 | }) + | ||
478 | ')' | ||
479 | ), | ||
480 | 'videoQuotaUsed' | ||
481 | ] as any // FIXME: typings | ||
482 | ] | ||
483 | }, | ||
484 | offset: start, | ||
485 | limit: count, | ||
486 | order: getSort(sort), | ||
487 | where | ||
488 | } | ||
489 | |||
490 | return UserModel.findAndCountAll(query) | ||
491 | .then(({ rows, count }) => { | ||
492 | return { | ||
493 | data: rows, | ||
494 | total: count | ||
495 | } | ||
496 | }) | ||
497 | } | ||
498 | |||
499 | static listWithRight (right: UserRight): Promise<MUserDefault[]> { | ||
500 | const roles = Object.keys(USER_ROLE_LABELS) | ||
501 | .map(k => parseInt(k, 10) as UserRole) | ||
502 | .filter(role => hasUserRight(role, right)) | ||
503 | |||
504 | const query = { | ||
505 | where: { | ||
506 | role: { | ||
507 | [Op.in]: roles | ||
508 | } | ||
509 | } | ||
510 | } | ||
511 | |||
512 | return UserModel.findAll(query) | ||
513 | } | ||
514 | |||
515 | static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> { | ||
516 | const query = { | ||
517 | include: [ | ||
518 | { | ||
519 | model: UserNotificationSettingModel.unscoped(), | ||
520 | required: true | ||
521 | }, | ||
522 | { | ||
523 | attributes: [ 'userId' ], | ||
524 | model: AccountModel.unscoped(), | ||
525 | required: true, | ||
526 | include: [ | ||
527 | { | ||
528 | attributes: [], | ||
529 | model: ActorModel.unscoped(), | ||
530 | required: true, | ||
531 | where: { | ||
532 | serverId: null | ||
533 | }, | ||
534 | include: [ | ||
535 | { | ||
536 | attributes: [], | ||
537 | as: 'ActorFollowings', | ||
538 | model: ActorFollowModel.unscoped(), | ||
539 | required: true, | ||
540 | where: { | ||
541 | targetActorId: actorId | ||
542 | } | ||
543 | } | ||
544 | ] | ||
545 | } | ||
546 | ] | ||
547 | } | ||
548 | ] | ||
549 | } | ||
550 | |||
551 | return UserModel.unscoped().findAll(query) | ||
552 | } | ||
553 | |||
554 | static listByUsernames (usernames: string[]): Promise<MUserDefault[]> { | ||
555 | const query = { | ||
556 | where: { | ||
557 | username: usernames | ||
558 | } | ||
559 | } | ||
560 | |||
561 | return UserModel.findAll(query) | ||
562 | } | ||
563 | |||
564 | static loadById (id: number): Promise<MUser> { | ||
565 | return UserModel.unscoped().findByPk(id) | ||
566 | } | ||
567 | |||
568 | static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> { | ||
569 | const scopes = [ | ||
570 | ScopeNames.WITH_VIDEOCHANNELS | ||
571 | ] | ||
572 | |||
573 | if (withStats) scopes.push(ScopeNames.WITH_STATS) | ||
574 | |||
575 | return UserModel.scope(scopes).findByPk(id) | ||
576 | } | ||
577 | |||
578 | static loadByUsername (username: string): Promise<MUserDefault> { | ||
579 | const query = { | ||
580 | where: { | ||
581 | username | ||
582 | } | ||
583 | } | ||
584 | |||
585 | return UserModel.findOne(query) | ||
586 | } | ||
587 | |||
588 | static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> { | ||
589 | const query = { | ||
590 | where: { | ||
591 | id | ||
592 | } | ||
593 | } | ||
594 | |||
595 | return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query) | ||
596 | } | ||
597 | |||
598 | static loadByEmail (email: string): Promise<MUserDefault> { | ||
599 | const query = { | ||
600 | where: { | ||
601 | |||
602 | } | ||
603 | } | ||
604 | |||
605 | return UserModel.findOne(query) | ||
606 | } | ||
607 | |||
608 | static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> { | ||
609 | if (!email) email = username | ||
610 | |||
611 | const query = { | ||
612 | where: { | ||
613 | [Op.or]: [ | ||
614 | where(fn('lower', col('username')), fn('lower', username)), | ||
615 | |||
616 | { email } | ||
617 | ] | ||
618 | } | ||
619 | } | ||
620 | |||
621 | return UserModel.findOne(query) | ||
622 | } | ||
623 | |||
624 | static loadByVideoId (videoId: number): Promise<MUserDefault> { | ||
625 | const query = { | ||
626 | include: [ | ||
627 | { | ||
628 | required: true, | ||
629 | attributes: [ 'id' ], | ||
630 | model: AccountModel.unscoped(), | ||
631 | include: [ | ||
632 | { | ||
633 | required: true, | ||
634 | attributes: [ 'id' ], | ||
635 | model: VideoChannelModel.unscoped(), | ||
636 | include: [ | ||
637 | { | ||
638 | required: true, | ||
639 | attributes: [ 'id' ], | ||
640 | model: VideoModel.unscoped(), | ||
641 | where: { | ||
642 | id: videoId | ||
643 | } | ||
644 | } | ||
645 | ] | ||
646 | } | ||
647 | ] | ||
648 | } | ||
649 | ] | ||
650 | } | ||
651 | |||
652 | return UserModel.findOne(query) | ||
653 | } | ||
654 | |||
655 | static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> { | ||
656 | const query = { | ||
657 | include: [ | ||
658 | { | ||
659 | required: true, | ||
660 | attributes: [ 'id' ], | ||
661 | model: VideoImportModel.unscoped(), | ||
662 | where: { | ||
663 | id: videoImportId | ||
664 | } | ||
665 | } | ||
666 | ] | ||
667 | } | ||
668 | |||
669 | return UserModel.findOne(query) | ||
670 | } | ||
671 | |||
672 | static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> { | ||
673 | const query = { | ||
674 | include: [ | ||
675 | { | ||
676 | required: true, | ||
677 | attributes: [ 'id' ], | ||
678 | model: AccountModel.unscoped(), | ||
679 | include: [ | ||
680 | { | ||
681 | required: true, | ||
682 | attributes: [ 'id' ], | ||
683 | model: VideoChannelModel.unscoped(), | ||
684 | where: { | ||
685 | actorId: videoChannelActorId | ||
686 | } | ||
687 | } | ||
688 | ] | ||
689 | } | ||
690 | ] | ||
691 | } | ||
692 | |||
693 | return UserModel.findOne(query) | ||
694 | } | ||
695 | |||
696 | static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> { | ||
697 | const query = { | ||
698 | include: [ | ||
699 | { | ||
700 | required: true, | ||
701 | attributes: [ 'id' ], | ||
702 | model: AccountModel.unscoped(), | ||
703 | where: { | ||
704 | actorId: accountActorId | ||
705 | } | ||
706 | } | ||
707 | ] | ||
708 | } | ||
709 | |||
710 | return UserModel.findOne(query) | ||
711 | } | ||
712 | |||
713 | static loadByLiveId (liveId: number): Promise<MUser> { | ||
714 | const query = { | ||
715 | include: [ | ||
716 | { | ||
717 | attributes: [ 'id' ], | ||
718 | model: AccountModel.unscoped(), | ||
719 | required: true, | ||
720 | include: [ | ||
721 | { | ||
722 | attributes: [ 'id' ], | ||
723 | model: VideoChannelModel.unscoped(), | ||
724 | required: true, | ||
725 | include: [ | ||
726 | { | ||
727 | attributes: [ 'id' ], | ||
728 | model: VideoModel.unscoped(), | ||
729 | required: true, | ||
730 | include: [ | ||
731 | { | ||
732 | attributes: [], | ||
733 | model: VideoLiveModel.unscoped(), | ||
734 | required: true, | ||
735 | where: { | ||
736 | id: liveId | ||
737 | } | ||
738 | } | ||
739 | ] | ||
740 | } | ||
741 | ] | ||
742 | } | ||
743 | ] | ||
744 | } | ||
745 | ] | ||
746 | } | ||
747 | |||
748 | return UserModel.unscoped().findOne(query) | ||
749 | } | ||
750 | |||
751 | static generateUserQuotaBaseSQL (options: { | ||
752 | whereUserId: '$userId' | '"UserModel"."id"' | ||
753 | withSelect: boolean | ||
754 | where?: string | ||
755 | }) { | ||
756 | const andWhere = options.where | ||
757 | ? 'AND ' + options.where | ||
758 | : '' | ||
759 | |||
760 | const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | ||
761 | 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' + | ||
762 | `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}` | ||
763 | |||
764 | const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | ||
765 | 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' + | ||
766 | videoChannelJoin | ||
767 | |||
768 | const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' + | ||
769 | 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' + | ||
770 | 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' + | ||
771 | videoChannelJoin | ||
772 | |||
773 | return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' + | ||
774 | 'FROM (' + | ||
775 | `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` + | ||
776 | 'GROUP BY "t1"."videoId"' + | ||
777 | ') t2' | ||
778 | } | ||
779 | |||
780 | static getTotalRawQuery (query: string, userId: number) { | ||
781 | const options = { | ||
782 | bind: { userId }, | ||
783 | type: QueryTypes.SELECT as QueryTypes.SELECT | ||
784 | } | ||
785 | |||
786 | return UserModel.sequelize.query<{ total: string }>(query, options) | ||
787 | .then(([ { total } ]) => { | ||
788 | if (total === null) return 0 | ||
789 | |||
790 | return parseInt(total, 10) | ||
791 | }) | ||
792 | } | ||
793 | |||
794 | static async getStats () { | ||
795 | function getActiveUsers (days: number) { | ||
796 | const query = { | ||
797 | where: { | ||
798 | [Op.and]: [ | ||
799 | literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`) | ||
800 | ] | ||
801 | } | ||
802 | } | ||
803 | |||
804 | return UserModel.count(query) | ||
805 | } | ||
806 | |||
807 | const totalUsers = await UserModel.count() | ||
808 | const totalDailyActiveUsers = await getActiveUsers(1) | ||
809 | const totalWeeklyActiveUsers = await getActiveUsers(7) | ||
810 | const totalMonthlyActiveUsers = await getActiveUsers(30) | ||
811 | const totalHalfYearActiveUsers = await getActiveUsers(180) | ||
812 | |||
813 | return { | ||
814 | totalUsers, | ||
815 | totalDailyActiveUsers, | ||
816 | totalWeeklyActiveUsers, | ||
817 | totalMonthlyActiveUsers, | ||
818 | totalHalfYearActiveUsers | ||
819 | } | ||
820 | } | ||
821 | |||
822 | static autoComplete (search: string) { | ||
823 | const query = { | ||
824 | where: { | ||
825 | username: { | ||
826 | [Op.like]: `%${search}%` | ||
827 | } | ||
828 | }, | ||
829 | limit: 10 | ||
830 | } | ||
831 | |||
832 | return UserModel.findAll(query) | ||
833 | .then(u => u.map(u => u.username)) | ||
834 | } | ||
835 | |||
836 | canGetVideo (video: MVideoWithRights) { | ||
837 | const videoUserId = video.VideoChannel.Account.userId | ||
838 | |||
839 | if (video.isBlacklisted()) { | ||
840 | return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | ||
841 | } | ||
842 | |||
843 | if (video.privacy === VideoPrivacy.PRIVATE) { | ||
844 | return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) | ||
845 | } | ||
846 | |||
847 | if (video.privacy === VideoPrivacy.INTERNAL) return true | ||
848 | |||
849 | return false | ||
850 | } | ||
851 | |||
852 | hasRight (right: UserRight) { | ||
853 | return hasUserRight(this.role, right) | ||
854 | } | ||
855 | |||
856 | hasAdminFlag (flag: UserAdminFlag) { | ||
857 | return this.adminFlags & flag | ||
858 | } | ||
859 | |||
860 | isPasswordMatch (password: string) { | ||
861 | return comparePassword(password, this.password) | ||
862 | } | ||
863 | |||
864 | toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User { | ||
865 | const videoQuotaUsed = this.get('videoQuotaUsed') | ||
866 | const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily') | ||
867 | const videosCount = this.get('videosCount') | ||
868 | const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':') | ||
869 | const abusesCreatedCount = this.get('abusesCreatedCount') | ||
870 | const videoCommentsCount = this.get('videoCommentsCount') | ||
871 | |||
872 | const json: User = { | ||
873 | id: this.id, | ||
874 | username: this.username, | ||
875 | email: this.email, | ||
876 | theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME), | ||
877 | |||
878 | pendingEmail: this.pendingEmail, | ||
879 | emailVerified: this.emailVerified, | ||
880 | |||
881 | nsfwPolicy: this.nsfwPolicy, | ||
882 | webTorrentEnabled: this.webTorrentEnabled, | ||
883 | videosHistoryEnabled: this.videosHistoryEnabled, | ||
884 | autoPlayVideo: this.autoPlayVideo, | ||
885 | autoPlayNextVideo: this.autoPlayNextVideo, | ||
886 | autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist, | ||
887 | videoLanguages: this.videoLanguages, | ||
888 | |||
889 | role: this.role, | ||
890 | roleLabel: USER_ROLE_LABELS[this.role], | ||
891 | |||
892 | videoQuota: this.videoQuota, | ||
893 | videoQuotaDaily: this.videoQuotaDaily, | ||
894 | videoQuotaUsed: videoQuotaUsed !== undefined | ||
895 | ? parseInt(videoQuotaUsed + '', 10) | ||
896 | : undefined, | ||
897 | videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined | ||
898 | ? parseInt(videoQuotaUsedDaily + '', 10) | ||
899 | : undefined, | ||
900 | videosCount: videosCount !== undefined | ||
901 | ? parseInt(videosCount + '', 10) | ||
902 | : undefined, | ||
903 | abusesCount: abusesCount | ||
904 | ? parseInt(abusesCount, 10) | ||
905 | : undefined, | ||
906 | abusesAcceptedCount: abusesAcceptedCount | ||
907 | ? parseInt(abusesAcceptedCount, 10) | ||
908 | : undefined, | ||
909 | abusesCreatedCount: abusesCreatedCount !== undefined | ||
910 | ? parseInt(abusesCreatedCount + '', 10) | ||
911 | : undefined, | ||
912 | videoCommentsCount: videoCommentsCount !== undefined | ||
913 | ? parseInt(videoCommentsCount + '', 10) | ||
914 | : undefined, | ||
915 | |||
916 | noInstanceConfigWarningModal: this.noInstanceConfigWarningModal, | ||
917 | noWelcomeModal: this.noWelcomeModal, | ||
918 | |||
919 | blocked: this.blocked, | ||
920 | blockedReason: this.blockedReason, | ||
921 | |||
922 | account: this.Account.toFormattedJSON(), | ||
923 | |||
924 | notificationSettings: this.NotificationSetting | ||
925 | ? this.NotificationSetting.toFormattedJSON() | ||
926 | : undefined, | ||
927 | |||
928 | videoChannels: [], | ||
929 | |||
930 | createdAt: this.createdAt, | ||
931 | |||
932 | pluginAuth: this.pluginAuth, | ||
933 | |||
934 | lastLoginDate: this.lastLoginDate | ||
935 | } | ||
936 | |||
937 | if (parameters.withAdminFlags) { | ||
938 | Object.assign(json, { adminFlags: this.adminFlags }) | ||
939 | } | ||
940 | |||
941 | if (Array.isArray(this.Account.VideoChannels) === true) { | ||
942 | json.videoChannels = this.Account.VideoChannels | ||
943 | .map(c => c.toFormattedJSON()) | ||
944 | .sort((v1, v2) => { | ||
945 | if (v1.createdAt < v2.createdAt) return -1 | ||
946 | if (v1.createdAt === v2.createdAt) return 0 | ||
947 | |||
948 | return 1 | ||
949 | }) | ||
950 | } | ||
951 | |||
952 | return json | ||
953 | } | ||
954 | |||
955 | toMeFormattedJSON (this: MMyUserFormattable): MyUser { | ||
956 | const formatted = this.toFormattedJSON() | ||
957 | |||
958 | const specialPlaylists = this.Account.VideoPlaylists | ||
959 | .map(p => ({ id: p.id, name: p.name, type: p.type })) | ||
960 | |||
961 | return Object.assign(formatted, { specialPlaylists }) | ||
962 | } | ||
963 | } | ||