aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/notifier.ts
blob: 5c50fcf01b355891c579f46cab29bb5b57209cd4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
import { AbuseMessageModel } from '@server/models/abuse/abuse-message'
import { getServerActor } from '@server/models/application/application'
import { ServerBlocklistModel } from '@server/models/server/server-blocklist'
import {
  MUser,
  MUserAccount,
  MUserDefault,
  MUserNotifSettingAccount,
  MUserWithNotificationSetting,
  UserNotificationModelForApi
} from '@server/types/models/user'
import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
import { MVideoImportVideo } from '@server/types/models/video/video-import'
import { UserAbuse } from '@shared/models'
import { UserNotificationSettingValue, UserNotificationType, UserRight } from '../../shared/models/users'
import { VideoPrivacy, VideoState } from '../../shared/models/videos'
import { logger } from '../helpers/logger'
import { CONFIG } from '../initializers/config'
import { AccountBlocklistModel } from '../models/account/account-blocklist'
import { UserModel } from '../models/account/user'
import { UserNotificationModel } from '../models/account/user-notification'
import { MAbuseFull, MAbuseMessage, MAccountServer, MActorFollowFull } from '../types/models'
import { MCommentOwnerVideo, MVideoAccountLight, MVideoFullLight } from '../types/models/video'
import { isBlockedByServerOrAccount } from './blocklist'
import { Emailer } from './emailer'
import { PeerTubeSocket } from './peertube-socket'

class Notifier {

  private static instance: Notifier

  private constructor () {
  }

  notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
    // Only notify on public and published videos which are not blacklisted
    if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return

