notifier.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import { AccountModel } from '@server/models/account/account'
  2. import { getServerActor } from '@server/models/application/application'
  3. import { ServerBlocklistModel } from '@server/models/server/server-blocklist'
  4. import {
  5. MUser,
  6. MUserAccount,
  7. MUserDefault,
  8. MUserNotifSettingAccount,
  9. MUserWithNotificationSetting,
  10. UserNotificationModelForApi
  11. } from '@server/types/models/user'
  12. import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
  13. import { MVideoImportVideo } from '@server/types/models/video/video-import'
  14. import { UserAbuse } from '@shared/models'
  15. import { UserNotificationSettingValue, UserNotificationType, UserRight } from '../../shared/models/users'
  16. import { VideoPrivacy, VideoState } from '../../shared/models/videos'
  17. import { logger } from '../helpers/logger'
  18. import { CONFIG } from '../initializers/config'
  19. import { AccountBlocklistModel } from '../models/account/account-blocklist'
  20. import { UserModel } from '../models/account/user'
  21. import { UserNotificationModel } from '../models/account/user-notification'
  22. import { MAbuseFull, MAbuseMessage, MAccountServer, MActorFollowFull } from '../types/models'
  23. import { MCommentOwnerVideo, MVideoAccountLight, MVideoFullLight } from '../types/models/video'
  24. import { isBlockedByServerOrAccount } from './blocklist'
  25. import { Emailer } from './emailer'
  26. import { PeerTubeSocket } from './peertube-socket'
  27. class Notifier {
  28. private static instance: Notifier
  29. private constructor () {
  30. }
  31. notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void {
  32. // Only notify on public and published videos which are not blacklisted
  33. if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return
  34. this.notifySubscribersOfNewVideo(video)
  35. .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err }))
  36. }
  37. notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void {
  38. // don't notify if didn't wait for transcoding or video is still blacklisted/waiting for scheduled update
  39. if (!video.waitTranscoding || video.VideoBlacklist || video.ScheduleVideoUpdate) return
  40. this.notifyOwnedVideoHasBeenPublished(video)
  41. .catch(err => logger.error('Cannot notify owner that its video %s has been published after transcoding.', video.url, { err }))
  42. }
  43. notifyOnVideoPublishedAfterScheduledUpdate (video: MVideoFullLight): void {
  44. // don't notify if video is still blacklisted or waiting for transcoding
  45. if (video.VideoBlacklist || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
  46. this.notifyOwnedVideoHasBeenPublished(video)
  47. .catch(err => logger.error('Cannot notify owner that its video %s has been published after scheduled update.', video.url, { err }))
  48. }
  49. notifyOnVideoPublishedAfterRemovedFromAutoBlacklist (video: MVideoFullLight): void {
  50. // don't notify if video is still waiting for transcoding or scheduled update
  51. if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return
  52. this.notifyOwnedVideoHasBeenPublished(video)
  53. .catch(err => {
  54. logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })
  55. })
  56. }
  57. notifyOnNewComment (comment: MCommentOwnerVideo): void {
  58. this.notifyVideoOwnerOfNewComment(comment)
  59. .catch(err => logger.error('Cannot notify video owner of new comment %s.', comment.url, { err }))
  60. this.notifyOfCommentMention(comment)
  61. .catch(err => logger.error('Cannot notify mentions of comment %s.', comment.url, { err }))
  62. }
  63. notifyOnNewAbuse (parameters: { abuse: UserAbuse, abuseInstance: MAbuseFull, reporter: string }): void {
  64. this.notifyModeratorsOfNewAbuse(parameters)
  65. .catch(err => logger.error('Cannot notify of new abuse %d.', parameters.abuseInstance.id, { err }))
  66. }
  67. notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void {
  68. this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist)
  69. .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err }))
  70. }
  71. notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void {
  72. this.notifyVideoOwnerOfBlacklist(videoBlacklist)
  73. .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err }))
  74. }
  75. notifyOnVideoUnblacklist (video: MVideoFullLight): void {
  76. this.notifyVideoOwnerOfUnblacklist(video)
  77. .catch(err => logger.error('Cannot notify video owner of unblacklist of %s.', video.url, { err }))
  78. }
  79. notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void {
  80. this.notifyOwnerVideoImportIsFinished(videoImport, success)
  81. .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err }))
  82. }
  83. notifyOnNewUserRegistration (user: MUserDefault): void {
  84. this.notifyModeratorsOfNewUserRegistration(user)
  85. .catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
  86. }
  87. notifyOfNewUserFollow (actorFollow: MActorFollowFull): void {
  88. this.notifyUserOfNewActorFollow(actorFollow)
  89. .catch(err => {
  90. logger.error(
  91. 'Cannot notify owner of channel %s of a new follow by %s.',
  92. actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
  93. actorFollow.ActorFollower.Account.getDisplayName(),
  94. { err }
  95. )
  96. })
  97. }
  98. notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void {
  99. this.notifyAdminsOfNewInstanceFollow(actorFollow)
  100. .catch(err => {
  101. logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
  102. })
  103. }
  104. notifyOfAutoInstanceFollowing (actorFollow: MActorFollowFull): void {
  105. this.notifyAdminsOfAutoInstanceFollowing(actorFollow)
  106. .catch(err => {
  107. logger.error('Cannot notify administrators of auto instance following %s.', actorFollow.ActorFollowing.url, { err })
  108. })
  109. }
  110. notifyOnAbuseStateChange (abuse: MAbuseFull): void {
  111. this.notifyReporterOfAbuseStateChange(abuse)
  112. .catch(err => {
  113. logger.error('Cannot notify reporter of abuse %d state change.', abuse.id, { err })
  114. })
  115. }
  116. notifyOnAbuseMessage (abuse: MAbuseFull, message: MAbuseMessage): void {
  117. this.notifyOfNewAbuseMessage(abuse, message)
  118. .catch(err => {
  119. logger.error('Cannot notify on new abuse %d message.', abuse.id, { err })
  120. })
  121. }
  122. private async notifySubscribersOfNewVideo (video: MVideoAccountLight) {
  123. // List all followers that are users
  124. const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
  125. logger.info('Notifying %d users of new video %s.', users.length, video.url)
  126. function settingGetter (user: MUserWithNotificationSetting) {
  127. return user.NotificationSetting.newVideoFromSubscription
  128. }
  129. async function notificationCreator (user: MUserWithNotificationSetting) {
  130. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  131. type: UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION,
  132. userId: user.id,
  133. videoId: video.id
  134. })
  135. notification.Video = video
  136. return notification
  137. }
  138. function emailSender (emails: string[]) {
  139. return Emailer.Instance.addNewVideoFromSubscriberNotification(emails, video)
  140. }
  141. return this.notify({ users, settingGetter, notificationCreator, emailSender })
  142. }
  143. private async notifyVideoOwnerOfNewComment (comment: MCommentOwnerVideo) {
  144. if (comment.Video.isOwned() === false) return
  145. const user = await UserModel.loadByVideoId(comment.videoId)
  146. // Not our user or user comments its own video
  147. if (!user || comment.Account.userId === user.id) return
  148. if (await this.isBlockedByServerOrUser(comment.Account, user)) return
  149. logger.info('Notifying user %s of new comment %s.', user.username, comment.url)
  150. function settingGetter (user: MUserWithNotificationSetting) {
  151. return user.NotificationSetting.newCommentOnMyVideo
  152. }
  153. async function notificationCreator (user: MUserWithNotificationSetting) {
  154. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  155. type: UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,
  156. userId: user.id,
  157. commentId: comment.id
  158. })
  159. notification.Comment = comment
  160. return notification
  161. }
  162. function emailSender (emails: string[]) {
  163. return Emailer.Instance.addNewCommentOnMyVideoNotification(emails, comment)
  164. }
  165. return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  166. }
  167. private async notifyOfCommentMention (comment: MCommentOwnerVideo) {
  168. const extractedUsernames = comment.extractMentions()
  169. logger.debug(
  170. 'Extracted %d username from comment %s.', extractedUsernames.length, comment.url,
  171. { usernames: extractedUsernames, text: comment.text }
  172. )
  173. let users = await UserModel.listByUsernames(extractedUsernames)
  174. if (comment.Video.isOwned()) {
  175. const userException = await UserModel.loadByVideoId(comment.videoId)
  176. users = users.filter(u => u.id !== userException.id)
  177. }
  178. // Don't notify if I mentioned myself
  179. users = users.filter(u => u.Account.id !== comment.accountId)
  180. if (users.length === 0) return
  181. const serverAccountId = (await getServerActor()).Account.id
  182. const sourceAccounts = users.map(u => u.Account.id).concat([ serverAccountId ])
  183. const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, comment.accountId)
  184. const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, comment.Account.Actor.serverId)
  185. logger.info('Notifying %d users of new comment %s.', users.length, comment.url)
  186. function settingGetter (user: MUserNotifSettingAccount) {
  187. const accountId = user.Account.id
  188. if (
  189. accountMutedHash[accountId] === true || instanceMutedHash[accountId] === true ||
  190. accountMutedHash[serverAccountId] === true || instanceMutedHash[serverAccountId] === true
  191. ) {
  192. return UserNotificationSettingValue.NONE
  193. }
  194. return user.NotificationSetting.commentMention
  195. }
  196. async function notificationCreator (user: MUserNotifSettingAccount) {
  197. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  198. type: UserNotificationType.COMMENT_MENTION,
  199. userId: user.id,
  200. commentId: comment.id
  201. })
  202. notification.Comment = comment
  203. return notification
  204. }
  205. function emailSender (emails: string[]) {
  206. return Emailer.Instance.addNewCommentMentionNotification(emails, comment)
  207. }
  208. return this.notify({ users, settingGetter, notificationCreator, emailSender })
  209. }
  210. private async notifyUserOfNewActorFollow (actorFollow: MActorFollowFull) {
  211. if (actorFollow.ActorFollowing.isOwned() === false) return
  212. // Account follows one of our account?
  213. let followType: 'account' | 'channel' = 'channel'
  214. let user = await UserModel.loadByChannelActorId(actorFollow.ActorFollowing.id)
  215. // Account follows one of our channel?
  216. if (!user) {
  217. user = await UserModel.loadByAccountActorId(actorFollow.ActorFollowing.id)
  218. followType = 'account'
  219. }
  220. if (!user) return
  221. const followerAccount = actorFollow.ActorFollower.Account
  222. const followerAccountWithActor = Object.assign(followerAccount, { Actor: actorFollow.ActorFollower })
  223. if (await this.isBlockedByServerOrUser(followerAccountWithActor, user)) return
  224. logger.info('Notifying user %s of new follower: %s.', user.username, followerAccount.getDisplayName())
  225. function settingGetter (user: MUserWithNotificationSetting) {
  226. return user.NotificationSetting.newFollow
  227. }
  228. async function notificationCreator (user: MUserWithNotificationSetting) {
  229. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  230. type: UserNotificationType.NEW_FOLLOW,
  231. userId: user.id,
  232. actorFollowId: actorFollow.id
  233. })
  234. notification.ActorFollow = actorFollow
  235. return notification
  236. }
  237. function emailSender (emails: string[]) {
  238. return Emailer.Instance.addNewFollowNotification(emails, actorFollow, followType)
  239. }
  240. return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  241. }
  242. private async notifyAdminsOfNewInstanceFollow (actorFollow: MActorFollowFull) {
  243. const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
  244. const follower = Object.assign(actorFollow.ActorFollower.Account, { Actor: actorFollow.ActorFollower })
  245. if (await this.isBlockedByServerOrUser(follower)) return
  246. logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
  247. function settingGetter (user: MUserWithNotificationSetting) {
  248. return user.NotificationSetting.newInstanceFollower
  249. }
  250. async function notificationCreator (user: MUserWithNotificationSetting) {
  251. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  252. type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
  253. userId: user.id,
  254. actorFollowId: actorFollow.id
  255. })
  256. notification.ActorFollow = actorFollow
  257. return notification
  258. }
  259. function emailSender (emails: string[]) {
  260. return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
  261. }
  262. return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
  263. }
  264. private async notifyAdminsOfAutoInstanceFollowing (actorFollow: MActorFollowFull) {
  265. const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
  266. logger.info('Notifying %d administrators of auto instance following: %s.', admins.length, actorFollow.ActorFollowing.url)
  267. function settingGetter (user: MUserWithNotificationSetting) {
  268. return user.NotificationSetting.autoInstanceFollowing
  269. }
  270. async function notificationCreator (user: MUserWithNotificationSetting) {
  271. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  272. type: UserNotificationType.AUTO_INSTANCE_FOLLOWING,
  273. userId: user.id,
  274. actorFollowId: actorFollow.id
  275. })
  276. notification.ActorFollow = actorFollow
  277. return notification
  278. }
  279. function emailSender (emails: string[]) {
  280. return Emailer.Instance.addAutoInstanceFollowingNotification(emails, actorFollow)
  281. }
  282. return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
  283. }
  284. private async notifyModeratorsOfNewAbuse (parameters: {
  285. abuse: UserAbuse
  286. abuseInstance: MAbuseFull
  287. reporter: string
  288. }) {
  289. const { abuse, abuseInstance } = parameters
  290. const moderators = await UserModel.listWithRight(UserRight.MANAGE_ABUSES)
  291. if (moderators.length === 0) return
  292. const url = this.getAbuseUrl(abuseInstance)
  293. logger.info('Notifying %s user/moderators of new abuse %s.', moderators.length, url)
  294. function settingGetter (user: MUserWithNotificationSetting) {
  295. return user.NotificationSetting.abuseAsModerator
  296. }
  297. async function notificationCreator (user: MUserWithNotificationSetting) {
  298. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  299. type: UserNotificationType.NEW_ABUSE_FOR_MODERATORS,
  300. userId: user.id,
  301. abuseId: abuse.id
  302. })
  303. notification.Abuse = abuseInstance
  304. return notification
  305. }
  306. function emailSender (emails: string[]) {
  307. return Emailer.Instance.addAbuseModeratorsNotification(emails, parameters)
  308. }
  309. return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
  310. }
  311. private async notifyReporterOfAbuseStateChange (abuse: MAbuseFull) {
  312. // Only notify our users
  313. if (abuse.ReporterAccount.isOwned() !== true) return
  314. const url = this.getAbuseUrl(abuse)
  315. logger.info('Notifying reporter of abuse % of state change.', url)
  316. const reporter = await UserModel.loadByAccountActorId(abuse.ReporterAccount.actorId)
  317. function settingGetter (user: MUserWithNotificationSetting) {
  318. return user.NotificationSetting.abuseStateChange
  319. }
  320. async function notificationCreator (user: MUserWithNotificationSetting) {
  321. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  322. type: UserNotificationType.ABUSE_STATE_CHANGE,
  323. userId: user.id,
  324. abuseId: abuse.id
  325. })
  326. notification.Abuse = abuse
  327. return notification
  328. }
  329. function emailSender (emails: string[]) {
  330. return Emailer.Instance.addAbuseStateChangeNotification(emails, abuse)
  331. }
  332. return this.notify({ users: [ reporter ], settingGetter, notificationCreator, emailSender })
  333. }
  334. private async notifyOfNewAbuseMessage (abuse: MAbuseFull, message: MAbuseMessage) {
  335. const url = this.getAbuseUrl(abuse)
  336. logger.info('Notifying reporter and moderators of new abuse message on %s.', url)
  337. const accountMessage = await AccountModel.load(message.accountId)
  338. function settingGetter (user: MUserWithNotificationSetting) {
  339. return user.NotificationSetting.abuseNewMessage
  340. }
  341. async function notificationCreator (user: MUserWithNotificationSetting) {
  342. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  343. type: UserNotificationType.ABUSE_NEW_MESSAGE,
  344. userId: user.id,
  345. abuseId: abuse.id
  346. })
  347. notification.Abuse = abuse
  348. return notification
  349. }
  350. function emailSenderReporter (emails: string[]) {
  351. return Emailer.Instance.addAbuseNewMessageNotification(emails, { target: 'reporter', abuse, message, accountMessage })
  352. }
  353. function emailSenderModerators (emails: string[]) {
  354. return Emailer.Instance.addAbuseNewMessageNotification(emails, { target: 'moderator', abuse, message, accountMessage })
  355. }
  356. async function buildReporterOptions () {
  357. // Only notify our users
  358. if (abuse.ReporterAccount.isOwned() !== true) return undefined
  359. const reporter = await UserModel.loadByAccountActorId(abuse.ReporterAccount.actorId)
  360. // Don't notify my own message
  361. if (reporter.Account.id === message.accountId) return undefined
  362. return { users: [ reporter ], settingGetter, notificationCreator, emailSender: emailSenderReporter }
  363. }
  364. async function buildModeratorsOptions () {
  365. let moderators = await UserModel.listWithRight(UserRight.MANAGE_ABUSES)
  366. // Don't notify my own message
  367. moderators = moderators.filter(m => m.Account.id !== message.accountId)
  368. if (moderators.length === 0) return undefined
  369. return { users: moderators, settingGetter, notificationCreator, emailSender: emailSenderModerators }
  370. }
  371. const options = await Promise.all([
  372. buildReporterOptions(),
  373. buildModeratorsOptions()
  374. ])
  375. return Promise.all(
  376. options
  377. .filter(opt => !!opt)
  378. .map(opt => this.notify(opt))
  379. )
  380. }
  381. private async notifyModeratorsOfVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo) {
  382. const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_BLACKLIST)
  383. if (moderators.length === 0) return
  384. logger.info('Notifying %s moderators of video auto-blacklist %s.', moderators.length, videoBlacklist.Video.url)
  385. function settingGetter (user: MUserWithNotificationSetting) {
  386. return user.NotificationSetting.videoAutoBlacklistAsModerator
  387. }
  388. async function notificationCreator (user: MUserWithNotificationSetting) {
  389. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  390. type: UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS,
  391. userId: user.id,
  392. videoBlacklistId: videoBlacklist.id
  393. })
  394. notification.VideoBlacklist = videoBlacklist
  395. return notification
  396. }
  397. function emailSender (emails: string[]) {
  398. return Emailer.Instance.addVideoAutoBlacklistModeratorsNotification(emails, videoBlacklist)
  399. }
  400. return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
  401. }
  402. private async notifyVideoOwnerOfBlacklist (videoBlacklist: MVideoBlacklistVideo) {
  403. const user = await UserModel.loadByVideoId(videoBlacklist.videoId)
  404. if (!user) return
  405. logger.info('Notifying user %s that its video %s has been blacklisted.', user.username, videoBlacklist.Video.url)
  406. function settingGetter (user: MUserWithNotificationSetting) {
  407. return user.NotificationSetting.blacklistOnMyVideo
  408. }
  409. async function notificationCreator (user: MUserWithNotificationSetting) {
  410. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  411. type: UserNotificationType.BLACKLIST_ON_MY_VIDEO,
  412. userId: user.id,
  413. videoBlacklistId: videoBlacklist.id
  414. })
  415. notification.VideoBlacklist = videoBlacklist
  416. return notification
  417. }
  418. function emailSender (emails: string[]) {
  419. return Emailer.Instance.addVideoBlacklistNotification(emails, videoBlacklist)
  420. }
  421. return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  422. }
  423. private async notifyVideoOwnerOfUnblacklist (video: MVideoFullLight) {
  424. const user = await UserModel.loadByVideoId(video.id)
  425. if (!user) return
  426. logger.info('Notifying user %s that its video %s has been unblacklisted.', user.username, video.url)
  427. function settingGetter (user: MUserWithNotificationSetting) {
  428. return user.NotificationSetting.blacklistOnMyVideo
  429. }
  430. async function notificationCreator (user: MUserWithNotificationSetting) {
  431. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  432. type: UserNotificationType.UNBLACKLIST_ON_MY_VIDEO,
  433. userId: user.id,
  434. videoId: video.id
  435. })
  436. notification.Video = video
  437. return notification
  438. }
  439. function emailSender (emails: string[]) {
  440. return Emailer.Instance.addVideoUnblacklistNotification(emails, video)
  441. }
  442. return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  443. }
  444. private async notifyOwnedVideoHasBeenPublished (video: MVideoFullLight) {
  445. const user = await UserModel.loadByVideoId(video.id)
  446. if (!user) return
  447. logger.info('Notifying user %s of the publication of its video %s.', user.username, video.url)
  448. function settingGetter (user: MUserWithNotificationSetting) {
  449. return user.NotificationSetting.myVideoPublished
  450. }
  451. async function notificationCreator (user: MUserWithNotificationSetting) {
  452. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  453. type: UserNotificationType.MY_VIDEO_PUBLISHED,
  454. userId: user.id,
  455. videoId: video.id
  456. })
  457. notification.Video = video
  458. return notification
  459. }
  460. function emailSender (emails: string[]) {
  461. return Emailer.Instance.myVideoPublishedNotification(emails, video)
  462. }
  463. return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  464. }
  465. private async notifyOwnerVideoImportIsFinished (videoImport: MVideoImportVideo, success: boolean) {
  466. const user = await UserModel.loadByVideoImportId(videoImport.id)
  467. if (!user) return
  468. logger.info('Notifying user %s its video import %s is finished.', user.username, videoImport.getTargetIdentifier())
  469. function settingGetter (user: MUserWithNotificationSetting) {
  470. return user.NotificationSetting.myVideoImportFinished
  471. }
  472. async function notificationCreator (user: MUserWithNotificationSetting) {
  473. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  474. type: success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR,
  475. userId: user.id,
  476. videoImportId: videoImport.id
  477. })
  478. notification.VideoImport = videoImport
  479. return notification
  480. }
  481. function emailSender (emails: string[]) {
  482. return success
  483. ? Emailer.Instance.myVideoImportSuccessNotification(emails, videoImport)
  484. : Emailer.Instance.myVideoImportErrorNotification(emails, videoImport)
  485. }
  486. return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
  487. }
  488. private async notifyModeratorsOfNewUserRegistration (registeredUser: MUserDefault) {
  489. const moderators = await UserModel.listWithRight(UserRight.MANAGE_USERS)
  490. if (moderators.length === 0) return
  491. logger.info(
  492. 'Notifying %s moderators of new user registration of %s.',
  493. moderators.length, registeredUser.username
  494. )
  495. function settingGetter (user: MUserWithNotificationSetting) {
  496. return user.NotificationSetting.newUserRegistration
  497. }
  498. async function notificationCreator (user: MUserWithNotificationSetting) {
  499. const notification = await UserNotificationModel.create<UserNotificationModelForApi>({
  500. type: UserNotificationType.NEW_USER_REGISTRATION,
  501. userId: user.id,
  502. accountId: registeredUser.Account.id
  503. })
  504. notification.Account = registeredUser.Account
  505. return notification
  506. }
  507. function emailSender (emails: string[]) {
  508. return Emailer.Instance.addNewUserRegistrationNotification(emails, registeredUser)
  509. }
  510. return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender })
  511. }
  512. private async notify<T extends MUserWithNotificationSetting> (options: {
  513. users: T[]
  514. notificationCreator: (user: T) => Promise<UserNotificationModelForApi>
  515. emailSender: (emails: string[]) => void
  516. settingGetter: (user: T) => UserNotificationSettingValue
  517. }) {
  518. const emails: string[] = []
  519. for (const user of options.users) {
  520. if (this.isWebNotificationEnabled(options.settingGetter(user))) {
  521. const notification = await options.notificationCreator(user)
  522. PeerTubeSocket.Instance.sendNotification(user.id, notification)
  523. }
  524. if (this.isEmailEnabled(user, options.settingGetter(user))) {
  525. emails.push(user.email)
  526. }
  527. }
  528. if (emails.length !== 0) {
  529. options.emailSender(emails)
  530. }
  531. }
  532. private isEmailEnabled (user: MUser, value: UserNotificationSettingValue) {
  533. if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION === true && user.emailVerified === false) return false
  534. return value & UserNotificationSettingValue.EMAIL
  535. }
  536. private isWebNotificationEnabled (value: UserNotificationSettingValue) {
  537. return value & UserNotificationSettingValue.WEB
  538. }
  539. private isBlockedByServerOrUser (targetAccount: MAccountServer, user?: MUserAccount) {
  540. return isBlockedByServerOrAccount(targetAccount, user?.Account)
  541. }
  542. private getAbuseUrl (abuse: MAbuseFull) {
  543. return abuse.VideoAbuse?.Video?.url ||
  544. abuse.VideoCommentAbuse?.VideoComment?.url ||
  545. abuse.FlaggedAccount.Actor.url
  546. }
  547. static get Instance () {
  548. return this.instance || (this.instance = new this())
  549. }
  550. }
  551. // ---------------------------------------------------------------------------
  552. export {
  553. Notifier
  554. }