]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
Add import finished and video published notifs
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
e02643f3 1import * as Sequelize from 'sequelize'
3fd3ab2d 2import {
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'
e34c85e5 22import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
ba75d268 23import { User, UserRole } from '../../../shared/models/users'
65fcc311 24import {
a73c582e 25 isUserAutoPlayVideoValid,
eacb25c4 26 isUserBlockedReasonValid,
e6921918 27 isUserBlockedValid,
d9eaee39 28 isUserEmailVerifiedValid,
5cf84858 29 isUserNSFWPolicyValid,
a73c582e
C
30 isUserPasswordValid,
31 isUserRoleValid,
32 isUserUsernameValid,
5cf84858 33 isUserVideoQuotaDailyValid,
64cc5e85 34 isUserVideoQuotaValid,
cef534ed
C
35 isUserVideosHistoryEnabledValid,
36 isUserWebTorrentEnabledValid
3fd3ab2d 37} from '../../helpers/custom-validators/users'
da854ddd 38import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
39import { OAuthTokenModel } from '../oauth/oauth-token'
40import { getSort, throwIfNotValid } from '../utils'
41import { VideoChannelModel } from '../video/video-channel'
42import { AccountModel } from './account'
0883b324
C
43import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
44import { values } from 'lodash'
ed638e53 45import { NSFW_POLICY_TYPES } from '../../initializers'
f201a749 46import { clearCacheByUserId } from '../../lib/oauth-model'
cef534ed
C
47import { UserNotificationSettingModel } from './user-notification-setting'
48import { VideoModel } from '../video/video'
49import { ActorModel } from '../activitypub/actor'
50import { ActorFollowModel } from '../activitypub/actor-follow'
dc133480 51import { VideoImportModel } from '../video/video-import'
3fd3ab2d 52
9c2e0dbf
C
53enum ScopeNames {
54 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
55}
56
d48ff09d
C
57@DefaultScope({
58 include: [
59 {
60 model: () => AccountModel,
61 required: true
cef534ed
C
62 },
63 {
64 model: () => UserNotificationSettingModel,
65 required: true
d48ff09d
C
66 }
67 ]
68})
69@Scopes({
9c2e0dbf 70 [ScopeNames.WITH_VIDEO_CHANNEL]: {
d48ff09d
C
71 include: [
72 {
73 model: () => AccountModel,
74 required: true,
75 include: [ () => VideoChannelModel ]
cef534ed
C
76 },
77 {
78 model: () => UserNotificationSettingModel,
79 required: true
d48ff09d
C
80 }
81 ]
82 }
83})
3fd3ab2d
C
84@Table({
85 tableName: 'user',
86 indexes: [
feb4bdfd 87 {
3fd3ab2d
C
88 fields: [ 'username' ],
89 unique: true
feb4bdfd
C
90 },
91 {
3fd3ab2d
C
92 fields: [ 'email' ],
93 unique: true
feb4bdfd 94 }
e02643f3 95 ]
3fd3ab2d
C
96})
97export class UserModel extends Model<UserModel> {
98
99 @AllowNull(false)
100 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
101 @Column
102 password: string
103
104 @AllowNull(false)
105 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
106 @Column
107 username: string
108
109 @AllowNull(false)
110 @IsEmail
111 @Column(DataType.STRING(400))
112 email: string
113
d9eaee39
JM
114 @AllowNull(true)
115 @Default(null)
116 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
117 @Column
118 emailVerified: boolean
119
3fd3ab2d 120 @AllowNull(false)
0883b324
C
121 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
122 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
123 nsfwPolicy: NSFWPolicyType
3fd3ab2d 124
64cc5e85 125 @AllowNull(false)
0229b014 126 @Default(true)
ed638e53
RK
127 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
128 @Column
129 webTorrentEnabled: boolean
64cc5e85 130
8b9a525a
C
131 @AllowNull(false)
132 @Default(true)
133 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
134 @Column
135 videosHistoryEnabled: boolean
136
7efe153b
AL
137 @AllowNull(false)
138 @Default(true)
139 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
140 @Column
141 autoPlayVideo: boolean
142
e6921918
C
143 @AllowNull(false)
144 @Default(false)
145 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
146 @Column
147 blocked: boolean
148
eacb25c4
C
149 @AllowNull(true)
150 @Default(null)
151 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
152 @Column
153 blockedReason: string
154
3fd3ab2d
C
155 @AllowNull(false)
156 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
157 @Column
158 role: number
159
160 @AllowNull(false)
161 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
162 @Column(DataType.BIGINT)
163 videoQuota: number
164
bee0abff
FA
165 @AllowNull(false)
166 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
167 @Column(DataType.BIGINT)
168 videoQuotaDaily: number
169
3fd3ab2d
C
170 @CreatedAt
171 createdAt: Date
172
173 @UpdatedAt
174 updatedAt: Date
175
176 @HasOne(() => AccountModel, {
177 foreignKey: 'userId',
f05a1c30
C
178 onDelete: 'cascade',
179 hooks: true
3fd3ab2d
C
180 })
181 Account: AccountModel
69b0a27c 182
cef534ed
C
183 @HasOne(() => UserNotificationSettingModel, {
184 foreignKey: 'userId',
185 onDelete: 'cascade',
186 hooks: true
187 })
188 NotificationSetting: UserNotificationSettingModel
189
dc133480
C
190 @HasMany(() => VideoImportModel, {
191 foreignKey: 'userId',
192 onDelete: 'cascade'
193 })
194 VideoImports: VideoImportModel[]
195
3fd3ab2d
C
196 @HasMany(() => OAuthTokenModel, {
197 foreignKey: 'userId',
198 onDelete: 'cascade'
199 })
200 OAuthTokens: OAuthTokenModel[]
201
202 @BeforeCreate
203 @BeforeUpdate
204 static cryptPasswordIfNeeded (instance: UserModel) {
205 if (instance.changed('password')) {
206 return cryptPassword(instance.password)
207 .then(hash => {
208 instance.password = hash
209 return undefined
210 })
211 }
59557c46 212 }
26d7d31b 213
f201a749 214 @AfterUpdate
d175a6f7 215 @AfterDestroy
f201a749
C
216 static removeTokenCache (instance: UserModel) {
217 return clearCacheByUserId(instance.id)
218 }
219
3fd3ab2d
C
220 static countTotal () {
221 return this.count()
222 }
954605a8 223
24b9417c
C
224 static listForApi (start: number, count: number, sort: string, search?: string) {
225 let where = undefined
226 if (search) {
227 where = {
228 [Sequelize.Op.or]: [
229 {
230 email: {
231 [Sequelize.Op.iLike]: '%' + search + '%'
232 }
233 },
234 {
235 username: {
236 [ Sequelize.Op.iLike ]: '%' + search + '%'
237 }
238 }
239 ]
240 }
241 }
242
3fd3ab2d 243 const query = {
a76138ff
C
244 attributes: {
245 include: [
246 [
247 Sequelize.literal(
248 '(' +
8b604880
C
249 'SELECT COALESCE(SUM("size"), 0) ' +
250 'FROM (' +
a76138ff
C
251 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
252 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
253 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
254 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
255 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
256 ') t' +
257 ')'
258 ),
259 'videoQuotaUsed'
260 ] as any // FIXME: typings
261 ]
262 },
3fd3ab2d
C
263 offset: start,
264 limit: count,
24b9417c
C
265 order: getSort(sort),
266 where
3fd3ab2d 267 }
72c7248b 268
3fd3ab2d
C
269 return UserModel.findAndCountAll(query)
270 .then(({ rows, count }) => {
271 return {
272 data: rows,
273 total: count
274 }
72c7248b 275 })
72c7248b
C
276 }
277
cef534ed 278 static listWithRight (right: UserRight) {
ba75d268
C
279 const roles = Object.keys(USER_ROLE_LABELS)
280 .map(k => parseInt(k, 10) as UserRole)
281 .filter(role => hasUserRight(role, right))
282
ba75d268 283 const query = {
ba75d268
C
284 where: {
285 role: {
286 [Sequelize.Op.in]: roles
287 }
288 }
289 }
290
cef534ed
C
291 return UserModel.findAll(query)
292 }
293
294 static listUserSubscribersOf (actorId: number) {
295 const query = {
296 include: [
297 {
298 model: UserNotificationSettingModel.unscoped(),
299 required: true
300 },
301 {
302 attributes: [ 'userId' ],
303 model: AccountModel.unscoped(),
304 required: true,
305 include: [
306 {
307 attributes: [ ],
308 model: ActorModel.unscoped(),
309 required: true,
310 where: {
311 serverId: null
312 },
313 include: [
314 {
315 attributes: [ ],
316 as: 'ActorFollowings',
317 model: ActorFollowModel.unscoped(),
318 required: true,
319 where: {
320 targetActorId: actorId
321 }
322 }
323 ]
324 }
325 ]
326 }
327 ]
328 }
329
330 return UserModel.unscoped().findAll(query)
ba75d268
C
331 }
332
3fd3ab2d 333 static loadById (id: number) {
d48ff09d 334 return UserModel.findById(id)
3fd3ab2d 335 }
feb4bdfd 336
3fd3ab2d
C
337 static loadByUsername (username: string) {
338 const query = {
339 where: {
340 username
d48ff09d 341 }
3fd3ab2d 342 }
089ff2f2 343
3fd3ab2d 344 return UserModel.findOne(query)
feb4bdfd
C
345 }
346
3fd3ab2d
C
347 static loadByUsernameAndPopulateChannels (username: string) {
348 const query = {
349 where: {
350 username
d48ff09d 351 }
3fd3ab2d 352 }
9bd26629 353
9c2e0dbf 354 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
feb4bdfd
C
355 }
356
ecb4e35f
C
357 static loadByEmail (email: string) {
358 const query = {
359 where: {
360 email
361 }
362 }
363
364 return UserModel.findOne(query)
365 }
366
ba12e8b3
C
367 static loadByUsernameOrEmail (username: string, email?: string) {
368 if (!email) email = username
369
3fd3ab2d 370 const query = {
3fd3ab2d
C
371 where: {
372 [ Sequelize.Op.or ]: [ { username }, { email } ]
373 }
6fcd19ba 374 }
69b0a27c 375
d48ff09d 376 return UserModel.findOne(query)
72c7248b
C
377 }
378
cef534ed
C
379 static loadByVideoId (videoId: number) {
380 const query = {
381 include: [
382 {
383 required: true,
384 attributes: [ 'id' ],
385 model: AccountModel.unscoped(),
386 include: [
387 {
388 required: true,
389 attributes: [ 'id' ],
390 model: VideoChannelModel.unscoped(),
391 include: [
392 {
393 required: true,
394 attributes: [ 'id' ],
395 model: VideoModel.unscoped(),
396 where: {
397 id: videoId
398 }
399 }
400 ]
401 }
402 ]
403 }
404 ]
405 }
406
407 return UserModel.findOne(query)
408 }
409
dc133480
C
410 static loadByVideoImportId (videoImportId: number) {
411 const query = {
412 include: [
413 {
414 required: true,
415 attributes: [ 'id' ],
416 model: VideoImportModel.unscoped(),
417 where: {
418 id: videoImportId
419 }
420 }
421 ]
422 }
423
424 return UserModel.findOne(query)
425 }
426
ce5496d6 427 static getOriginalVideoFileTotalFromUser (user: UserModel) {
3fd3ab2d 428 // Don't use sequelize because we need to use a sub query
8b604880 429 const query = UserModel.generateUserQuotaBaseSQL()
bee0abff 430
8b604880 431 return UserModel.getTotalRawQuery(query, user.id)
bee0abff
FA
432 }
433
8b604880 434 // Returns cumulative size of all video files uploaded in the last 24 hours.
bee0abff
FA
435 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
436 // Don't use sequelize because we need to use a sub query
8b604880 437 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
68a3b9f2 438
8b604880 439 return UserModel.getTotalRawQuery(query, user.id)
72c7248b
C
440 }
441
09cababd
C
442 static async getStats () {
443 const totalUsers = await UserModel.count()
444
445 return {
446 totalUsers
447 }
448 }
449
5cf84858
C
450 static autoComplete (search: string) {
451 const query = {
452 where: {
453 username: {
454 [ Sequelize.Op.like ]: `%${search}%`
455 }
456 },
457 limit: 10
458 }
459
460 return UserModel.findAll(query)
461 .then(u => u.map(u => u.username))
462 }
463
3fd3ab2d
C
464 hasRight (right: UserRight) {
465 return hasUserRight(this.role, right)
466 }
72c7248b 467
3fd3ab2d
C
468 isPasswordMatch (password: string) {
469 return comparePassword(password, this.password)
feb4bdfd
C
470 }
471
c5911fd3 472 toFormattedJSON (): User {
a76138ff 473 const videoQuotaUsed = this.get('videoQuotaUsed')
bee0abff 474 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
a76138ff 475
3fd3ab2d
C
476 const json = {
477 id: this.id,
478 username: this.username,
479 email: this.email,
d9eaee39 480 emailVerified: this.emailVerified,
0883b324 481 nsfwPolicy: this.nsfwPolicy,
ed638e53 482 webTorrentEnabled: this.webTorrentEnabled,
276d9652 483 videosHistoryEnabled: this.videosHistoryEnabled,
7efe153b 484 autoPlayVideo: this.autoPlayVideo,
3fd3ab2d
C
485 role: this.role,
486 roleLabel: USER_ROLE_LABELS[ this.role ],
487 videoQuota: this.videoQuota,
bee0abff 488 videoQuotaDaily: this.videoQuotaDaily,
3fd3ab2d 489 createdAt: this.createdAt,
eacb25c4
C
490 blocked: this.blocked,
491 blockedReason: this.blockedReason,
c5911fd3 492 account: this.Account.toFormattedJSON(),
cef534ed 493 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
a76138ff 494 videoChannels: [],
bee0abff
FA
495 videoQuotaUsed: videoQuotaUsed !== undefined
496 ? parseInt(videoQuotaUsed, 10)
497 : undefined,
498 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
499 ? parseInt(videoQuotaUsedDaily, 10)
500 : undefined
3fd3ab2d
C
501 }
502
503 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 504 json.videoChannels = this.Account.VideoChannels
3fd3ab2d
C
505 .map(c => c.toFormattedJSON())
506 .sort((v1, v2) => {
507 if (v1.createdAt < v2.createdAt) return -1
508 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 509
3fd3ab2d
C
510 return 1
511 })
ad4a8a1c 512 }
3fd3ab2d
C
513
514 return json
ad4a8a1c
C
515 }
516
bee0abff
FA
517 async isAbleToUploadVideo (videoFile: { size: number }) {
518 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
b0f9f39e 519
bee0abff
FA
520 const [ totalBytes, totalBytesDaily ] = await Promise.all([
521 UserModel.getOriginalVideoFileTotalFromUser(this),
522 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
523 ])
524
525 const uploadedTotal = videoFile.size + totalBytes
526 const uploadedDaily = videoFile.size + totalBytesDaily
527 if (this.videoQuotaDaily === -1) {
528 return uploadedTotal < this.videoQuota
529 }
530 if (this.videoQuota === -1) {
531 return uploadedDaily < this.videoQuotaDaily
532 }
533
534 return (uploadedTotal < this.videoQuota) &&
535 (uploadedDaily < this.videoQuotaDaily)
b0f9f39e 536 }
8b604880
C
537
538 private static generateUserQuotaBaseSQL (where?: string) {
539 const andWhere = where ? 'AND ' + where : ''
540
541 return 'SELECT SUM("size") AS "total" ' +
542 'FROM (' +
543 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
544 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
545 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
546 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
547 'WHERE "account"."userId" = $userId ' + andWhere +
548 'GROUP BY "video"."id"' +
549 ') t'
550 }
551
552 private static getTotalRawQuery (query: string, userId: number) {
553 const options = {
554 bind: { userId },
555 type: Sequelize.QueryTypes.SELECT
556 }
557
558 return UserModel.sequelize.query(query, options)
559 .then(([ { total } ]) => {
560 if (total === null) return 0
561
562 return parseInt(total, 10)
563 })
564 }
b0f9f39e 565}