2fa320cd7527906ea36a879da967462fd18b9b6c
[oweals/peertube.git] / server / lib / notifier.ts
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/constants'
10 import { VideoPrivacy, VideoState } from '../../shared/models/videos'
11 import { VideoAbuseModel } from '../models/video/video-abuse'
12 import { VideoBlacklistModel } from '../models/video/video-blacklist'
13 import * as Bluebird from 'bluebird'
14 import { VideoImportModel } from '../models/video/video-import'
15 import { AccountBlocklistModel } from '../models/account/account-blocklist'
16 import { ActorFollowModel } from '../models/activitypub/actor-follow'
17 import { AccountModel } from '../models/account/account'
18
19 class Notifier {
20
21   private static instance: Notifier
22
23   private constructor () {}
24
25   notifyOnNewVideo (video: VideoModel): void {
26     // Only notify on public and published videos
27     if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED) return
28
29     this.notifySubscribersOfNewVideo(video)
30       .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
31   }
32
33   notifyOnPendingVideoPublished (video: VideoModel): void {
34     // Only notify on public videos that has been published while the user waited transcoding/scheduled update
35     if (video.waitTranscoding === false && !video.ScheduleVideoUpdate) return
36
37     this.notifyOwnedVideoHasBeenPublished(video)
38         .catch(err => logger.error('Cannot notify owner that its video %s has been published.', video.url, { err }))
39   }
40
41   notifyOnNewComment (comment: VideoCommentModel): void {
42     this.notifyVideoOwnerOfNewComment(comment)
43         .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
44
45     this.notifyOfCommentMention(comment)
46         .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
47   }
48
49   notifyOnNewVideoAbuse (videoAbuse: VideoAbuseModel): void {
50     this.notifyModeratorsOfNewVideoAbuse(videoAbuse)
51       .catch(err => logger.error('Cannot notify of new video abuse of video %s.', videoAbuse.Video.url, { err }))
52   }
53
54   notifyOnVideoBlacklist (videoBlacklist: VideoBlacklistModel): void {
55     this.notifyVideoOwnerOfBlacklist(videoBlacklist)
56       .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
57   }
58
59   notifyOnVideoUnblacklist (video: VideoModel): void {
60     this.notifyVideoOwnerOfUnblacklist(video)
61         .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', video.url, { err }))
62   }
63
64   notifyOnFinishedVideoImport (videoImport: VideoImportModel, success: boolean): void {
65     this.notifyOwnerVideoImportIsFinished(videoImport, success)
66       .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
67   }
68
69   notifyOnNewUserRegistration (user: UserModel): void {
70     this.notifyModeratorsOfNewUserRegistration(user)
71         .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
72   }
73
74   notifyOfNewFollow (actorFollow: ActorFollowModel): void {
75     this.notifyUserOfNewActorFollow(actorFollow)
76       .catch(err => {
77         logger.error(
78           'Cannot notify owner of channel %s of a new follow by %s.',
79           actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
80           actorFollow.ActorFollower.Account.getDisplayName(),
81           err
82         )
83       })
84   }
85
86   private async notifySubscribersOfNewVideo (video: VideoModel) {
87     // List all followers that are users
88     const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
89
90     logger.info('Notifying %d users of new video %s.', users.length, video.url)
91
92     function settingGetter (user: UserModel) {
93       return user.NotificationSetting.newVideoFromSubscription
94     }
95
96     async function notificationCreator (user: UserModel) {
97       const notification = await UserNotificationModel.create({
98         type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
99         userId: user.id,
100         videoId: video.id
101       })
102       notification.Video = video
103
104       return notification
105     }
106
107     function emailSender (emails: string[]) {
108       return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
109     }
110
111     return this.notify({ users, settingGetter, notificationCreator, emailSender })
112   }
113
114   private async notifyVideoOwnerOfNewComment (comment: VideoCommentModel) {
115     if (comment.Video.isOwned() === false) return
116
117     const user = await UserModel.loadByVideoId(comment.videoId)
118
119     // Not our user or user comments its own video
120     if (!user || comment.Account.userId === user.id) return
121
122     const accountMuted = await AccountBlocklistModel.isAccountMutedBy(user.Account.id, comment.accountId)
123     if (accountMuted) return
124
125     logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
126
127     function settingGetter (user: UserModel) {
128       return user.NotificationSetting.newCommentOnMyVideo
129     }
130
131     async function notificationCreator (user: UserModel) {
132       const notification = await UserNotificationModel.create({
133         type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
134         userId: user.id,
135         commentId: comment.id
136       })
137       notification.Comment = comment
138
139       return notification
140     }
141
142     function emailSender (emails: string[]) {
143       return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
144     }
145
146     return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
147   }
148
149   private async notifyOfCommentMention (comment: VideoCommentModel) {
150     const usernames = comment.extractMentions()
151     logger.debug('Extracted %d username from comment %s.', usernames.length, comment.url, { usernames, text: comment.text })
152
153     let users = await UserModel.listByUsernames(usernames)
154
155     if (comment.Video.isOwned()) {
156       const userException = await UserModel.loadByVideoId(comment.videoId)
157       users = users.filter(u => u.id !== userException.id)
158     }
159
160     // Don't notify if I mentioned myself
161     users = users.filter(u => u.Account.id !== comment.accountId)
162
163     if (users.length === 0) return
164
165     const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(users.map(u => u.Account.id), comment.accountId)
166
167     logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
168
169     function settingGetter (user: UserModel) {
170       if (accountMutedHash[user.Account.id] === true) return UserNotificationSettingValue.NONE
171
172       return user.NotificationSetting.commentMention
173     }
174
175     async function notificationCreator (user: UserModel) {
176       const notification = await UserNotificationModel.create({
177         type: UserNotificationType.COMMENT_MENTION,
178         userId: user.id,
179         commentId: comment.id
180       })
181       notification.Comment = comment
182
183       return notification
184     }
185
186     function emailSender (emails: string[]) {
187       return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
188     }
189
190     return this.notify({ users, settingGetter, notificationCreator, emailSender })
191   }
192
193   private async notifyUserOfNewActorFollow (actorFollow: ActorFollowModel) {
194     if (actorFollow.ActorFollowing.isOwned() === false) return
195
196     // Account follows one of our account?
197     let followType: 'account' | 'channel' = 'channel'
198     let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
199
200     // Account follows one of our channel?
201     if (!user) {
202       user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
203       followType = 'account'
204     }
205
206     if (!user) return
207
208     if (!actorFollow.ActorFollower.Account || !actorFollow.ActorFollower.Account.name) {
209       actorFollow.ActorFollower.Account = await actorFollow.ActorFollower.$get('Account') as AccountModel
210     }
211     const followerAccount = actorFollow.ActorFollower.Account
212
213     const accountMuted = await AccountBlocklistModel.isAccountMutedBy(user.Account.id, followerAccount.id)
214     if (accountMuted) return
215
216     logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
217
218     function settingGetter (user: UserModel) {
219       return user.NotificationSetting.newFollow
220     }
221
222     async function notificationCreator (user: UserModel) {
223       const notification = await UserNotificationModel.create({
224         type: UserNotificationType.NEW_FOLLOW,
225         userId: user.id,
226         actorFollowId: actorFollow.id
227       })
228       notification.ActorFollow = actorFollow
229
230       return notification
231     }
232
233     function emailSender (emails: string[]) {
234       return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
235     }
236
237     return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
238   }
239
240   private async notifyModeratorsOfNewVideoAbuse (videoAbuse: VideoAbuseModel) {
241     const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_ABUSES)
242     if (moderators.length === 0) return
243
244     logger.info('Notifying %s user/moderators of new video abuse %s.', moderators.length, videoAbuse.Video.url)
245
246     function settingGetter (user: UserModel) {
247       return user.NotificationSetting.videoAbuseAsModerator
248     }
249
250     async function notificationCreator (user: UserModel) {
251       const notification = await UserNotificationModel.create({
252         type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
253         userId: user.id,
254         videoAbuseId: videoAbuse.id
255       })
256       notification.VideoAbuse = videoAbuse
257
258       return notification
259     }
260
261     function emailSender (emails: string[]) {
262       return Emailer.Instance.addVideoAbuseModeratorsNotification(emails, videoAbuse)
263     }
264
265     return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
266   }
267
268   private async notifyVideoOwnerOfBlacklist (videoBlacklist: VideoBlacklistModel) {
269     const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
270     if (!user) return
271
272     logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
273
274     function settingGetter (user: UserModel) {
275       return user.NotificationSetting.blacklistOnMyVideo
276     }
277
278     async function notificationCreator (user: UserModel) {
279       const notification = await UserNotificationModel.create({
280         type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
281         userId: user.id,
282         videoBlacklistId: videoBlacklist.id
283       })
284       notification.VideoBlacklist = videoBlacklist
285
286       return notification
287     }
288
289     function emailSender (emails: string[]) {
290       return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
291     }
292
293     return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
294   }
295
296   private async notifyVideoOwnerOfUnblacklist (video: VideoModel) {
297     const user = await UserModel.loadByVideoId(video.id)
298     if (!user) return
299
300     logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
301
302     function settingGetter (user: UserModel) {
303       return user.NotificationSetting.blacklistOnMyVideo
304     }
305
306     async function notificationCreator (user: UserModel) {
307       const notification = await UserNotificationModel.create({
308         type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
309         userId: user.id,
310         videoId: video.id
311       })
312       notification.Video = video
313
314       return notification
315     }
316
317     function emailSender (emails: string[]) {
318       return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
319     }
320
321     return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
322   }
323
324   private async notifyOwnedVideoHasBeenPublished (video: VideoModel) {
325     const user = await UserModel.loadByVideoId(video.id)
326     if (!user) return
327
328     logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
329
330     function settingGetter (user: UserModel) {
331       return user.NotificationSetting.myVideoPublished
332     }
333
334     async function notificationCreator (user: UserModel) {
335       const notification = await UserNotificationModel.create({
336         type: UserNotificationType.MY_VIDEO_PUBLISHED,
337         userId: user.id,
338         videoId: video.id
339       })
340       notification.Video = video
341
342       return notification
343     }
344
345     function emailSender (emails: string[]) {
346       return Emailer.Instance.myVideoPublishedNotification(emails, video)
347     }
348
349     return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
350   }
351
352   private async notifyOwnerVideoImportIsFinished (videoImport: VideoImportModel, success: boolean) {
353     const user = await UserModel.loadByVideoImportId(videoImport.id)
354     if (!user) return
355
356     logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
357
358     function settingGetter (user: UserModel) {
359       return user.NotificationSetting.myVideoImportFinished
360     }
361
362     async function notificationCreator (user: UserModel) {
363       const notification = await UserNotificationModel.create({
364         type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
365         userId: user.id,
366         videoImportId: videoImport.id
367       })
368       notification.VideoImport = videoImport
369
370       return notification
371     }
372
373     function emailSender (emails: string[]) {
374       return success
375         ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
376         : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
377     }
378
379     return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
380   }
381
382   private async notifyModeratorsOfNewUserRegistration (registeredUser: UserModel) {
383     const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
384     if (moderators.length === 0) return
385
386     logger.info(
387       'Notifying %s moderators of new user registration of %s.',
388       moderators.length, registeredUser.Account.Actor.preferredUsername
389     )
390
391     function settingGetter (user: UserModel) {
392       return user.NotificationSetting.newUserRegistration
393     }
394
395     async function notificationCreator (user: UserModel) {
396       const notification = await UserNotificationModel.create({
397         type: UserNotificationType.NEW_USER_REGISTRATION,
398         userId: user.id,
399         accountId: registeredUser.Account.id
400       })
401       notification.Account = registeredUser.Account
402
403       return notification
404     }
405
406     function emailSender (emails: string[]) {
407       return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
408     }
409
410     return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
411   }
412
413   private async notify (options: {
414     users: UserModel[],
415     notificationCreator: (user: UserModel) => Promise<UserNotificationModel>,
416     emailSender: (emails: string[]) => Promise<any> | Bluebird<any>,
417     settingGetter: (user: UserModel) => UserNotificationSettingValue
418   }) {
419     const emails: string[] = []
420
421     for (const user of options.users) {
422       if (this.isWebNotificationEnabled(options.settingGetter(user))) {
423         const notification = await options.notificationCreator(user)
424
425         PeerTubeSocket.Instance.sendNotification(user.id, notification)
426       }
427
428       if (this.isEmailEnabled(user, options.settingGetter(user))) {
429         emails.push(user.email)
430       }
431     }
432
433     if (emails.length !== 0) {
434       await options.emailSender(emails)
435     }
436   }
437
438   private isEmailEnabled (user: UserModel, value: UserNotificationSettingValue) {
439     if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified !== true) return false
440
441     return value & UserNotificationSettingValue.EMAIL
442   }
443
444   private isWebNotificationEnabled (value: UserNotificationSettingValue) {
445     return value & UserNotificationSettingValue.WEB
446   }
447
448   static get Instance () {
449     return this.instance || (this.instance = new this())
450   }
451 }
452
453 // ---------------------------------------------------------------------------
454
455 export {
456   Notifier
457 }