preNotify.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import type { IPage, IUser, Ref } from '@growi/core';
  2. import { ActivityDocument } from '../models/activity';
  3. import Subscription from '../models/subscription';
  4. import { getModelSafely } from '../util/mongoose-utils';
  5. export type PreNotifyProps = {
  6. notificationTargetUsers?: IUser[],
  7. }
  8. export type PreNotify = (props: PreNotifyProps) => Promise<void>;
  9. export const generateInitialPreNotifyProps = (): PreNotifyProps => {
  10. const initialPreNotifyProps: IUser[] = [];
  11. return { notificationTargetUsers: initialPreNotifyProps };
  12. };
  13. export const generateDefaultPreNotify = (activity: ActivityDocument): PreNotify => {
  14. const preNotify = async(props: PreNotifyProps) => {
  15. const { notificationTargetUsers } = props;
  16. const User = getModelSafely('User') || require('~/server/models/user')();
  17. const actionUser = activity.user;
  18. const target = activity.target;
  19. const subscribedUsers = await Subscription.getSubscription(target as unknown as Ref<IPage>);
  20. const notificationUsers = subscribedUsers.filter(item => (item.toString() !== actionUser._id.toString()));
  21. const activeNotificationUsers = await User.find({
  22. _id: { $in: notificationUsers },
  23. status: User.STATUS_ACTIVE,
  24. }).distinct('_id');
  25. notificationTargetUsers?.concat(activeNotificationUsers);
  26. };
  27. return preNotify;
  28. };
  29. export const generatePreNotifyAlsoDescendants = (activity: ActivityDocument, descendantsSubscribedUsers): PreNotify => {
  30. const preNotify = async(props: PreNotifyProps) => {
  31. const { notificationTargetUsers } = props;
  32. const User = getModelSafely('User') || require('~/server/models/user')();
  33. const actionUser = activity.user;
  34. const target = activity.target;
  35. const subscribedUsers = await Subscription.getSubscription(target as unknown as Ref<IPage>);
  36. const notificationUsers = subscribedUsers.filter(item => (item.toString() !== actionUser._id.toString()));
  37. const activeNotificationUsers = await User.find({
  38. _id: { $in: notificationUsers },
  39. status: User.STATUS_ACTIVE,
  40. }).distinct('_id');
  41. notificationTargetUsers?.concat(
  42. activeNotificationUsers,
  43. descendantsSubscribedUsers as IUser[],
  44. );
  45. };
  46. return preNotify;
  47. };