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