pre-notify.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import type {
  2. IPage, IUser, Ref,
  3. } from '@growi/core';
  4. import { SupportedTargetModel } from '~/interfaces/activity';
  5. import type { ActivityDocument } from '../models/activity';
  6. import Subscription from '../models/subscription';
  7. import { getModelSafely } from '../util/mongoose-utils';
  8. export type PreNotifyProps = {
  9. notificationTargetUsers?: Ref<IUser>[],
  10. }
  11. export type PreNotify = (props: PreNotifyProps) => Promise<void>;
  12. export type GeneratePreNotify = (activity: ActivityDocument, getAdditionalTargetUsers?: (activity?: ActivityDocument) => Ref<IUser>[]) => PreNotify;
  13. export type GetAdditionalTargetUsers = (activity: ActivityDocument) => Ref<IUser>[];
  14. interface IPreNotifyService {
  15. generateInitialPreNotifyProps: (PreNotifyProps) => { notificationTargetUsers?: Ref<IUser>[] },
  16. generatePreNotify: GeneratePreNotify
  17. }
  18. class PreNotifyService implements IPreNotifyService {
  19. generateInitialPreNotifyProps = (): PreNotifyProps => {
  20. const initialPreNotifyProps: Ref<IUser>[] = [];
  21. return { notificationTargetUsers: initialPreNotifyProps };
  22. };
  23. generatePreNotify = (activity: ActivityDocument, getAdditionalTargetUsers?: GetAdditionalTargetUsers): PreNotify => {
  24. const preNotify = async(props: PreNotifyProps) => {
  25. const { notificationTargetUsers } = props;
  26. const User = getModelSafely('User') || require('~/server/models/user')();
  27. const actionUser = activity.user;
  28. const target = activity.target;
  29. const subscribedUsers = await Subscription.getSubscription(target as unknown as Ref<IPage>);
  30. // If target model is PageBulkExportJob, notify the user who started the job. Otherwise, exclude the activity user from the notification.
  31. const notificationUsers = activity.targetModel === SupportedTargetModel.MODEL_PAGE_BULK_EXPORT_JOB ? subscribedUsers
  32. : subscribedUsers.filter(item => (item.toString() !== actionUser._id.toString()));
  33. const activeNotificationUsers = await User.find({
  34. _id: { $in: notificationUsers },
  35. status: User.STATUS_ACTIVE,
  36. }).distinct('_id');
  37. if (getAdditionalTargetUsers == null) {
  38. notificationTargetUsers?.push(...activeNotificationUsers);
  39. }
  40. else {
  41. const AdditionalTargetUsers = getAdditionalTargetUsers(activity);
  42. notificationTargetUsers?.push(
  43. ...activeNotificationUsers,
  44. ...AdditionalTargetUsers,
  45. );
  46. }
  47. };
  48. return preNotify;
  49. };
  50. }
  51. export const preNotifyService = new PreNotifyService();