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/typings/models/user'
11 import { MVideoImportVideo } from '@server/typings/models/video/video-import'
12 import { UserNotificationSettingValue, UserNotificationType, UserRight } from '../../shared/models/users'
13 import { VideoAbuse, VideoPrivacy, VideoState } from '../../shared/models/videos'
14 import { logger } from '../helpers/logger'
15 import { CONFIG } from '../initializers/config'
16 import { AccountBlocklistModel } from '../models/account/account-blocklist'
17 import { UserModel } from '../models/account/user'
18 import { UserNotificationModel } from '../models/account/user-notification'
19 import { MAccountServer, MActorFollowFull } from '../typings/models'
24 MVideoBlacklistLightVideo,
27 } from '../typings/models/video'
28 import { isBlockedByServerOrAccount } from './blocklist'
29 import { Emailer } from './emailer'
30 import { PeerTubeSocket } from './peertube-socket'
34 private static instance: Notifier
36 private constructor () {
39 notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
40 // Only notify on public and published videos which are not blacklisted
41 if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return
43 this.notifySubscribersOfNewVideo(video)
44 .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
47 notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
48 // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
49 if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return
51 this.notifyOwnedVideoHasBeenPublished(video)
52 .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
55 notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
56 // don't notify if video is still blacklisted or waiting for transcoding
57 if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
59 this.notifyOwnedVideoHasBeenPublished(video)
60 .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
63 notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
64 // don't notify if video is still waiting for transcoding or scheduled update
65 if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
67 this.notifyOwnedVideoHasBeenPublished(video)
69 logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })
73 notifyOnNewComment (comment: MCommentOwnerVideo): void {
74 this.notifyVideoOwnerOfNewComment(comment)
75 .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
77 this.notifyOfCommentMention(comment)
78 .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
81 notifyOnNewVideoAbuse (parameters: { videoAbuse: VideoAbuse, videoAbuseInstance: MVideoAbuseVideo, reporter: string }): void {
82 this.notifyModeratorsOfNewVideoAbuse(parameters)
83 .catch(err => logger.error('Cannot notify of new video abuse of video %s.', parameters.videoAbuseInstance.Video.url, { err }))
86 notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void {
87 this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist)
88 .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err }))
91 notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
92 this.notifyVideoOwnerOfBlacklist(videoBlacklist)
93 .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
96 notifyOnVideoUnblacklist (video: MVideoFullLight): void {
97 this.notifyVideoOwnerOfUnblacklist(video)
98 .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
101 notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
102 this.notifyOwnerVideoImportIsFinished(videoImport, success)
103 .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
106 notifyOnNewUserRegistration (user: MUserDefault): void {
107 this.notifyModeratorsOfNewUserRegistration(user)
108 .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
111 notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
112 this.notifyUserOfNewActorFollow(actorFollow)
115 'Cannot notify owner of channel %s of a new follow by %s.',
116 actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
117 actorFollow.ActorFollower.Account.getDisplayName(),
123 notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
124 this.notifyAdminsOfNewInstanceFollow(actorFollow)
126 logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
130 notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
131 this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
133 logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
137 private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
138 // List all followers that are users
139 const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
141 logger.info('Notifying %d users of new video %s.', users.length, video.url)
143 function settingGetter (user: MUserWithNotificationSetting) {
144 return user.NotificationSetting.newVideoFromSubscription
147 async function notificationCreator (user: MUserWithNotificationSetting) {
148 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
149 type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
153 notification.Video = video
158 function emailSender (emails: string[]) {
159 return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
162 return this.notify({ users, settingGetter, notificationCreator, emailSender })
165 private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
166 if (comment.Video.isOwned() === false) return
168 const user = await UserModel.loadByVideoId(comment.videoId)
170 // Not our user or user comments its own video
171 if (!user || comment.Account.userId === user.id) return
173 if (await this.isBlockedByServerOrUser(comment.Account, user)) return
175 logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
177 function settingGetter (user: MUserWithNotificationSetting) {
178 return user.NotificationSetting.newCommentOnMyVideo
181 async function notificationCreator (user: MUserWithNotificationSetting) {
182 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
183 type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
185 commentId: comment.id
187 notification.Comment = comment
192 function emailSender (emails: string[]) {
193 return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
196 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
199 private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
200 const extractedUsernames = comment.extractMentions()
202 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
203 { usernames: extractedUsernames, text: comment.text }
206 let users = await UserModel.listByUsernames(extractedUsernames)
208 if (comment.Video.isOwned()) {
209 const userException = await UserModel.loadByVideoId(comment.videoId)
210 users = users.filter(u => u.id !== userException.id)
213 // Don't notify if I mentioned myself
214 users = users.filter(u => u.Account.id !== comment.accountId)
216 if (users.length === 0) return
218 const serverAccountId = (await getServerActor()).Account.id
219 const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])
221 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
222 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)
224 logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
226 function settingGetter (user: MUserNotifSettingAccount) {
227 const accountId = user.Account.id
229 accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
230 accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
232 return UserNotificationSettingValue.NONE
235 return user.NotificationSetting.commentMention
238 async function notificationCreator (user: MUserNotifSettingAccount) {
239 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
240 type: UserNotificationType.COMMENT_MENTION,
242 commentId: comment.id
244 notification.Comment = comment
249 function emailSender (emails: string[]) {
250 return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
253 return this.notify({ users, settingGetter, notificationCreator, emailSender })
256 private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
257 if (actorFollow.ActorFollowing.isOwned() === false) return
259 // Account follows one of our account?
260 let followType: 'account' | 'channel' = 'channel'
261 let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
263 // Account follows one of our channel?
265 user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
266 followType = 'account'
271 const followerAccount = actorFollow.ActorFollower.Account
272 const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })
274 if (await this.isBlockedByServerOrUser(followerAccountWithActor, user)) return
276 logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
278 function settingGetter (user: MUserWithNotificationSetting) {
279 return user.NotificationSetting.newFollow
282 async function notificationCreator (user: MUserWithNotificationSetting) {
283 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
284 type: UserNotificationType.NEW_FOLLOW,
286 actorFollowId: actorFollow.id
288 notification.ActorFollow = actorFollow
293 function emailSender (emails: string[]) {
294 return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
297 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
300 private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
301 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
303 const follower = Object.assign(actorFollow.ActorFollower.Account, { Actor: actorFollow.ActorFollower })
304 if (await this.isBlockedByServerOrUser(follower)) return
306 logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
308 function settingGetter (user: MUserWithNotificationSetting) {
309 return user.NotificationSetting.newInstanceFollower
312 async function notificationCreator (user: MUserWithNotificationSetting) {
313 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
314 type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
316 actorFollowId: actorFollow.id
318 notification.ActorFollow = actorFollow
323 function emailSender (emails: string[]) {
324 return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
327 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
330 private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
331 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
333 logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)
335 function settingGetter (user: MUserWithNotificationSetting) {
336 return user.NotificationSetting.autoInstanceFollowing
339 async function notificationCreator (user: MUserWithNotificationSetting) {
340 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
341 type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
343 actorFollowId: actorFollow.id
345 notification.ActorFollow = actorFollow
350 function emailSender (emails: string[]) {
351 return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
354 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
357 private async notifyModeratorsOfNewVideoAbuse (parameters: {
358 videoAbuse: VideoAbuse
359 videoAbuseInstance: MVideoAbuseVideo
362 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_ABUSES)
363 if (moderators.length === 0) return
365 logger.info('Notifying %s user/moderators of new video abuse %s.', moderators.length, parameters.videoAbuseInstance.Video.url)
367 function settingGetter (user: MUserWithNotificationSetting) {
368 return user.NotificationSetting.videoAbuseAsModerator
371 async function notificationCreator (user: MUserWithNotificationSetting) {
372 const notification: UserNotificationModelForApi = await UserNotificationModel.create<UserNotificationModelForApi>({
373 type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
375 videoAbuseId: parameters.videoAbuse.id
377 notification.VideoAbuse = parameters.videoAbuseInstance
382 function emailSender (emails: string[]) {
383 return Emailer.Instance.addVideoAbuseModeratorsNotification(emails, parameters)
386 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
389 private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
390 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
391 if (moderators.length === 0) return
393 logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)
395 function settingGetter (user: MUserWithNotificationSetting) {
396 return user.NotificationSetting.videoAutoBlacklistAsModerator
399 async function notificationCreator (user: MUserWithNotificationSetting) {
400 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
401 type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
403 videoBlacklistId: videoBlacklist.id
405 notification.VideoBlacklist = videoBlacklist
410 function emailSender (emails: string[]) {
411 return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
414 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
417 private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
418 const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
421 logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
423 function settingGetter (user: MUserWithNotificationSetting) {
424 return user.NotificationSetting.blacklistOnMyVideo
427 async function notificationCreator (user: MUserWithNotificationSetting) {
428 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
429 type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
431 videoBlacklistId: videoBlacklist.id
433 notification.VideoBlacklist = videoBlacklist
438 function emailSender (emails: string[]) {
439 return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
442 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
445 private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
446 const user = await UserModel.loadByVideoId(video.id)
449 logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
451 function settingGetter (user: MUserWithNotificationSetting) {
452 return user.NotificationSetting.blacklistOnMyVideo
455 async function notificationCreator (user: MUserWithNotificationSetting) {
456 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
457 type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
461 notification.Video = video
466 function emailSender (emails: string[]) {
467 return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
470 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
473 private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
474 const user = await UserModel.loadByVideoId(video.id)
477 logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
479 function settingGetter (user: MUserWithNotificationSetting) {
480 return user.NotificationSetting.myVideoPublished
483 async function notificationCreator (user: MUserWithNotificationSetting) {
484 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
485 type: UserNotificationType.MY_VIDEO_PUBLISHED,
489 notification.Video = video
494 function emailSender (emails: string[]) {
495 return Emailer.Instance.myVideoPublishedNotification(emails, video)
498 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
501 private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
502 const user = await UserModel.loadByVideoImportId(videoImport.id)
505 logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
507 function settingGetter (user: MUserWithNotificationSetting) {
508 return user.NotificationSetting.myVideoImportFinished
511 async function notificationCreator (user: MUserWithNotificationSetting) {
512 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
513 type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
515 videoImportId: videoImport.id
517 notification.VideoImport = videoImport
522 function emailSender (emails: string[]) {
524 ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
525 : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
528 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
531 private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
532 const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
533 if (moderators.length === 0) return
536 'Notifying %s moderators of new user registration of %s.',
537 moderators.length, registeredUser.username
540 function settingGetter (user: MUserWithNotificationSetting) {
541 return user.NotificationSetting.newUserRegistration
544 async function notificationCreator (user: MUserWithNotificationSetting) {
545 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
546 type: UserNotificationType.NEW_USER_REGISTRATION,
548 accountId: registeredUser.Account.id
550 notification.Account = registeredUser.Account
555 function emailSender (emails: string[]) {
556 return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
559 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
562 private async notify<T extends MUserWithNotificationSetting> (options: {
564 notificationCreator: (user: T) => Promise<UserNotificationModelForApi>
565 emailSender: (emails: string[]) => void
566 settingGetter: (user: T) => UserNotificationSettingValue
568 const emails: string[] = []
570 for (const user of options.users) {
571 if (this.isWebNotificationEnabled(options.settingGetter(user))) {
572 const notification = await options.notificationCreator(user)
574 PeerTubeSocket.Instance.sendNotification(user.id, notification)
577 if (this.isEmailEnabled(user, options.settingGetter(user))) {
578 emails.push(user.email)
582 if (emails.length !== 0) {
583 options.emailSender(emails)
587 private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
588 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
590 return value & UserNotificationSettingValue.EMAIL
593 private isWebNotificationEnabled (value: UserNotificationSettingValue) {
594 return value & UserNotificationSettingValue.WEB
597 private isBlockedByServerOrUser (targetAccount: MAccountServer, user?: MUserAccount) {
598 return isBlockedByServerOrAccount(targetAccount, user?.Account)
601 static get Instance () {
602 return this.instance || (this.instance = new this())
606 // ---------------------------------------------------------------------------