1 import { UserNotificationSettingValue, UserNotificationType, UserRight } from '../../shared/models/users'
2 import { logger } from '../helpers/logger'
3 import { VideoModel } from '../models/video/video'
4 import { Emailer } from './emailer'
5 import { UserNotificationModel } from '../models/account/user-notification'
6 import { VideoCommentModel } from '../models/video/video-comment'
7 import { UserModel } from '../models/account/user'
8 import { PeerTubeSocket } from './peertube-socket'
9 import { CONFIG } from '../initializers/config'
10 import { VideoPrivacy, VideoState } from '../../shared/models/videos'
11 import { VideoBlacklistModel } from '../models/video/video-blacklist'
12 import * as Bluebird from 'bluebird'
13 import { VideoImportModel } from '../models/video/video-import'
14 import { AccountBlocklistModel } from '../models/account/account-blocklist'
22 } from '../typings/models/video'
23 import { MUser, MUserAccount, MUserWithNotificationSetting, UserNotificationModelForApi } from '@server/typings/models/user'
24 import { MActorFollowActors, MActorFollowFull } from '../typings/models'
25 import { ActorFollowModel } from '../models/activitypub/actor-follow'
26 import { MVideoImportVideo } from '@server/typings/models/video/video-import'
27 import { AccountModel } from '@server/models/account/account'
31 private static instance: Notifier
33 private constructor () {}
35 notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
36 // Only notify on public and published videos which are not blacklisted
37 if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return
39 this.notifySubscribersOfNewVideo(video)
40 .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
43 notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
44 // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
45 if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return
47 this.notifyOwnedVideoHasBeenPublished(video)
48 .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
51 notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
52 // don't notify if video is still blacklisted or waiting for transcoding
53 if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
55 this.notifyOwnedVideoHasBeenPublished(video)
56 .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
59 notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
60 // don't notify if video is still waiting for transcoding or scheduled update
61 if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
63 this.notifyOwnedVideoHasBeenPublished(video)
64 .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
67 notifyOnNewComment (comment: MCommentOwnerVideo): void {
68 this.notifyVideoOwnerOfNewComment(comment)
69 .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
71 this.notifyOfCommentMention(comment)
72 .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
75 notifyOnNewVideoAbuse (videoAbuse: MVideoAbuseVideo): void {
76 this.notifyModeratorsOfNewVideoAbuse(videoAbuse)
77 .catch(err => logger.error('Cannot notify of new video abuse of video %s.', videoAbuse.Video.url, { err }))
80 notifyOnVideoAutoBlacklist (video: MVideo): void {
81 this.notifyModeratorsOfVideoAutoBlacklist(video)
82 .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', video.url, { err }))
85 notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
86 this.notifyVideoOwnerOfBlacklist(videoBlacklist)
87 .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
90 notifyOnVideoUnblacklist (video: MVideo): void {
91 this.notifyVideoOwnerOfUnblacklist(video)
92 .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
95 notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
96 this.notifyOwnerVideoImportIsFinished(videoImport, success)
97 .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
100 notifyOnNewUserRegistration (user: MUserAccount): void {
101 this.notifyModeratorsOfNewUserRegistration(user)
102 .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
105 notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
106 this.notifyUserOfNewActorFollow(actorFollow)
109 'Cannot notify owner of channel %s of a new follow by %s.',
110 actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
111 actorFollow.ActorFollower.Account.getDisplayName(),
117 notifyOfNewInstanceFollow (actorFollow: MActorFollowActors): void {
118 this.notifyAdminsOfNewInstanceFollow(actorFollow)
120 logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
124 private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
125 // List all followers that are users
126 const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
128 logger.info('Notifying %d users of new video %s.', users.length, video.url)
130 function settingGetter (user: UserModel) {
131 return user.NotificationSetting.newVideoFromSubscription
134 async function notificationCreator (user: UserModel) {
135 const notification = await UserNotificationModel.create({
136 type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
140 notification.Video = video as VideoModel
145 function emailSender (emails: string[]) {
146 return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
149 return this.notify({ users, settingGetter, notificationCreator, emailSender })
152 private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
153 if (comment.Video.isOwned() === false) return
155 const user = await UserModel.loadByVideoId(comment.videoId)
157 // Not our user or user comments its own video
158 if (!user || comment.Account.userId === user.id) return
160 const accountMuted = await AccountBlocklistModel.isAccountMutedBy(user.Account.id, comment.accountId)
161 if (accountMuted) return
163 logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
165 function settingGetter (user: UserModel) {
166 return user.NotificationSetting.newCommentOnMyVideo
169 async function notificationCreator (user: UserModel) {
170 const notification = await UserNotificationModel.create({
171 type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
173 commentId: comment.id
175 notification.Comment = comment as VideoCommentModel
180 function emailSender (emails: string[]) {
181 return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
184 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
187 private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
188 const extractedUsernames = comment.extractMentions()
190 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
191 { usernames: extractedUsernames, text: comment.text }
194 let users = await UserModel.listByUsernames(extractedUsernames)
196 if (comment.Video.isOwned()) {
197 const userException = await UserModel.loadByVideoId(comment.videoId)
198 users = users.filter(u => u.id !== userException.id)
201 // Don't notify if I mentioned myself
202 users = users.filter(u => u.Account.id !== comment.accountId)
204 if (users.length === 0) return
206 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(users.map(u => u.Account.id), comment.accountId)
208 logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
210 function settingGetter (user: UserModel) {
211 if (accountMutedHash[user.Account.id] === true) return UserNotificationSettingValue.NONE
213 return user.NotificationSetting.commentMention
216 async function notificationCreator (user: UserModel) {
217 const notification = await UserNotificationModel.create({
218 type: UserNotificationType.COMMENT_MENTION,
220 commentId: comment.id
222 notification.Comment = comment as VideoCommentModel
227 function emailSender (emails: string[]) {
228 return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
231 return this.notify({ users, settingGetter, notificationCreator, emailSender })
234 private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
235 if (actorFollow.ActorFollowing.isOwned() === false) return
237 // Account follows one of our account?
238 let followType: 'account' | 'channel' = 'channel'
239 let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
241 // Account follows one of our channel?
243 user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
244 followType = 'account'
249 const followerAccount = actorFollow.ActorFollower.Account
251 const accountMuted = await AccountBlocklistModel.isAccountMutedBy(user.Account.id, followerAccount.id)
252 if (accountMuted) return
254 logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
256 function settingGetter (user: UserModel) {
257 return user.NotificationSetting.newFollow
260 async function notificationCreator (user: UserModel) {
261 const notification = await UserNotificationModel.create({
262 type: UserNotificationType.NEW_FOLLOW,
264 actorFollowId: actorFollow.id
266 notification.ActorFollow = actorFollow as ActorFollowModel
271 function emailSender (emails: string[]) {
272 return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
275 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
278 private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowActors) {
279 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
281 logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
283 function settingGetter (user: UserModel) {
284 return user.NotificationSetting.newInstanceFollower
287 async function notificationCreator (user: UserModel) {
288 const notification = await UserNotificationModel.create({
289 type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
291 actorFollowId: actorFollow.id
293 notification.ActorFollow = actorFollow as ActorFollowModel
298 function emailSender (emails: string[]) {
299 return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
302 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
305 private async notifyModeratorsOfNewVideoAbuse (videoAbuse: MVideoAbuseVideo) {
306 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_ABUSES)
307 if (moderators.length === 0) return
309 logger.info('Notifying %s user/moderators of new video abuse %s.', moderators.length, videoAbuse.Video.url)
311 function settingGetter (user: UserModel) {
312 return user.NotificationSetting.videoAbuseAsModerator
315 async function notificationCreator (user: UserModel) {
316 const notification: UserNotificationModelForApi = await UserNotificationModel.create({
317 type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
319 videoAbuseId: videoAbuse.id
321 notification.VideoAbuse = videoAbuse
326 function emailSender (emails: string[]) {
327 return Emailer.Instance.addVideoAbuseModeratorsNotification(emails, videoAbuse)
330 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
333 private async notifyModeratorsOfVideoAutoBlacklist (video: MVideo) {
334 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
335 if (moderators.length === 0) return
337 logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, video.url)
339 function settingGetter (user: UserModel) {
340 return user.NotificationSetting.videoAutoBlacklistAsModerator
342 async function notificationCreator (user: UserModel) {
344 const notification = await UserNotificationModel.create({
345 type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
349 notification.Video = video as VideoModel
354 function emailSender (emails: string[]) {
355 return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, video)
358 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
361 private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
362 const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
365 logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
367 function settingGetter (user: UserModel) {
368 return user.NotificationSetting.blacklistOnMyVideo
371 async function notificationCreator (user: UserModel) {
372 const notification = await UserNotificationModel.create({
373 type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
375 videoBlacklistId: videoBlacklist.id
377 notification.VideoBlacklist = videoBlacklist as VideoBlacklistModel
382 function emailSender (emails: string[]) {
383 return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
386 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
389 private async notifyVideoOwnerOfUnblacklist (video: MVideo) {
390 const user = await UserModel.loadByVideoId(video.id)
393 logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
395 function settingGetter (user: UserModel) {
396 return user.NotificationSetting.blacklistOnMyVideo
399 async function notificationCreator (user: UserModel) {
400 const notification = await UserNotificationModel.create({
401 type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
405 notification.Video = video as VideoModel
410 function emailSender (emails: string[]) {
411 return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
414 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
417 private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
418 const user = await UserModel.loadByVideoId(video.id)
421 logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
423 function settingGetter (user: UserModel) {
424 return user.NotificationSetting.myVideoPublished
427 async function notificationCreator (user: UserModel) {
428 const notification = await UserNotificationModel.create({
429 type: UserNotificationType.MY_VIDEO_PUBLISHED,
433 notification.Video = video as VideoModel
438 function emailSender (emails: string[]) {
439 return Emailer.Instance.myVideoPublishedNotification(emails, video)
442 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
445 private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
446 const user = await UserModel.loadByVideoImportId(videoImport.id)
449 logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
451 function settingGetter (user: UserModel) {
452 return user.NotificationSetting.myVideoImportFinished
455 async function notificationCreator (user: UserModel) {
456 const notification = await UserNotificationModel.create({
457 type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
459 videoImportId: videoImport.id
461 notification.VideoImport = videoImport as VideoImportModel
466 function emailSender (emails: string[]) {
468 ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
469 : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
472 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
475 private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserAccount) {
476 const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
477 if (moderators.length === 0) return
480 'Notifying %s moderators of new user registration of %s.',
481 moderators.length, registeredUser.username
484 function settingGetter (user: UserModel) {
485 return user.NotificationSetting.newUserRegistration
488 async function notificationCreator (user: UserModel) {
489 const notification = await UserNotificationModel.create({
490 type: UserNotificationType.NEW_USER_REGISTRATION,
492 accountId: registeredUser.Account.id
494 notification.Account = registeredUser.Account as AccountModel
499 function emailSender (emails: string[]) {
500 return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
503 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
506 private async notify (options: {
507 users: MUserWithNotificationSetting[],
508 notificationCreator: (user: MUserWithNotificationSetting) => Promise<UserNotificationModelForApi>,
509 emailSender: (emails: string[]) => Promise<any> | Bluebird<any>,
510 settingGetter: (user: MUserWithNotificationSetting) => UserNotificationSettingValue
512 const emails: string[] = []
514 for (const user of options.users) {
515 if (this.isWebNotificationEnabled(options.settingGetter(user))) {
516 const notification = await options.notificationCreator(user)
518 PeerTubeSocket.Instance.sendNotification(user.id, notification)
521 if (this.isEmailEnabled(user, options.settingGetter(user))) {
522 emails.push(user.email)
526 if (emails.length !== 0) {
527 await options.emailSender(emails)
531 private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
532 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
534 return value & UserNotificationSettingValue.EMAIL
537 private isWebNotificationEnabled (value: UserNotificationSettingValue) {
538 return value & UserNotificationSettingValue.WEB
541 static get Instance () {
542 return this.instance || (this.instance = new this())
546 // ---------------------------------------------------------------------------