]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user-notification.ts
Add new plugin/peertube version notifs
[github/Chocobozzz/PeerTube.git] / server / models / account / user-notification.ts
1 import { FindOptions, ModelIndexesOptions, Op, WhereOptions } from 'sequelize'
2 import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, Is, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
3 import { UserNotificationIncludes, UserNotificationModelForApi } from '@server/types/models/user'
4 import { UserNotification, UserNotificationType } from '../../../shared'
5 import { isBooleanValid } from '../../helpers/custom-validators/misc'
6 import { isUserNotificationTypeValid } from '../../helpers/custom-validators/user-notifications'
7 import { AbuseModel } from '../abuse/abuse'
8 import { VideoAbuseModel } from '../abuse/video-abuse'
9 import { VideoCommentAbuseModel } from '../abuse/video-comment-abuse'
10 import { ActorModel } from '../activitypub/actor'
11 import { ActorFollowModel } from '../activitypub/actor-follow'
12 import { ApplicationModel } from '../application/application'
13 import { AvatarModel } from '../avatar/avatar'
14 import { PluginModel } from '../server/plugin'
15 import { ServerModel } from '../server/server'
16 import { getSort, throwIfNotValid } from '../utils'
17 import { VideoModel } from '../video/video'
18 import { VideoBlacklistModel } from '../video/video-blacklist'
19 import { VideoChannelModel } from '../video/video-channel'
20 import { VideoCommentModel } from '../video/video-comment'
21 import { VideoImportModel } from '../video/video-import'
22 import { AccountModel } from './account'
23 import { UserModel } from './user'
24
25 enum ScopeNames {
26 WITH_ALL = 'WITH_ALL'
27 }
28
29 function buildActorWithAvatarInclude () {
30 return {
31 attributes: [ 'preferredUsername' ],
32 model: ActorModel.unscoped(),
33 required: true,
34 include: [
35 {
36 attributes: [ 'filename' ],
37 model: AvatarModel.unscoped(),
38 required: false
39 },
40 {
41 attributes: [ 'host' ],
42 model: ServerModel.unscoped(),
43 required: false
44 }
45 ]
46 }
47 }
48
49 function buildVideoInclude (required: boolean) {
50 return {
51 attributes: [ 'id', 'uuid', 'name' ],
52 model: VideoModel.unscoped(),
53 required
54 }
55 }
56
57 function buildChannelInclude (required: boolean, withActor = false) {
58 return {
59 required,
60 attributes: [ 'id', 'name' ],
61 model: VideoChannelModel.unscoped(),
62 include: withActor === true ? [ buildActorWithAvatarInclude() ] : []
63 }
64 }
65
66 function buildAccountInclude (required: boolean, withActor = false) {
67 return {
68 required,
69 attributes: [ 'id', 'name' ],
70 model: AccountModel.unscoped(),
71 include: withActor === true ? [ buildActorWithAvatarInclude() ] : []
72 }
73 }
74
75 @Scopes(() => ({
76 [ScopeNames.WITH_ALL]: {
77 include: [
78 Object.assign(buildVideoInclude(false), {
79 include: [ buildChannelInclude(true, true) ]
80 }),
81
82 {
83 attributes: [ 'id', 'originCommentId' ],
84 model: VideoCommentModel.unscoped(),
85 required: false,
86 include: [
87 buildAccountInclude(true, true),
88 buildVideoInclude(true)
89 ]
90 },
91
92 {
93 attributes: [ 'id', 'state' ],
94 model: AbuseModel.unscoped(),
95 required: false,
96 include: [
97 {
98 attributes: [ 'id' ],
99 model: VideoAbuseModel.unscoped(),
100 required: false,
101 include: [ buildVideoInclude(false) ]
102 },
103 {
104 attributes: [ 'id' ],
105 model: VideoCommentAbuseModel.unscoped(),
106 required: false,
107 include: [
108 {
109 attributes: [ 'id', 'originCommentId' ],
110 model: VideoCommentModel.unscoped(),
111 required: false,
112 include: [
113 {
114 attributes: [ 'id', 'name', 'uuid' ],
115 model: VideoModel.unscoped(),
116 required: false
117 }
118 ]
119 }
120 ]
121 },
122 {
123 model: AccountModel,
124 as: 'FlaggedAccount',
125 required: false,
126 include: [ buildActorWithAvatarInclude() ]
127 }
128 ]
129 },
130
131 {
132 attributes: [ 'id' ],
133 model: VideoBlacklistModel.unscoped(),
134 required: false,
135 include: [ buildVideoInclude(true) ]
136 },
137
138 {
139 attributes: [ 'id', 'magnetUri', 'targetUrl', 'torrentName' ],
140 model: VideoImportModel.unscoped(),
141 required: false,
142 include: [ buildVideoInclude(false) ]
143 },
144
145 {
146 attributes: [ 'id', 'name', 'type', 'latestVersion' ],
147 model: PluginModel.unscoped(),
148 required: false
149 },
150
151 {
152 attributes: [ 'id', 'latestPeerTubeVersion' ],
153 model: ApplicationModel.unscoped(),
154 required: false
155 },
156
157 {
158 attributes: [ 'id', 'state' ],
159 model: ActorFollowModel.unscoped(),
160 required: false,
161 include: [
162 {
163 attributes: [ 'preferredUsername' ],
164 model: ActorModel.unscoped(),
165 required: true,
166 as: 'ActorFollower',
167 include: [
168 {
169 attributes: [ 'id', 'name' ],
170 model: AccountModel.unscoped(),
171 required: true
172 },
173 {
174 attributes: [ 'filename' ],
175 model: AvatarModel.unscoped(),
176 required: false
177 },
178 {
179 attributes: [ 'host' ],
180 model: ServerModel.unscoped(),
181 required: false
182 }
183 ]
184 },
185 {
186 attributes: [ 'preferredUsername', 'type' ],
187 model: ActorModel.unscoped(),
188 required: true,
189 as: 'ActorFollowing',
190 include: [
191 buildChannelInclude(false),
192 buildAccountInclude(false),
193 {
194 attributes: [ 'host' ],
195 model: ServerModel.unscoped(),
196 required: false
197 }
198 ]
199 }
200 ]
201 },
202
203 buildAccountInclude(false, true)
204 ]
205 }
206 }))
207 @Table({
208 tableName: 'userNotification',
209 indexes: [
210 {
211 fields: [ 'userId' ]
212 },
213 {
214 fields: [ 'videoId' ],
215 where: {
216 videoId: {
217 [Op.ne]: null
218 }
219 }
220 },
221 {
222 fields: [ 'commentId' ],
223 where: {
224 commentId: {
225 [Op.ne]: null
226 }
227 }
228 },
229 {
230 fields: [ 'abuseId' ],
231 where: {
232 abuseId: {
233 [Op.ne]: null
234 }
235 }
236 },
237 {
238 fields: [ 'videoBlacklistId' ],
239 where: {
240 videoBlacklistId: {
241 [Op.ne]: null
242 }
243 }
244 },
245 {
246 fields: [ 'videoImportId' ],
247 where: {
248 videoImportId: {
249 [Op.ne]: null
250 }
251 }
252 },
253 {
254 fields: [ 'accountId' ],
255 where: {
256 accountId: {
257 [Op.ne]: null
258 }
259 }
260 },
261 {
262 fields: [ 'actorFollowId' ],
263 where: {
264 actorFollowId: {
265 [Op.ne]: null
266 }
267 }
268 },
269 {
270 fields: [ 'pluginId' ],
271 where: {
272 pluginId: {
273 [Op.ne]: null
274 }
275 }
276 },
277 {
278 fields: [ 'applicationId' ],
279 where: {
280 applicationId: {
281 [Op.ne]: null
282 }
283 }
284 }
285 ] as (ModelIndexesOptions & { where?: WhereOptions })[]
286 })
287 export class UserNotificationModel extends Model {
288
289 @AllowNull(false)
290 @Default(null)
291 @Is('UserNotificationType', value => throwIfNotValid(value, isUserNotificationTypeValid, 'type'))
292 @Column
293 type: UserNotificationType
294
295 @AllowNull(false)
296 @Default(false)
297 @Is('UserNotificationRead', value => throwIfNotValid(value, isBooleanValid, 'read'))
298 @Column
299 read: boolean
300
301 @CreatedAt
302 createdAt: Date
303
304 @UpdatedAt
305 updatedAt: Date
306
307 @ForeignKey(() => UserModel)
308 @Column
309 userId: number
310
311 @BelongsTo(() => UserModel, {
312 foreignKey: {
313 allowNull: false
314 },
315 onDelete: 'cascade'
316 })
317 User: UserModel
318
319 @ForeignKey(() => VideoModel)
320 @Column
321 videoId: number
322
323 @BelongsTo(() => VideoModel, {
324 foreignKey: {
325 allowNull: true
326 },
327 onDelete: 'cascade'
328 })
329 Video: VideoModel
330
331 @ForeignKey(() => VideoCommentModel)
332 @Column
333 commentId: number
334
335 @BelongsTo(() => VideoCommentModel, {
336 foreignKey: {
337 allowNull: true
338 },
339 onDelete: 'cascade'
340 })
341 Comment: VideoCommentModel
342
343 @ForeignKey(() => AbuseModel)
344 @Column
345 abuseId: number
346
347 @BelongsTo(() => AbuseModel, {
348 foreignKey: {
349 allowNull: true
350 },
351 onDelete: 'cascade'
352 })
353 Abuse: AbuseModel
354
355 @ForeignKey(() => VideoBlacklistModel)
356 @Column
357 videoBlacklistId: number
358
359 @BelongsTo(() => VideoBlacklistModel, {
360 foreignKey: {
361 allowNull: true
362 },
363 onDelete: 'cascade'
364 })
365 VideoBlacklist: VideoBlacklistModel
366
367 @ForeignKey(() => VideoImportModel)
368 @Column
369 videoImportId: number
370
371 @BelongsTo(() => VideoImportModel, {
372 foreignKey: {
373 allowNull: true
374 },
375 onDelete: 'cascade'
376 })
377 VideoImport: VideoImportModel
378
379 @ForeignKey(() => AccountModel)
380 @Column
381 accountId: number
382
383 @BelongsTo(() => AccountModel, {
384 foreignKey: {
385 allowNull: true
386 },
387 onDelete: 'cascade'
388 })
389 Account: AccountModel
390
391 @ForeignKey(() => ActorFollowModel)
392 @Column
393 actorFollowId: number
394
395 @BelongsTo(() => ActorFollowModel, {
396 foreignKey: {
397 allowNull: true
398 },
399 onDelete: 'cascade'
400 })
401 ActorFollow: ActorFollowModel
402
403 @ForeignKey(() => PluginModel)
404 @Column
405 pluginId: number
406
407 @BelongsTo(() => PluginModel, {
408 foreignKey: {
409 allowNull: true
410 },
411 onDelete: 'cascade'
412 })
413 Plugin: PluginModel
414
415 @ForeignKey(() => ApplicationModel)
416 @Column
417 applicationId: number
418
419 @BelongsTo(() => ApplicationModel, {
420 foreignKey: {
421 allowNull: true
422 },
423 onDelete: 'cascade'
424 })
425 Application: ApplicationModel
426
427 static listForApi (userId: number, start: number, count: number, sort: string, unread?: boolean) {
428 const where = { userId }
429
430 const query: FindOptions = {
431 offset: start,
432 limit: count,
433 order: getSort(sort),
434 where
435 }
436
437 if (unread !== undefined) query.where['read'] = !unread
438
439 return Promise.all([
440 UserNotificationModel.count({ where })
441 .then(count => count || 0),
442
443 count === 0
444 ? []
445 : UserNotificationModel.scope(ScopeNames.WITH_ALL).findAll(query)
446 ]).then(([ total, data ]) => ({ total, data }))
447 }
448
449 static markAsRead (userId: number, notificationIds: number[]) {
450 const query = {
451 where: {
452 userId,
453 id: {
454 [Op.in]: notificationIds
455 }
456 }
457 }
458
459 return UserNotificationModel.update({ read: true }, query)
460 }
461
462 static markAllAsRead (userId: number) {
463 const query = { where: { userId } }
464
465 return UserNotificationModel.update({ read: true }, query)
466 }
467
468 static removeNotificationsOf (options: { id: number, type: 'account' | 'server', forUserId?: number }) {
469 const id = parseInt(options.id + '', 10)
470
471 function buildAccountWhereQuery (base: string) {
472 const whereSuffix = options.forUserId
473 ? ` AND "userNotification"."userId" = ${options.forUserId}`
474 : ''
475
476 if (options.type === 'account') {
477 return base +
478 ` WHERE "account"."id" = ${id} ${whereSuffix}`
479 }
480
481 return base +
482 ` WHERE "actor"."serverId" = ${id} ${whereSuffix}`
483 }
484
485 const queries = [
486 buildAccountWhereQuery(
487 `SELECT "userNotification"."id" FROM "userNotification" ` +
488 `INNER JOIN "account" ON "userNotification"."accountId" = "account"."id" ` +
489 `INNER JOIN actor ON "actor"."id" = "account"."actorId" `
490 ),
491
492 // Remove notifications from muted accounts that followed ours
493 buildAccountWhereQuery(
494 `SELECT "userNotification"."id" FROM "userNotification" ` +
495 `INNER JOIN "actorFollow" ON "actorFollow".id = "userNotification"."actorFollowId" ` +
496 `INNER JOIN actor ON actor.id = "actorFollow"."actorId" ` +
497 `INNER JOIN account ON account."actorId" = actor.id `
498 ),
499
500 // Remove notifications from muted accounts that commented something
501 buildAccountWhereQuery(
502 `SELECT "userNotification"."id" FROM "userNotification" ` +
503 `INNER JOIN "actorFollow" ON "actorFollow".id = "userNotification"."actorFollowId" ` +
504 `INNER JOIN actor ON actor.id = "actorFollow"."actorId" ` +
505 `INNER JOIN account ON account."actorId" = actor.id `
506 ),
507
508 buildAccountWhereQuery(
509 `SELECT "userNotification"."id" FROM "userNotification" ` +
510 `INNER JOIN "videoComment" ON "videoComment".id = "userNotification"."commentId" ` +
511 `INNER JOIN account ON account.id = "videoComment"."accountId" ` +
512 `INNER JOIN actor ON "actor"."id" = "account"."actorId" `
513 )
514 ]
515
516 const query = `DELETE FROM "userNotification" WHERE id IN (${queries.join(' UNION ')})`
517
518 return UserNotificationModel.sequelize.query(query)
519 }
520
521 toFormattedJSON (this: UserNotificationModelForApi): UserNotification {
522 const video = this.Video
523 ? Object.assign(this.formatVideo(this.Video), { channel: this.formatActor(this.Video.VideoChannel) })
524 : undefined
525
526 const videoImport = this.VideoImport
527 ? {
528 id: this.VideoImport.id,
529 video: this.VideoImport.Video ? this.formatVideo(this.VideoImport.Video) : undefined,
530 torrentName: this.VideoImport.torrentName,
531 magnetUri: this.VideoImport.magnetUri,
532 targetUrl: this.VideoImport.targetUrl
533 }
534 : undefined
535
536 const comment = this.Comment
537 ? {
538 id: this.Comment.id,
539 threadId: this.Comment.getThreadId(),
540 account: this.formatActor(this.Comment.Account),
541 video: this.formatVideo(this.Comment.Video)
542 }
543 : undefined
544
545 const abuse = this.Abuse ? this.formatAbuse(this.Abuse) : undefined
546
547 const videoBlacklist = this.VideoBlacklist
548 ? {
549 id: this.VideoBlacklist.id,
550 video: this.formatVideo(this.VideoBlacklist.Video)
551 }
552 : undefined
553
554 const account = this.Account ? this.formatActor(this.Account) : undefined
555
556 const actorFollowingType = {
557 Application: 'instance' as 'instance',
558 Group: 'channel' as 'channel',
559 Person: 'account' as 'account'
560 }
561 const actorFollow = this.ActorFollow
562 ? {
563 id: this.ActorFollow.id,
564 state: this.ActorFollow.state,
565 follower: {
566 id: this.ActorFollow.ActorFollower.Account.id,
567 displayName: this.ActorFollow.ActorFollower.Account.getDisplayName(),
568 name: this.ActorFollow.ActorFollower.preferredUsername,
569 avatar: this.ActorFollow.ActorFollower.Avatar ? { path: this.ActorFollow.ActorFollower.Avatar.getStaticPath() } : undefined,
570 host: this.ActorFollow.ActorFollower.getHost()
571 },
572 following: {
573 type: actorFollowingType[this.ActorFollow.ActorFollowing.type],
574 displayName: (this.ActorFollow.ActorFollowing.VideoChannel || this.ActorFollow.ActorFollowing.Account).getDisplayName(),
575 name: this.ActorFollow.ActorFollowing.preferredUsername,
576 host: this.ActorFollow.ActorFollowing.getHost()
577 }
578 }
579 : undefined
580
581 const plugin = this.Plugin
582 ? {
583 name: this.Plugin.name,
584 type: this.Plugin.type,
585 latestVersion: this.Plugin.latestVersion
586 }
587 : undefined
588
589 const peertube = this.Application
590 ? { latestVersion: this.Application.latestPeerTubeVersion }
591 : undefined
592
593 return {
594 id: this.id,
595 type: this.type,
596 read: this.read,
597 video,
598 videoImport,
599 comment,
600 abuse,
601 videoBlacklist,
602 account,
603 actorFollow,
604 plugin,
605 peertube,
606 createdAt: this.createdAt.toISOString(),
607 updatedAt: this.updatedAt.toISOString()
608 }
609 }
610
611 formatVideo (this: UserNotificationModelForApi, video: UserNotificationIncludes.VideoInclude) {
612 return {
613 id: video.id,
614 uuid: video.uuid,
615 name: video.name
616 }
617 }
618
619 formatAbuse (this: UserNotificationModelForApi, abuse: UserNotificationIncludes.AbuseInclude) {
620 const commentAbuse = abuse.VideoCommentAbuse?.VideoComment
621 ? {
622 threadId: abuse.VideoCommentAbuse.VideoComment.getThreadId(),
623
624 video: abuse.VideoCommentAbuse.VideoComment.Video
625 ? {
626 id: abuse.VideoCommentAbuse.VideoComment.Video.id,
627 name: abuse.VideoCommentAbuse.VideoComment.Video.name,
628 uuid: abuse.VideoCommentAbuse.VideoComment.Video.uuid
629 }
630 : undefined
631 }
632 : undefined
633
634 const videoAbuse = abuse.VideoAbuse?.Video ? this.formatVideo(abuse.VideoAbuse.Video) : undefined
635
636 const accountAbuse = (!commentAbuse && !videoAbuse && abuse.FlaggedAccount) ? this.formatActor(abuse.FlaggedAccount) : undefined
637
638 return {
639 id: abuse.id,
640 state: abuse.state,
641 video: videoAbuse,
642 comment: commentAbuse,
643 account: accountAbuse
644 }
645 }
646
647 formatActor (
648 this: UserNotificationModelForApi,
649 accountOrChannel: UserNotificationIncludes.AccountIncludeActor | UserNotificationIncludes.VideoChannelIncludeActor
650 ) {
651 const avatar = accountOrChannel.Actor.Avatar
652 ? { path: accountOrChannel.Actor.Avatar.getStaticPath() }
653 : undefined
654
655 return {
656 id: accountOrChannel.id,
657 displayName: accountOrChannel.getDisplayName(),
658 name: accountOrChannel.Actor.preferredUsername,
659 host: accountOrChannel.Actor.getHost(),
660 avatar
661 }
662 }
663 }