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