1 import { getServerActor } from '@server/models/application/application'
2 import { ServerBlocklistModel } from '@server/models/server/server-blocklist'
7 MUserNotifSettingAccount,
8 MUserWithNotificationSetting,
9 UserNotificationModelForApi
10 } from '@server/types/models/user'
11 import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
12 import { MVideoImportVideo } from '@server/types/models/video/video-import'
13 import { Abuse } from '@shared/models'
14 import { UserNotificationSettingValue, UserNotificationType, UserRight } from '../../shared/models/users'
15 import { VideoPrivacy, VideoState } from '../../shared/models/videos'
16 import { logger } from '../helpers/logger'
17 import { CONFIG } from '../initializers/config'
18 import { AccountBlocklistModel } from '../models/account/account-blocklist'
19 import { UserModel } from '../models/account/user'
20 import { UserNotificationModel } from '../models/account/user-notification'
21 import { MAbuseFull, MAccountServer, MActorFollowFull } from '../types/models'
22 import { MCommentOwnerVideo, MVideoAccountLight, MVideoFullLight } from '../types/models/video'
23 import { isBlockedByServerOrAccount } from './blocklist'
24 import { Emailer } from './emailer'
25 import { PeerTubeSocket } from './peertube-socket'
29 private static instance: Notifier
31 private constructor () {
34 notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
35 // Only notify on public and published videos which are not blacklisted
36 if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return
38 this.notifySubscribersOfNewVideo(video)
39 .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
42 notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
43 // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
44 if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return
46 this.notifyOwnedVideoHasBeenPublished(video)
47 .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
50 notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
51 // don't notify if video is still blacklisted or waiting for transcoding
52 if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
54 this.notifyOwnedVideoHasBeenPublished(video)
55 .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
58 notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
59 // don't notify if video is still waiting for transcoding or scheduled update
60 if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
62 this.notifyOwnedVideoHasBeenPublished(video)
64 logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })
68 notifyOnNewComment (comment: MCommentOwnerVideo): void {
69 this.notifyVideoOwnerOfNewComment(comment)
70 .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
72 this.notifyOfCommentMention(comment)
73 .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
76 notifyOnNewAbuse (parameters: { abuse: Abuse, abuseInstance: MAbuseFull, reporter: string }): void {
77 this.notifyModeratorsOfNewAbuse(parameters)
78 .catch(err => logger.error('Cannot notify of new abuse %d.', parameters.abuseInstance.id, { err }))
81 notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void {
82 this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist)
83 .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err }))
86 notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
87 this.notifyVideoOwnerOfBlacklist(videoBlacklist)
88 .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
91 notifyOnVideoUnblacklist (video: MVideoFullLight): void {
92 this.notifyVideoOwnerOfUnblacklist(video)
93 .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
96 notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
97 this.notifyOwnerVideoImportIsFinished(videoImport, success)
98 .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
101 notifyOnNewUserRegistration (user: MUserDefault): void {
102 this.notifyModeratorsOfNewUserRegistration(user)
103 .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
106 notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
107 this.notifyUserOfNewActorFollow(actorFollow)
110 'Cannot notify owner of channel %s of a new follow by %s.',
111 actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
112 actorFollow.ActorFollower.Account.getDisplayName(),
118 notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
119 this.notifyAdminsOfNewInstanceFollow(actorFollow)
121 logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
125 notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
126 this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
128 logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
132 private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
133 // List all followers that are users
134 const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
136 logger.info('Notifying %d users of new video %s.', users.length, video.url)
138 function settingGetter (user: MUserWithNotificationSetting) {
139 return user.NotificationSetting.newVideoFromSubscription
142 async function notificationCreator (user: MUserWithNotificationSetting) {
143 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
144 type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
148 notification.Video = video
153 function emailSender (emails: string[]) {
154 return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
157 return this.notify({ users, settingGetter, notificationCreator, emailSender })
160 private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
161 if (comment.Video.isOwned() === false) return
163 const user = await UserModel.loadByVideoId(comment.videoId)
165 // Not our user or user comments its own video
166 if (!user || comment.Account.userId === user.id) return
168 if (await this.isBlockedByServerOrUser(comment.Account, user)) return
170 logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
172 function settingGetter (user: MUserWithNotificationSetting) {
173 return user.NotificationSetting.newCommentOnMyVideo
176 async function notificationCreator (user: MUserWithNotificationSetting) {
177 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
178 type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
180 commentId: comment.id
182 notification.Comment = comment
187 function emailSender (emails: string[]) {
188 return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
191 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
194 private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
195 const extractedUsernames = comment.extractMentions()
197 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
198 { usernames: extractedUsernames, text: comment.text }
201 let users = await UserModel.listByUsernames(extractedUsernames)
203 if (comment.Video.isOwned()) {
204 const userException = await UserModel.loadByVideoId(comment.videoId)
205 users = users.filter(u => u.id !== userException.id)
208 // Don't notify if I mentioned myself
209 users = users.filter(u => u.Account.id !== comment.accountId)
211 if (users.length === 0) return
213 const serverAccountId = (await getServerActor()).Account.id
214 const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])
216 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
217 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)
219 logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
221 function settingGetter (user: MUserNotifSettingAccount) {
222 const accountId = user.Account.id
224 accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
225 accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
227 return UserNotificationSettingValue.NONE
230 return user.NotificationSetting.commentMention
233 async function notificationCreator (user: MUserNotifSettingAccount) {
234 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
235 type: UserNotificationType.COMMENT_MENTION,
237 commentId: comment.id
239 notification.Comment = comment
244 function emailSender (emails: string[]) {
245 return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
248 return this.notify({ users, settingGetter, notificationCreator, emailSender })
251 private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
252 if (actorFollow.ActorFollowing.isOwned() === false) return
254 // Account follows one of our account?
255 let followType: 'account' | 'channel' = 'channel'
256 let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
258 // Account follows one of our channel?
260 user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
261 followType = 'account'
266 const followerAccount = actorFollow.ActorFollower.Account
267 const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })
269 if (await this.isBlockedByServerOrUser(followerAccountWithActor, user)) return
271 logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
273 function settingGetter (user: MUserWithNotificationSetting) {
274 return user.NotificationSetting.newFollow
277 async function notificationCreator (user: MUserWithNotificationSetting) {
278 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
279 type: UserNotificationType.NEW_FOLLOW,
281 actorFollowId: actorFollow.id
283 notification.ActorFollow = actorFollow
288 function emailSender (emails: string[]) {
289 return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
292 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
295 private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
296 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
298 const follower = Object.assign(actorFollow.ActorFollower.Account, { Actor: actorFollow.ActorFollower })
299 if (await this.isBlockedByServerOrUser(follower)) return
301 logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
303 function settingGetter (user: MUserWithNotificationSetting) {
304 return user.NotificationSetting.newInstanceFollower
307 async function notificationCreator (user: MUserWithNotificationSetting) {
308 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
309 type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
311 actorFollowId: actorFollow.id
313 notification.ActorFollow = actorFollow
318 function emailSender (emails: string[]) {
319 return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
322 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
325 private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
326 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
328 logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)
330 function settingGetter (user: MUserWithNotificationSetting) {
331 return user.NotificationSetting.autoInstanceFollowing
334 async function notificationCreator (user: MUserWithNotificationSetting) {
335 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
336 type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
338 actorFollowId: actorFollow.id
340 notification.ActorFollow = actorFollow
345 function emailSender (emails: string[]) {
346 return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
349 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
352 private async notifyModeratorsOfNewAbuse (parameters: {
354 abuseInstance: MAbuseFull
357 const { abuse, abuseInstance } = parameters
359 const moderators = await UserModel.listWithRight(UserRight.MANAGE_ABUSES)
360 if (moderators.length === 0) return
362 const url = abuseInstance.VideoAbuse?.Video?.url ||
363 abuseInstance.VideoCommentAbuse?.VideoComment?.url ||
364 abuseInstance.FlaggedAccount.Actor.url
366 logger.info('Notifying %s user/moderators of new abuse %s.', moderators.length, url)
368 function settingGetter (user: MUserWithNotificationSetting) {
369 return user.NotificationSetting.abuseAsModerator
372 async function notificationCreator (user: MUserWithNotificationSetting) {
373 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
374 type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
378 notification.Abuse = abuseInstance
383 function emailSender (emails: string[]) {
384 return Emailer.Instance.addAbuseModeratorsNotification(emails, parameters)
387 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
390 private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
391 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
392 if (moderators.length === 0) return
394 logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)
396 function settingGetter (user: MUserWithNotificationSetting) {
397 return user.NotificationSetting.videoAutoBlacklistAsModerator
400 async function notificationCreator (user: MUserWithNotificationSetting) {
401 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
402 type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
404 videoBlacklistId: videoBlacklist.id
406 notification.VideoBlacklist = videoBlacklist
411 function emailSender (emails: string[]) {
412 return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
415 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
418 private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
419 const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
422 logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
424 function settingGetter (user: MUserWithNotificationSetting) {
425 return user.NotificationSetting.blacklistOnMyVideo
428 async function notificationCreator (user: MUserWithNotificationSetting) {
429 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
430 type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
432 videoBlacklistId: videoBlacklist.id
434 notification.VideoBlacklist = videoBlacklist
439 function emailSender (emails: string[]) {
440 return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
443 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
446 private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
447 const user = await UserModel.loadByVideoId(video.id)
450 logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
452 function settingGetter (user: MUserWithNotificationSetting) {
453 return user.NotificationSetting.blacklistOnMyVideo
456 async function notificationCreator (user: MUserWithNotificationSetting) {
457 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
458 type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
462 notification.Video = video
467 function emailSender (emails: string[]) {
468 return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
471 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
474 private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
475 const user = await UserModel.loadByVideoId(video.id)
478 logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
480 function settingGetter (user: MUserWithNotificationSetting) {
481 return user.NotificationSetting.myVideoPublished
484 async function notificationCreator (user: MUserWithNotificationSetting) {
485 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
486 type: UserNotificationType.MY_VIDEO_PUBLISHED,
490 notification.Video = video
495 function emailSender (emails: string[]) {
496 return Emailer.Instance.myVideoPublishedNotification(emails, video)
499 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
502 private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
503 const user = await UserModel.loadByVideoImportId(videoImport.id)
506 logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
508 function settingGetter (user: MUserWithNotificationSetting) {
509 return user.NotificationSetting.myVideoImportFinished
512 async function notificationCreator (user: MUserWithNotificationSetting) {
513 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
514 type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
516 videoImportId: videoImport.id
518 notification.VideoImport = videoImport
523 function emailSender (emails: string[]) {
525 ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
526 : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
529 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
532 private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
533 const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
534 if (moderators.length === 0) return
537 'Notifying %s moderators of new user registration of %s.',
538 moderators.length, registeredUser.username
541 function settingGetter (user: MUserWithNotificationSetting) {
542 return user.NotificationSetting.newUserRegistration
545 async function notificationCreator (user: MUserWithNotificationSetting) {
546 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
547 type: UserNotificationType.NEW_USER_REGISTRATION,
549 accountId: registeredUser.Account.id
551 notification.Account = registeredUser.Account
556 function emailSender (emails: string[]) {
557 return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
560 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
563 private async notify<T extends MUserWithNotificationSetting> (options: {
565 notificationCreator: (user: T) => Promise<UserNotificationModelForApi>
566 emailSender: (emails: string[]) => void
567 settingGetter: (user: T) => UserNotificationSettingValue
569 const emails: string[] = []
571 for (const user of options.users) {
572 if (this.isWebNotificationEnabled(options.settingGetter(user))) {
573 const notification = await options.notificationCreator(user)
575 PeerTubeSocket.Instance.sendNotification(user.id, notification)
578 if (this.isEmailEnabled(user, options.settingGetter(user))) {
579 emails.push(user.email)
583 if (emails.length !== 0) {
584 options.emailSender(emails)
588 private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
589 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
591 return value & UserNotificationSettingValue.EMAIL
594 private isWebNotificationEnabled (value: UserNotificationSettingValue) {
595 return value & UserNotificationSettingValue.WEB
598 private isBlockedByServerOrUser (targetAccount: MAccountServer, user?: MUserAccount) {
599 return isBlockedByServerOrAccount(targetAccount, user?.Account)
602 static get Instance () {
603 return this.instance || (this.instance = new this())
607 // ---------------------------------------------------------------------------