]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/notifier.ts
Add migrations
[github/Chocobozzz/PeerTube.git] / server / lib / notifier.ts
1 import { getServerActor } from '@server/models/application/application'
2 import { ServerBlocklistModel } from '@server/models/server/server-blocklist'
3 import {
4 MUser,
5 MUserAccount,
6 MUserDefault,
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'
26
27 class Notifier {
28
29 private static instance: Notifier
30
31 private constructor () {
32 }
33
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
37
38 this.notifySubscribersOfNewVideo(video)
39 .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
40 }
41
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
45
46 this.notifyOwnedVideoHasBeenPublished(video)
47 .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
48 }
49
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
53
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 }))
56 }
57
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
61
62 this.notifyOwnedVideoHasBeenPublished(video)
63 .catch(err => {
64 logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })
65 })
66 }
67
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 }))
71
72 this.notifyOfCommentMention(comment)
73 .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
74 }
75
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 }))
79 }
80
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 }))
84 }
85
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 }))
89 }
90
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 }))
94 }
95
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 }))
99 }
100
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 }))
104 }
105
106 notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
107 this.notifyUserOfNewActorFollow(actorFollow)
108 .catch(err => {
109 logger.error(
110 'Cannot notify owner of channel %s of a new follow by %s.',
111 actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
112 actorFollow.ActorFollower.Account.getDisplayName(),
113 { err }
114 )
115 })
116 }
117
118 notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
119 this.notifyAdminsOfNewInstanceFollow(actorFollow)
120 .catch(err => {
121 logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
122 })
123 }
124
125 notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
126 this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
127 .catch(err => {
128 logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
129 })
130 }
131
132 private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
133 // List all followers that are users
134 const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
135
136 logger.info('Notifying %d users of new video %s.', users.length, video.url)
137
138 function settingGetter (user: MUserWithNotificationSetting) {
139 return user.NotificationSetting.newVideoFromSubscription
140 }
141
142 async function notificationCreator (user: MUserWithNotificationSetting) {
143 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
144 type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
145 userId: user.id,
146 videoId: video.id
147 })
148 notification.Video = video
149
150 return notification
151 }
152
153 function emailSender (emails: string[]) {
154 return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
155 }
156
157 return this.notify({ users, settingGetter, notificationCreator, emailSender })
158 }
159
160 private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
161 if (comment.Video.isOwned() === false) return
162
163 const user = await UserModel.loadByVideoId(comment.videoId)
164
165 // Not our user or user comments its own video
166 if (!user || comment.Account.userId === user.id) return
167
168 if (await this.isBlockedByServerOrUser(comment.Account, user)) return
169
170 logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
171
172 function settingGetter (user: MUserWithNotificationSetting) {
173 return user.NotificationSetting.newCommentOnMyVideo
174 }
175
176 async function notificationCreator (user: MUserWithNotificationSetting) {
177 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
178 type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
179 userId: user.id,
180 commentId: comment.id
181 })
182 notification.Comment = comment
183
184 return notification
185 }
186
187 function emailSender (emails: string[]) {
188 return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
189 }
190
191 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
192 }
193
194 private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
195 const extractedUsernames = comment.extractMentions()
196 logger.debug(
197 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
198 { usernames: extractedUsernames, text: comment.text }
199 )
200
201 let users = await UserModel.listByUsernames(extractedUsernames)
202
203 if (comment.Video.isOwned()) {
204 const userException = await UserModel.loadByVideoId(comment.videoId)
205 users = users.filter(u => u.id !== userException.id)
206 }
207
208 // Don't notify if I mentioned myself
209 users = users.filter(u => u.Account.id !== comment.accountId)
210
211 if (users.length === 0) return
212
213 const serverAccountId = (await getServerActor()).Account.id
214 const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])
215
216 const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
217 const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)
218
219 logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
220
221 function settingGetter (user: MUserNotifSettingAccount) {
222 const accountId = user.Account.id
223 if (
224 accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
225 accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
226 ) {
227 return UserNotificationSettingValue.NONE
228 }
229
230 return user.NotificationSetting.commentMention
231 }
232
233 async function notificationCreator (user: MUserNotifSettingAccount) {
234 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
235 type: UserNotificationType.COMMENT_MENTION,
236 userId: user.id,
237 commentId: comment.id
238 })
239 notification.Comment = comment
240
241 return notification
242 }
243
244 function emailSender (emails: string[]) {
245 return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
246 }
247
248 return this.notify({ users, settingGetter, notificationCreator, emailSender })
249 }
250
251 private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
252 if (actorFollow.ActorFollowing.isOwned() === false) return
253
254 // Account follows one of our account?
255 let followType: 'account' | 'channel' = 'channel'
256 let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
257
258 // Account follows one of our channel?
259 if (!user) {
260 user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
261 followType = 'account'
262 }
263
264 if (!user) return
265
266 const followerAccount = actorFollow.ActorFollower.Account
267 const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })
268
269 if (await this.isBlockedByServerOrUser(followerAccountWithActor, user)) return
270
271 logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
272
273 function settingGetter (user: MUserWithNotificationSetting) {
274 return user.NotificationSetting.newFollow
275 }
276
277 async function notificationCreator (user: MUserWithNotificationSetting) {
278 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
279 type: UserNotificationType.NEW_FOLLOW,
280 userId: user.id,
281 actorFollowId: actorFollow.id
282 })
283 notification.ActorFollow = actorFollow
284
285 return notification
286 }
287
288 function emailSender (emails: string[]) {
289 return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
290 }
291
292 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
293 }
294
295 private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
296 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
297
298 const follower = Object.assign(actorFollow.ActorFollower.Account, { Actor: actorFollow.ActorFollower })
299 if (await this.isBlockedByServerOrUser(follower)) return
300
301 logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
302
303 function settingGetter (user: MUserWithNotificationSetting) {
304 return user.NotificationSetting.newInstanceFollower
305 }
306
307 async function notificationCreator (user: MUserWithNotificationSetting) {
308 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
309 type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
310 userId: user.id,
311 actorFollowId: actorFollow.id
312 })
313 notification.ActorFollow = actorFollow
314
315 return notification
316 }
317
318 function emailSender (emails: string[]) {
319 return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
320 }
321
322 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
323 }
324
325 private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
326 const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
327
328 logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)
329
330 function settingGetter (user: MUserWithNotificationSetting) {
331 return user.NotificationSetting.autoInstanceFollowing
332 }
333
334 async function notificationCreator (user: MUserWithNotificationSetting) {
335 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
336 type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
337 userId: user.id,
338 actorFollowId: actorFollow.id
339 })
340 notification.ActorFollow = actorFollow
341
342 return notification
343 }
344
345 function emailSender (emails: string[]) {
346 return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
347 }
348
349 return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
350 }
351
352 private async notifyModeratorsOfNewAbuse (parameters: {
353 abuse: Abuse
354 abuseInstance: MAbuseFull
355 reporter: string
356 }) {
357 const { abuse, abuseInstance } = parameters
358
359 const moderators = await UserModel.listWithRight(UserRight.MANAGE_ABUSES)
360 if (moderators.length === 0) return
361
362 const url = abuseInstance.VideoAbuse?.Video?.url ||
363 abuseInstance.VideoCommentAbuse?.VideoComment?.url ||
364 abuseInstance.FlaggedAccount.Actor.url
365
366 logger.info('Notifying %s user/moderators of new abuse %s.', moderators.length, url)
367
368 function settingGetter (user: MUserWithNotificationSetting) {
369 return user.NotificationSetting.abuseAsModerator
370 }
371
372 async function notificationCreator (user: MUserWithNotificationSetting) {
373 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
374 type: UserNotificationType.NEW_VIDEO_ABUSE_FOR_MODERATORS,
375 userId: user.id,
376 abuseId: abuse.id
377 })
378 notification.Abuse = abuseInstance
379
380 return notification
381 }
382
383 function emailSender (emails: string[]) {
384 return Emailer.Instance.addAbuseModeratorsNotification(emails, parameters)
385 }
386
387 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
388 }
389
390 private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
391 const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
392 if (moderators.length === 0) return
393
394 logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)
395
396 function settingGetter (user: MUserWithNotificationSetting) {
397 return user.NotificationSetting.videoAutoBlacklistAsModerator
398 }
399
400 async function notificationCreator (user: MUserWithNotificationSetting) {
401 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
402 type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
403 userId: user.id,
404 videoBlacklistId: videoBlacklist.id
405 })
406 notification.VideoBlacklist = videoBlacklist
407
408 return notification
409 }
410
411 function emailSender (emails: string[]) {
412 return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
413 }
414
415 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
416 }
417
418 private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
419 const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
420 if (!user) return
421
422 logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
423
424 function settingGetter (user: MUserWithNotificationSetting) {
425 return user.NotificationSetting.blacklistOnMyVideo
426 }
427
428 async function notificationCreator (user: MUserWithNotificationSetting) {
429 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
430 type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
431 userId: user.id,
432 videoBlacklistId: videoBlacklist.id
433 })
434 notification.VideoBlacklist = videoBlacklist
435
436 return notification
437 }
438
439 function emailSender (emails: string[]) {
440 return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
441 }
442
443 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
444 }
445
446 private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
447 const user = await UserModel.loadByVideoId(video.id)
448 if (!user) return
449
450 logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
451
452 function settingGetter (user: MUserWithNotificationSetting) {
453 return user.NotificationSetting.blacklistOnMyVideo
454 }
455
456 async function notificationCreator (user: MUserWithNotificationSetting) {
457 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
458 type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
459 userId: user.id,
460 videoId: video.id
461 })
462 notification.Video = video
463
464 return notification
465 }
466
467 function emailSender (emails: string[]) {
468 return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
469 }
470
471 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
472 }
473
474 private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
475 const user = await UserModel.loadByVideoId(video.id)
476 if (!user) return
477
478 logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
479
480 function settingGetter (user: MUserWithNotificationSetting) {
481 return user.NotificationSetting.myVideoPublished
482 }
483
484 async function notificationCreator (user: MUserWithNotificationSetting) {
485 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
486 type: UserNotificationType.MY_VIDEO_PUBLISHED,
487 userId: user.id,
488 videoId: video.id
489 })
490 notification.Video = video
491
492 return notification
493 }
494
495 function emailSender (emails: string[]) {
496 return Emailer.Instance.myVideoPublishedNotification(emails, video)
497 }
498
499 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
500 }
501
502 private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
503 const user = await UserModel.loadByVideoImportId(videoImport.id)
504 if (!user) return
505
506 logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
507
508 function settingGetter (user: MUserWithNotificationSetting) {
509 return user.NotificationSetting.myVideoImportFinished
510 }
511
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,
515 userId: user.id,
516 videoImportId: videoImport.id
517 })
518 notification.VideoImport = videoImport
519
520 return notification
521 }
522
523 function emailSender (emails: string[]) {
524 return success
525 ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
526 : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
527 }
528
529 return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
530 }
531
532 private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
533 const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
534 if (moderators.length === 0) return
535
536 logger.info(
537 'Notifying %s moderators of new user registration of %s.',
538 moderators.length, registeredUser.username
539 )
540
541 function settingGetter (user: MUserWithNotificationSetting) {
542 return user.NotificationSetting.newUserRegistration
543 }
544
545 async function notificationCreator (user: MUserWithNotificationSetting) {
546 const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
547 type: UserNotificationType.NEW_USER_REGISTRATION,
548 userId: user.id,
549 accountId: registeredUser.Account.id
550 })
551 notification.Account = registeredUser.Account
552
553 return notification
554 }
555
556 function emailSender (emails: string[]) {
557 return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
558 }
559
560 return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
561 }
562
563 private async notify<T extends MUserWithNotificationSetting> (options: {
564 users: T[]
565 notificationCreator: (user: T) => Promise<UserNotificationModelForApi>
566 emailSender: (emails: string[]) => void
567 settingGetter: (user: T) => UserNotificationSettingValue
568 }) {
569 const emails: string[] = []
570
571 for (const user of options.users) {
572 if (this.isWebNotificationEnabled(options.settingGetter(user))) {
573 const notification = await options.notificationCreator(user)
574
575 PeerTubeSocket.Instance.sendNotification(user.id, notification)
576 }
577
578 if (this.isEmailEnabled(user, options.settingGetter(user))) {
579 emails.push(user.email)
580 }
581 }
582
583 if (emails.length !== 0) {
584 options.emailSender(emails)
585 }
586 }
587
588 private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
589 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
590
591 return value & UserNotificationSettingValue.EMAIL
592 }
593
594 private isWebNotificationEnabled (value: UserNotificationSettingValue) {
595 return value & UserNotificationSettingValue.WEB
596 }
597
598 private isBlockedByServerOrUser (targetAccount: MAccountServer, user?: MUserAccount) {
599 return isBlockedByServerOrAccount(targetAccount, user?.Account)
600 }
601
602 static get Instance () {
603 return this.instance || (this.instance = new this())
604 }
605 }
606
607 // ---------------------------------------------------------------------------
608
609 export {
610 Notifier
611 }