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 * as Bluebird from 'bluebird'
10 import { AccountBlocklistModel } from '../models/account/account-blocklist'
15 MVideoBlacklistLightVideo,
18 } 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 () {}
37 notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
38 // Only notify on public and published videos which are not blacklisted
39 if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return
41 this.notifySubscribersOfNewVideo(video)
42 .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
45 notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
46 // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
47 if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return
49 this.notifyOwnedVideoHasBeenPublished(video)
50 .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
53 notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
54 // don't notify if video is still blacklisted or waiting for transcoding
55 if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
57 this.notifyOwnedVideoHasBeenPublished(video)
58 .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
61 notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
62 // don't notify if video is still waiting for transcoding or scheduled update
63 if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
65 this.notifyOwnedVideoHasBeenPublished(video)
66 .catch(err => logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })) // tslint:disable-line:max-line-length
69 notifyOnNewComment (comment: MCommentOwnerVideo): void {
70 this.notifyVideoOwnerOfNewComment(comment)
71 .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
73 this.notifyOfCommentMention(comment)
74 .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
77 notifyOnNewVideoAbuse (videoAbuse: MVideoAbuseVideo): void {
78 this.notifyModeratorsOfNewVideoAbuse(videoAbuse)
79 .catch(err => logger.error('Cannot notify of new video abuse of video %s.', videoAbuse.Video.url, { err }))
82 notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void {
83 this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist)
84 .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err }))
87 notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
88 this.notifyVideoOwnerOfBlacklist(videoBlacklist)
89 .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
92 notifyOnVideoUnblacklist (video: MVideoFullLight): void {
93 this.notifyVideoOwnerOfUnblacklist(video)
94 .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
97 notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
98 this.notifyOwnerVideoImportIsFinished(videoImport, success)
99 .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
102 notifyOnNewUserRegistration (user: MUserDefault): void {
103 this.notifyModeratorsOfNewUserRegistration(user)
104 .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
107 notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
108 this.notifyUserOfNewActorFollow(actorFollow)
111 'Cannot notify owner of channel %s of a new follow by %s.',
112 actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
113 actorFollow.ActorFollower.Account.getDisplayName(),
119 notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
120 this.notifyAdminsOfNewInstanceFollow(actorFollow)
122 logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
126 notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
127 this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
129 logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
133 private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
134 // List all followers that are users
135 const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
137 logger.info('Notifying %d users of new video %s.', users.length, video.url)
139 function settingGetter (user: MUserWithNotificationSetting) {
140 return user.NotificationSetting.newVideoFromSubscription
143 async function notificationCreator (user: MUserWithNotificationSetting) {
144 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
145 type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
149 notification.Video = video
154 function emailSender (emails: string[]) {
155 return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
158 return this.notify({ users, settingGetter, notificationCreator, emailSender })
161 private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
162 if (comment.Video.isOwned() === false) return
164 const user = await UserModel.loadByVideoId(comment.videoId)
166 // Not our user or user comments its own video
167 if (!user || comment.Account.userId === user.id) return
169 if (await this.isBlockedByServerOrAccount(user, comment.Account)) return
171 logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
173 function settingGetter (user: MUserWithNotificationSetting) {
174 return user.NotificationSetting.newCommentOnMyVideo
177 async function notificationCreator (user: MUserWithNotificationSetting) {
178 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
179 type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
181 commentId: comment.id
183 notification.Comment = comment
188 function emailSender (emails: string[]) {
189 return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
192 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
195 private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
196 const extractedUsernames = comment.extractMentions()
198 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
199 { usernames: extractedUsernames, text: comment.text }
202 let users = await UserModel.listByUsernames(extractedUsernames)
204 if (comment.Video.isOwned()) {
205 const userException = await UserModel.loadByVideoId(comment.videoId)
206 users = users.filter(u => u.id !== userException.id)
209 // Don't notify if I mentioned myself
210 users = users.filter(u => u.Account.id !== comment.accountId)
212 if (users.length === 0) return
214 const serverAccountId = (await getServerActor()).Account.id
215 const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])
217 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
218 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)
220 logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
222 function settingGetter (user: MUserNotifSettingAccount) {
223 const accountId = user.Account.id
225 accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
226 accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
228 return UserNotificationSettingValue.NONE
231 return user.NotificationSetting.commentMention
234 async function notificationCreator (user: MUserNotifSettingAccount) {
235 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
236 type: UserNotificationType.COMMENT_MENTION,
238 commentId: comment.id
240 notification.Comment = comment
245 function emailSender (emails: string[]) {
246 return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
249 return this.notify({ users, settingGetter, notificationCreator, emailSender })
252 private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
253 if (actorFollow.ActorFollowing.isOwned() === false) return
255 // Account follows one of our account?
256 let followType: 'account' | 'channel' = 'channel'
257 let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
259 // Account follows one of our channel?
261 user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
262 followType = 'account'
267 const followerAccount = actorFollow.ActorFollower.Account
268 const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })
270 if (await this.isBlockedByServerOrAccount(user, followerAccountWithActor)) return
272 logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
274 function settingGetter (user: MUserWithNotificationSetting) {
275 return user.NotificationSetting.newFollow
278 async function notificationCreator (user: MUserWithNotificationSetting) {
279 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
280 type: UserNotificationType.NEW_FOLLOW,
282 actorFollowId: actorFollow.id
284 notification.ActorFollow = actorFollow
289 function emailSender (emails: string[]) {
290 return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
293 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
296 private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
297 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
299 logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
301 function settingGetter (user: MUserWithNotificationSetting) {
302 return user.NotificationSetting.newInstanceFollower
305 async function notificationCreator (user: MUserWithNotificationSetting) {
306 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
307 type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
309 actorFollowId: actorFollow.id
311 notification.ActorFollow = actorFollow
316 function emailSender (emails: string[]) {
317 return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
320 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
323 private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
324 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
326 logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)
328 function settingGetter (user: MUserWithNotificationSetting) {
329 return user.NotificationSetting.autoInstanceFollowing
332 async function notificationCreator (user: MUserWithNotificationSetting) {
333 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
334 type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
336 actorFollowId: actorFollow.id
338 notification.ActorFollow = actorFollow
343 function emailSender (emails: string[]) {
344 return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
347 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
350 private async notifyModeratorsOfNewVideoAbuse (videoAbuse: MVideoAbuseVideo) {
351 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_ABUSES)
352 if (moderators.length === 0) return
354 logger.info('Notifying %s user/moderators of new video abuse %s.', moderators.length, videoAbuse.Video.url)
356 function settingGetter (user: MUserWithNotificationSetting) {
357 return user.NotificationSetting.videoAbuseAsModerator
360 async function notificationCreator (user: MUserWithNotificationSetting) {
361 const notification: UserNotificationModelForApi = await UserNotificationModel.create<UserNotificationModelForApi>({
362 type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
364 videoAbuseId: videoAbuse.id
366 notification.VideoAbuse = videoAbuse
371 function emailSender (emails: string[]) {
372 return Emailer.Instance.addVideoAbuseModeratorsNotification(emails, videoAbuse)
375 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
378 private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
379 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
380 if (moderators.length === 0) return
382 logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)
384 function settingGetter (user: MUserWithNotificationSetting) {
385 return user.NotificationSetting.videoAutoBlacklistAsModerator
388 async function notificationCreator (user: MUserWithNotificationSetting) {
389 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
390 type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
392 videoBlacklistId: videoBlacklist.id
394 notification.VideoBlacklist = videoBlacklist
399 function emailSender (emails: string[]) {
400 return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
403 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
406 private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
407 const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
410 logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
412 function settingGetter (user: MUserWithNotificationSetting) {
413 return user.NotificationSetting.blacklistOnMyVideo
416 async function notificationCreator (user: MUserWithNotificationSetting) {
417 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
418 type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
420 videoBlacklistId: videoBlacklist.id
422 notification.VideoBlacklist = videoBlacklist
427 function emailSender (emails: string[]) {
428 return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
431 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
434 private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
435 const user = await UserModel.loadByVideoId(video.id)
438 logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
440 function settingGetter (user: MUserWithNotificationSetting) {
441 return user.NotificationSetting.blacklistOnMyVideo
444 async function notificationCreator (user: MUserWithNotificationSetting) {
445 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
446 type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
450 notification.Video = video
455 function emailSender (emails: string[]) {
456 return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
459 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
462 private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
463 const user = await UserModel.loadByVideoId(video.id)
466 logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
468 function settingGetter (user: MUserWithNotificationSetting) {
469 return user.NotificationSetting.myVideoPublished
472 async function notificationCreator (user: MUserWithNotificationSetting) {
473 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
474 type: UserNotificationType.MY_VIDEO_PUBLISHED,
478 notification.Video = video
483 function emailSender (emails: string[]) {
484 return Emailer.Instance.myVideoPublishedNotification(emails, video)
487 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
490 private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
491 const user = await UserModel.loadByVideoImportId(videoImport.id)
494 logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
496 function settingGetter (user: MUserWithNotificationSetting) {
497 return user.NotificationSetting.myVideoImportFinished
500 async function notificationCreator (user: MUserWithNotificationSetting) {
501 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
502 type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
504 videoImportId: videoImport.id
506 notification.VideoImport = videoImport
511 function emailSender (emails: string[]) {
513 ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
514 : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
517 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
520 private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
521 const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
522 if (moderators.length === 0) return
525 'Notifying %s moderators of new user registration of %s.',
526 moderators.length, registeredUser.username
529 function settingGetter (user: MUserWithNotificationSetting) {
530 return user.NotificationSetting.newUserRegistration
533 async function notificationCreator (user: MUserWithNotificationSetting) {
534 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
535 type: UserNotificationType.NEW_USER_REGISTRATION,
537 accountId: registeredUser.Account.id
539 notification.Account = registeredUser.Account
544 function emailSender (emails: string[]) {
545 return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
548 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
551 private async notify <T extends MUserWithNotificationSetting> (options: {
553 notificationCreator: (user: T) => Promise<UserNotificationModelForApi>,
554 emailSender: (emails: string[]) => Promise<any> | Bluebird<any>,
555 settingGetter: (user: T) => UserNotificationSettingValue
557 const emails: string[] = []
559 for (const user of options.users) {
560 if (this.isWebNotificationEnabled(options.settingGetter(user))) {
561 const notification = await options.notificationCreator(user)
563 PeerTubeSocket.Instance.sendNotification(user.id, notification)
566 if (this.isEmailEnabled(user, options.settingGetter(user))) {
567 emails.push(user.email)
571 if (emails.length !== 0) {
572 await options.emailSender(emails)
576 private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
577 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
579 return value & UserNotificationSettingValue.EMAIL
582 private isWebNotificationEnabled (value: UserNotificationSettingValue) {
583 return value & UserNotificationSettingValue.WEB
586 private async isBlockedByServerOrAccount (user: MUserAccount, targetAccount: MAccountDefault) {
587 const serverAccountId = (await getServerActor()).Account.id
588 const sourceAccounts = [ serverAccountId, user.Account.id ]
590 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, targetAccount.id)
591 if (accountMutedHash[serverAccountId] || accountMutedHash[user.Account.id]) return true
593 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, targetAccount.Actor.serverId)
594 if (instanceMutedHash[serverAccountId] || instanceMutedHash[user.Account.id]) return true
599 static get Instance () {
600 return this.instance || (this.instance = new this())
604 // ---------------------------------------------------------------------------