index.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import type { IRevisionHasId } from '@growi/core';
  2. import type Crowi from '~/server/crowi';
  3. import { toArrayFromCsv } from '~/utils/to-array-from-csv';
  4. import {
  5. prepareSlackMessageForComment,
  6. prepareSlackMessageForPage,
  7. } from '../../util/slack';
  8. import { growiInfoService } from '../growi-info';
  9. /**
  10. * service class of UserNotification
  11. */
  12. export class UserNotificationService {
  13. crowi: Crowi;
  14. constructor(crowi: Crowi) {
  15. this.crowi = crowi;
  16. }
  17. /**
  18. * fire user notification
  19. *
  20. * @memberof UserNotificationService
  21. *
  22. * @param {Page} page
  23. * @param {User} user
  24. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  25. * @param {string} mode 'create' or 'update' or 'comment'
  26. * @param {IRevisionHasId} previousRevision
  27. * @param {Comment} comment
  28. */
  29. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  30. async fire(
  31. page,
  32. user,
  33. slackChannelsStr,
  34. mode,
  35. option?: { previousRevision: IRevisionHasId },
  36. comment = {},
  37. ): Promise<PromiseSettledResult<any>[]> {
  38. const { appService, slackIntegrationService } = this.crowi;
  39. if (!slackIntegrationService.isSlackConfigured) {
  40. throw new Error('slackIntegrationService has not been set up');
  41. }
  42. // update slackChannels attribute asynchronously
  43. page.updateSlackChannels(slackChannelsStr);
  44. const { previousRevision } = option ?? {};
  45. // "dev,slacktest" => [dev,slacktest]
  46. const slackChannels: (string | null)[] = toArrayFromCsv(slackChannelsStr);
  47. const appTitle = appService.getAppTitle();
  48. const siteUrl = growiInfoService.getSiteUrl();
  49. const promises = slackChannels.map(async (chan) => {
  50. let messageObj;
  51. if (mode === 'comment') {
  52. messageObj = prepareSlackMessageForComment(
  53. comment,
  54. user,
  55. appTitle,
  56. siteUrl,
  57. chan,
  58. page.path,
  59. );
  60. } else {
  61. messageObj = prepareSlackMessageForPage(
  62. page,
  63. user,
  64. appTitle,
  65. siteUrl,
  66. chan,
  67. mode,
  68. previousRevision,
  69. );
  70. }
  71. return slackIntegrationService.postMessage(messageObj);
  72. });
  73. return Promise.allSettled(promises);
  74. }
  75. }