    this.notifySubscribersOfNewVideo(video)
        .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
  }

  notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
    // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
    if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return

    this.notifyOwnedVideoHasBeenPublished(video)
        .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
  }

  notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
    // don't notify if video is still blacklisted or waiting for transcoding
    if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return

    this.notifyOwnedVideoHasBeenPublished(video)
        .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
  }

  notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
    // don't notify if video is still waiting for transcoding or scheduled update
    if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return

    this.notifyOwnedVideoHasBeenPublished(video)
        .catch(err => {
          logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })
        })
  }

  notifyOnNewComment (comment: MCommentOwnerVideo): void {
    this.notifyVideoOwnerOfNewComment(comment)
        .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))

    this.notifyOfCommentMention(comment)
        .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
  }

  notifyOnNewAbuse (parameters: { abuse: UserAbuse, abuseInstance: MAbuseFull, reporter: string }): void {
    this.notifyModeratorsOfNewAbuse(parameters)
        .catch(err => logger.error('Cannot notify of new abuse %d.', parameters.abuseInstance.id, { err }))
  }

  notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void {
    this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist)
        .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err }))
  }

  notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
    this.notifyVideoOwnerOfBlacklist(videoBlacklist)
        .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
  }

  notifyOnVideoUnblacklist (video: MVideoFullLight): void {
    this.notifyVideoOwnerOfUnblacklist(video)
        .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
  }

  notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
    this.notifyOwnerVideoImportIsFinished(videoImport, success)
        .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
  }

  notifyOnNewUserRegistration (user: MUserDefault): void {
    this.notifyModeratorsOfNewUserRegistration(user)
        .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
  }

  notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
    this.notifyUserOfNewActorFollow(actorFollow)
        .catch(err => {
          logger.error(
            'Cannot notify owner of channel %s of a new follow by %s.',
            actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
            actorFollow.ActorFollower.Account.getDisplayName(),
            { err }
          )
        })
  }

  notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
    this.notifyAdminsOfNewInstanceFollow(actorFollow)
        .catch(err => {
          logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
        })
  }

  notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
    this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
        .catch(err => {
          logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
        })
  }

  notifyOnAbuseStateChange (abuse: MAbuseFull): void {
    this.notifyReporterOfAbuseStateChange(abuse)
      .catch(err => {
        logger.error('Cannot notify reporter of abuse %d state change.', abuse.id, { err })
      })
  }

  notifyOnAbuseMessage (abuse: MAbuseFull, message: AbuseMessageModel): void {
    this.notifyOfNewAbuseMessage(abuse, message)
      .catch(err => {
        logger.error('Cannot notify on new abuse %d message.', abuse.id, { err })
      })
  }

  private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
    // List all followers that are users
    const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)

    logger.info('Notifying %d users of new video %s.', users.length, video.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.newVideoFromSubscription
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
        userId: user.id,
        videoId: video.id
      })
      notification.Video = video

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
    }

    return this.notify({ users, settingGetter, notificationCreator, emailSender })
  }

  private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
    if (comment.Video.isOwned() === false) return

    const user = await UserModel.loadByVideoId(comment.videoId)

    // Not our user or user comments its own video
    if (!user || comment.Account.userId === user.id) return

    if (await this.isBlockedByServerOrUser(comment.Account, user)) return

    logger.info('Notifying user %s of new comment %s.', user.username, comment.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.newCommentOnMyVideo
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
        userId: user.id,
        commentId: comment.id
      })
      notification.Comment = comment

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
    }

    return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
    const extractedUsernames = comment.extractMentions()
    logger.debug(
      'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
      { usernames: extractedUsernames, text: comment.text }
    )

    let users = await UserModel.listByUsernames(extractedUsernames)

    if (comment.Video.isOwned()) {
      const userException = await UserModel.loadByVideoId(comment.videoId)
      users = users.filter(u => u.id !== userException.id)
    }

    // Don't notify if I mentioned myself
    users = users.filter(u => u.Account.id !== comment.accountId)

    if (users.length === 0) return

    const serverAccountId = (await getServerActor()).Account.id
    const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])

    const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
    const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)

    logger.info('Notifying %d users of new comment %s.', users.length, comment.url)

    function settingGetter (user: MUserNotifSettingAccount) {
      const accountId = user.Account.id
      if (
        accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
        accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
      ) {
        return UserNotificationSettingValue.NONE
      }

      return user.NotificationSetting.commentMention
    }

    async function notificationCreator (user: MUserNotifSettingAccount) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.COMMENT_MENTION,
        userId: user.id,
        commentId: comment.id
      })
      notification.Comment = comment

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
    }

    return this.notify({ users, settingGetter, notificationCreator, emailSender })
  }

  private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
    if (actorFollow.ActorFollowing.isOwned() === false) return

    // Account follows one of our account?
    let followType: 'account' | 'channel' = 'channel'
    let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)

    // Account follows one of our channel?
    if (!user) {
      user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
      followType = 'account'
    }

    if (!user) return

    const followerAccount = actorFollow.ActorFollower.Account
    const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })

    if (await this.isBlockedByServerOrUser(followerAccountWithActor, user)) return

    logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.newFollow
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.NEW_FOLLOW,
        userId: user.id,
        actorFollowId: actorFollow.id
      })
      notification.ActorFollow = actorFollow

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
    }

    return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
    const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)

    const follower = Object.assign(actorFollow.ActorFollower.Account, { Actor: actorFollow.ActorFollower })
    if (await this.isBlockedByServerOrUser(follower)) return

    logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.newInstanceFollower
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
        userId: user.id,
        actorFollowId: actorFollow.id
      })
      notification.ActorFollow = actorFollow

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
    }

    return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
  }

  private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
    const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)

    logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.autoInstanceFollowing
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
        userId: user.id,
        actorFollowId: actorFollow.id
      })
      notification.ActorFollow = actorFollow

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
    }

    return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
  }

  private async notifyModeratorsOfNewAbuse (parameters: {
    abuse: UserAbuse
    abuseInstance: MAbuseFull
    reporter: string
  }) {
    const { abuse, abuseInstance } = parameters

    const moderators = await UserModel.listWithRight(UserRight.MANAGE_ABUSES)
    if (moderators.length === 0) return

    const url = this.getAbuseUrl(abuseInstance)

    logger.info('Notifying %s user/moderators of new abuse %s.', moderators.length, url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.abuseAsModerator
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.NEW_ABUSE_FOR_MODERATORS,
        userId: user.id,
        abuseId: abuse.id
      })
      notification.Abuse = abuseInstance

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addAbuseModeratorsNotification(emails, parameters)
    }

    return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
  }

  private async notifyReporterOfAbuseStateChange (abuse: MAbuseFull) {
    // Only notify our users
    if (abuse.ReporterAccount.isOwned() !== true) return

    const url = this.getAbuseUrl(abuse)

    logger.info('Notifying reporter of abuse % of state change.', url)

    const reporter = await UserModel.loadByAccountActorId(abuse.ReporterAccount.actorId)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.abuseStateChange
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.ABUSE_STATE_CHANGE,
        userId: user.id,
        abuseId: abuse.id
      })
      notification.Abuse = abuse

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addAbuseStateChangeNotification(emails, abuse)
    }

    return this.notify({ users: [ reporter ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyOfNewAbuseMessage (abuse: MAbuseFull, message: MAbuseMessage) {
    const url = this.getAbuseUrl(abuse)
    logger.info('Notifying reporter and moderators of new abuse message on %s.', url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.abuseNewMessage
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.ABUSE_NEW_MESSAGE,
        userId: user.id,
        abuseId: abuse.id
      })
      notification.Abuse = abuse

      return notification
    }

    function emailSenderReporter (emails: string[]) {
      return Emailer.Instance.addAbuseNewMessageNotification(emails, { target: 'reporter', abuse, message })
    }

    function emailSenderModerators (emails: string[]) {
      return Emailer.Instance.addAbuseNewMessageNotification(emails, { target: 'moderator', abuse, message })
    }

    async function buildReporterOptions () {
      // Only notify our users
      if (abuse.ReporterAccount.isOwned() !== true) return

      const reporter = await UserModel.loadByAccountActorId(abuse.ReporterAccount.actorId)
      // Don't notify my own message
      if (reporter.Account.id === message.accountId) return

      return { users: [ reporter ], settingGetter, notificationCreator, emailSender: emailSenderReporter }
    }

    async function buildModeratorsOptions () {
      let moderators = await UserModel.listWithRight(UserRight.MANAGE_ABUSES)
      // Don't notify my own message
      moderators = moderators.filter(m => m.Account.id !== message.accountId)

      if (moderators.length === 0) return

      return { users: moderators, settingGetter, notificationCreator, emailSender: emailSenderModerators }
    }

    const [ reporterOptions, moderatorsOptions ] = await Promise.all([
      buildReporterOptions(),
      buildModeratorsOptions()
    ])

    return Promise.all([
      this.notify(reporterOptions),
      this.notify(moderatorsOptions)
    ])
  }

  private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
    const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
    if (moderators.length === 0) return

    logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.videoAutoBlacklistAsModerator
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
        userId: user.id,
        videoBlacklistId: videoBlacklist.id
      })
      notification.VideoBlacklist = videoBlacklist

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
    }

    return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
  }

  private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
    const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
    if (!user) return

    logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.blacklistOnMyVideo
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
        userId: user.id,
        videoBlacklistId: videoBlacklist.id
      })
      notification.VideoBlacklist = videoBlacklist

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
    }

    return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
    const user = await UserModel.loadByVideoId(video.id)
    if (!user) return

    logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.blacklistOnMyVideo
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
        userId: user.id,
        videoId: video.id
      })
      notification.Video = video

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
    }

    return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
    const user = await UserModel.loadByVideoId(video.id)
    if (!user) return

    logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.myVideoPublished
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.MY_VIDEO_PUBLISHED,
        userId: user.id,
        videoId: video.id
      })
      notification.Video = video

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.myVideoPublishedNotification(emails, video)
    }

    return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
    const user = await UserModel.loadByVideoImportId(videoImport.id)
    if (!user) return

    logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.myVideoImportFinished
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
        userId: user.id,
        videoImportId: videoImport.id
      })
      notification.VideoImport = videoImport

      return notification
    }

    function emailSender (emails: string[]) {
      return success
        ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
        : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
    }

    return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  }

  private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
    const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
    if (moderators.length === 0) return

    logger.info(
      'Notifying %s moderators of new user registration of %s.',
      moderators.length, registeredUser.username
    )

    function settingGetter (user: MUserWithNotificationSetting) {
      return user.NotificationSetting.newUserRegistration
    }

    async function notificationCreator (user: MUserWithNotificationSetting) {
      const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
        type: UserNotificationType.NEW_USER_REGISTRATION,
        userId: user.id,
        accountId: registeredUser.Account.id
      })
      notification.Account = registeredUser.Account

      return notification
    }

    function emailSender (emails: string[]) {
      return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
    }

    return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
  }

  private async notify<T extends MUserWithNotificationSetting> (options: {
    users: T[]
    notificationCreator: (user: T) => Promise<UserNotificationModelForApi>
    emailSender: (emails: string[]) => void
    settingGetter: (user: T) => UserNotificationSettingValue
  }) {
    const emails: string[] = []

    for (const user of options.users) {
      if (this.isWebNotificationEnabled(options.settingGetter(user))) {
        const notification = await options.notificationCreator(user)

        PeerTubeSocket.Instance.sendNotification(user.id, notification)
      }

      if (this.isEmailEnabled(user, options.settingGetter(user))) {
        emails.push(user.email)
      }
    }

    if (emails.length !== 0) {
      options.emailSender(emails)
    }
  }

  private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
    if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false

    return value & UserNotificationSettingValue.EMAIL
  }

  private isWebNotificationEnabled (value: UserNotificationSettingValue) {
    return value & UserNotificationSettingValue.WEB
  }

  private isBlockedByServerOrUser (targetAccount: MAccountServer, user?: MUserAccount) {
    return isBlockedByServerOrAccount(targetAccount, user?.Account)
  }

  private getAbuseUrl (abuse: MAbuseFull) {
    return abuse.VideoAbuse?.Video?.url ||
      abuse.VideoCommentAbuse?.VideoComment?.url ||
      abuse.FlaggedAccount.Actor.url
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}

// ---------------------------------------------------------------------------

export {
  Notifier
}