1 import { UserNotificationSettingValue, UserNotificationType, UserRight } from '../../shared/models/users'
2 import { logger } from '../helpers/logger'
3 import { Emailer } from './emailer'
4 import { UserNotificationModel } from '../models/account/user-notification'
5 import { UserModel } from '../models/account/user'
6 import { PeerTubeSocket } from './peertube-socket'
7 import { CONFIG } from '../initializers/config'
8 import { VideoPrivacy, VideoState } from '../../shared/models/videos'
9 import { AccountBlocklistModel } from '../models/account/account-blocklist'
14 MVideoBlacklistLightVideo,
17 } from '../typings/models/video'
22 MUserNotifSettingAccount,
23 MUserWithNotificationSetting,
24 UserNotificationModelForApi
25 } from '@server/typings/models/user'
26 import { MAccountDefault, MActorFollowFull } from '../typings/models'
27 import { MVideoImportVideo } from '@server/typings/models/video/video-import'
28 import { ServerBlocklistModel } from '@server/models/server/server-blocklist'
29 import { getServerActor } from '@server/helpers/utils'
33 private static instance: Notifier
35 private constructor () {
38 notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
39 // Only notify on public and published videos which are not blacklisted
40 if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return
42 this.notifySubscribersOfNewVideo(video)
43 .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
46 notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
47 // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
48 if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return
50 this.notifyOwnedVideoHasBeenPublished(video)
51 .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
54 notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
55 // don't notify if video is still blacklisted or waiting for transcoding
56 if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
58 this.notifyOwnedVideoHasBeenPublished(video)
59 .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
62 notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
63 // don't notify if video is still waiting for transcoding or scheduled update
64 if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
66 this.notifyOwnedVideoHasBeenPublished(video)
68 logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })
72 notifyOnNewComment (comment: MCommentOwnerVideo): void {
73 this.notifyVideoOwnerOfNewComment(comment)
74 .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
76 this.notifyOfCommentMention(comment)
77 .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
80 notifyOnNewVideoAbuse (videoAbuse: MVideoAbuseVideo): void {
81 this.notifyModeratorsOfNewVideoAbuse(videoAbuse)
82 .catch(err => logger.error('Cannot notify of new video abuse of video %s.', videoAbuse.Video.url, { err }))
85 notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void {
86 this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist)
87 .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err }))
90 notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
91 this.notifyVideoOwnerOfBlacklist(videoBlacklist)
92 .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
95 notifyOnVideoUnblacklist (video: MVideoFullLight): void {
96 this.notifyVideoOwnerOfUnblacklist(video)
97 .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
100 notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
101 this.notifyOwnerVideoImportIsFinished(videoImport, success)
102 .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
105 notifyOnNewUserRegistration (user: MUserDefault): void {
106 this.notifyModeratorsOfNewUserRegistration(user)
107 .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
110 notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
111 this.notifyUserOfNewActorFollow(actorFollow)
114 'Cannot notify owner of channel %s of a new follow by %s.',
115 actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
116 actorFollow.ActorFollower.Account.getDisplayName(),
122 notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
123 this.notifyAdminsOfNewInstanceFollow(actorFollow)
125 logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
129 notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
130 this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
132 logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
136 private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
137 // List all followers that are users
138 const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
140 logger.info('Notifying %d users of new video %s.', users.length, video.url)
142 function settingGetter (user: MUserWithNotificationSetting) {
143 return user.NotificationSetting.newVideoFromSubscription
146 async function notificationCreator (user: MUserWithNotificationSetting) {
147 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
148 type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
152 notification.Video = video
157 function emailSender (emails: string[]) {
158 return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
161 return this.notify({ users, settingGetter, notificationCreator, emailSender })
164 private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
165 if (comment.Video.isOwned() === false) return
167 const user = await UserModel.loadByVideoId(comment.videoId)
169 // Not our user or user comments its own video
170 if (!user || comment.Account.userId === user.id) return
172 if (await this.isBlockedByServerOrAccount(user, comment.Account)) return
174 logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
176 function settingGetter (user: MUserWithNotificationSetting) {
177 return user.NotificationSetting.newCommentOnMyVideo
180 async function notificationCreator (user: MUserWithNotificationSetting) {
181 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
182 type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
184 commentId: comment.id
186 notification.Comment = comment
191 function emailSender (emails: string[]) {
192 return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
195 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
198 private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
199 const extractedUsernames = comment.extractMentions()
201 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
202 { usernames: extractedUsernames, text: comment.text }
205 let users = await UserModel.listByUsernames(extractedUsernames)
207 if (comment.Video.isOwned()) {
208 const userException = await UserModel.loadByVideoId(comment.videoId)
209 users = users.filter(u => u.id !== userException.id)
212 // Don't notify if I mentioned myself
213 users = users.filter(u => u.Account.id !== comment.accountId)
215 if (users.length === 0) return
217 const serverAccountId = (await getServerActor()).Account.id
218 const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])
220 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
221 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)
223 logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
225 function settingGetter (user: MUserNotifSettingAccount) {
226 const accountId = user.Account.id
228 accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
229 accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
231 return UserNotificationSettingValue.NONE
234 return user.NotificationSetting.commentMention
237 async function notificationCreator (user: MUserNotifSettingAccount) {
238 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
239 type: UserNotificationType.COMMENT_MENTION,
241 commentId: comment.id
243 notification.Comment = comment
248 function emailSender (emails: string[]) {
249 return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
252 return this.notify({ users, settingGetter, notificationCreator, emailSender })
255 private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
256 if (actorFollow.ActorFollowing.isOwned() === false) return
258 // Account follows one of our account?
259 let followType: 'account' | 'channel' = 'channel'
260 let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
262 // Account follows one of our channel?
264 user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
265 followType = 'account'
270 const followerAccount = actorFollow.ActorFollower.Account
271 const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })
273 if (await this.isBlockedByServerOrAccount(user, followerAccountWithActor)) return
275 logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
277 function settingGetter (user: MUserWithNotificationSetting) {
278 return user.NotificationSetting.newFollow
281 async function notificationCreator (user: MUserWithNotificationSetting) {
282 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
283 type: UserNotificationType.NEW_FOLLOW,
285 actorFollowId: actorFollow.id
287 notification.ActorFollow = actorFollow
292 function emailSender (emails: string[]) {
293 return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
296 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
299 private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
300 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
302 logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
304 function settingGetter (user: MUserWithNotificationSetting) {
305 return user.NotificationSetting.newInstanceFollower
308 async function notificationCreator (user: MUserWithNotificationSetting) {
309 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
310 type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
312 actorFollowId: actorFollow.id
314 notification.ActorFollow = actorFollow
319 function emailSender (emails: string[]) {
320 return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
323 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
326 private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
327 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
329 logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)
331 function settingGetter (user: MUserWithNotificationSetting) {
332 return user.NotificationSetting.autoInstanceFollowing
335 async function notificationCreator (user: MUserWithNotificationSetting) {
336 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
337 type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
339 actorFollowId: actorFollow.id
341 notification.ActorFollow = actorFollow
346 function emailSender (emails: string[]) {
347 return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
350 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
353 private async notifyModeratorsOfNewVideoAbuse (videoAbuse: MVideoAbuseVideo) {
354 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_ABUSES)
355 if (moderators.length === 0) return
357 logger.info('Notifying %s user/moderators of new video abuse %s.', moderators.length, videoAbuse.Video.url)
359 function settingGetter (user: MUserWithNotificationSetting) {
360 return user.NotificationSetting.videoAbuseAsModerator
363 async function notificationCreator (user: MUserWithNotificationSetting) {
364 const notification: UserNotificationModelForApi = await UserNotificationModel.create<UserNotificationModelForApi>({
365 type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
367 videoAbuseId: videoAbuse.id
369 notification.VideoAbuse = videoAbuse
374 function emailSender (emails: string[]) {
375 return Emailer.Instance.addVideoAbuseModeratorsNotification(emails, videoAbuse)
378 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
381 private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
382 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
383 if (moderators.length === 0) return
385 logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)
387 function settingGetter (user: MUserWithNotificationSetting) {
388 return user.NotificationSetting.videoAutoBlacklistAsModerator
391 async function notificationCreator (user: MUserWithNotificationSetting) {
392 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
393 type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
395 videoBlacklistId: videoBlacklist.id
397 notification.VideoBlacklist = videoBlacklist
402 function emailSender (emails: string[]) {
403 return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
406 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
409 private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
410 const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
413 logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
415 function settingGetter (user: MUserWithNotificationSetting) {
416 return user.NotificationSetting.blacklistOnMyVideo
419 async function notificationCreator (user: MUserWithNotificationSetting) {
420 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
421 type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
423 videoBlacklistId: videoBlacklist.id
425 notification.VideoBlacklist = videoBlacklist
430 function emailSender (emails: string[]) {
431 return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
434 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
437 private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
438 const user = await UserModel.loadByVideoId(video.id)
441 logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
443 function settingGetter (user: MUserWithNotificationSetting) {
444 return user.NotificationSetting.blacklistOnMyVideo
447 async function notificationCreator (user: MUserWithNotificationSetting) {
448 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
449 type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
453 notification.Video = video
458 function emailSender (emails: string[]) {
459 return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
462 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
465 private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
466 const user = await UserModel.loadByVideoId(video.id)
469 logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
471 function settingGetter (user: MUserWithNotificationSetting) {
472 return user.NotificationSetting.myVideoPublished
475 async function notificationCreator (user: MUserWithNotificationSetting) {
476 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
477 type: UserNotificationType.MY_VIDEO_PUBLISHED,
481 notification.Video = video
486 function emailSender (emails: string[]) {
487 return Emailer.Instance.myVideoPublishedNotification(emails, video)
490 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
493 private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
494 const user = await UserModel.loadByVideoImportId(videoImport.id)
497 logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
499 function settingGetter (user: MUserWithNotificationSetting) {
500 return user.NotificationSetting.myVideoImportFinished
503 async function notificationCreator (user: MUserWithNotificationSetting) {
504 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
505 type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
507 videoImportId: videoImport.id
509 notification.VideoImport = videoImport
514 function emailSender (emails: string[]) {
516 ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
517 : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
520 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
523 private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
524 const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
525 if (moderators.length === 0) return
528 'Notifying %s moderators of new user registration of %s.',
529 moderators.length, registeredUser.username
532 function settingGetter (user: MUserWithNotificationSetting) {
533 return user.NotificationSetting.newUserRegistration
536 async function notificationCreator (user: MUserWithNotificationSetting) {
537 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
538 type: UserNotificationType.NEW_USER_REGISTRATION,
540 accountId: registeredUser.Account.id
542 notification.Account = registeredUser.Account
547 function emailSender (emails: string[]) {
548 return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
551 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
554 private async notify<T extends MUserWithNotificationSetting> (options: {
556 notificationCreator: (user: T) => Promise<UserNotificationModelForApi>
557 emailSender: (emails: string[]) => void
558 settingGetter: (user: T) => UserNotificationSettingValue
560 const emails: string[] = []
562 for (const user of options.users) {
563 if (this.isWebNotificationEnabled(options.settingGetter(user))) {
564 const notification = await options.notificationCreator(user)
566 PeerTubeSocket.Instance.sendNotification(user.id, notification)
569 if (this.isEmailEnabled(user, options.settingGetter(user))) {
570 emails.push(user.email)
574 if (emails.length !== 0) {
575 options.emailSender(emails)
579 private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
580 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
582 return value & UserNotificationSettingValue.EMAIL
585 private isWebNotificationEnabled (value: UserNotificationSettingValue) {
586 return value & UserNotificationSettingValue.WEB
589 private async isBlockedByServerOrAccount (user: MUserAccount, targetAccount: MAccountDefault) {
590 const serverAccountId = (await getServerActor()).Account.id
591 const sourceAccounts = [ serverAccountId, user.Account.id ]
593 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, targetAccount.id)
594 if (accountMutedHash[serverAccountId] || accountMutedHash[user.Account.id]) return true
596 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, targetAccount.Actor.serverId)
597 if (instanceMutedHash[serverAccountId] || instanceMutedHash[user.Account.id]) return true
602 static get Instance () {
603 return this.instance || (this.instance = new this())
607 // ---------------------------------------------------------------------------