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