slackbot.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const axios = require('axios');
  4. const { markdownSectionBlock } = require('@growi/slack');
  5. const { reshapeContentsBody } = require('@growi/slack');
  6. const { formatDistanceStrict } = require('date-fns');
  7. const S2sMessage = require('../models/vo/s2s-message');
  8. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  9. class SlackBotService extends S2sMessageHandlable {
  10. constructor(crowi) {
  11. super();
  12. this.crowi = crowi;
  13. this.s2sMessagingService = crowi.s2sMessagingService;
  14. this.lastLoadedAt = null;
  15. this.initialize();
  16. }
  17. initialize() {
  18. this.lastLoadedAt = new Date();
  19. }
  20. /**
  21. * @inheritdoc
  22. */
  23. shouldHandleS2sMessage(s2sMessage) {
  24. const { eventName, updatedAt } = s2sMessage;
  25. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  26. return false;
  27. }
  28. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. async handleS2sMessage() {
  34. const { configManager } = this.crowi;
  35. logger.info('Reset slack bot by pubsub notification');
  36. await configManager.loadConfigs();
  37. this.initialize();
  38. }
  39. async publishUpdatedMessage() {
  40. const { s2sMessagingService } = this;
  41. if (s2sMessagingService != null) {
  42. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  43. try {
  44. await s2sMessagingService.publish(s2sMessage);
  45. }
  46. catch (e) {
  47. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  48. }
  49. }
  50. }
  51. /**
  52. * Handle /commands endpoint
  53. */
  54. async handleCommand(command, client, body, ...opt) {
  55. const module = `./slack-command-handler/${command}`;
  56. try {
  57. const handler = require(module)(this.crowi);
  58. await handler.handleCommand(client, body, ...opt);
  59. }
  60. catch (err) {
  61. this.notCommand(client, body);
  62. }
  63. }
  64. async notCommand(client, body) {
  65. logger.error('Invalid first argument');
  66. client.chat.postEphemeral({
  67. channel: body.channel_id,
  68. user: body.user_id,
  69. text: 'No command',
  70. blocks: [
  71. markdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  72. ],
  73. });
  74. return;
  75. }
  76. generatePageLinkMrkdwn(pathname, href) {
  77. return `<${decodeURI(href)} | ${decodeURI(pathname)}>`;
  78. }
  79. appendSpeechBaloon(mrkdwn, commentCount) {
  80. return (commentCount != null && commentCount > 0)
  81. ? `${mrkdwn} :speech_balloon: ${commentCount}`
  82. : mrkdwn;
  83. }
  84. generateLastUpdateMrkdwn(updatedAt, baseDate) {
  85. if (updatedAt != null) {
  86. // cast to date
  87. const date = new Date(updatedAt);
  88. return formatDistanceStrict(date, baseDate);
  89. }
  90. return '';
  91. }
  92. async shareSinglePage(client, payload) {
  93. const { channel, user, actions } = payload;
  94. const appUrl = this.crowi.appService.getSiteUrl();
  95. const appTitle = this.crowi.appService.getAppTitle();
  96. const channelId = channel.id;
  97. const action = actions[0]; // shareSinglePage action must have button action
  98. // restore page data from value
  99. const { page, href, pathname } = JSON.parse(action.value);
  100. const { updatedAt, commentCount } = page;
  101. // share
  102. const now = new Date();
  103. return client.chat.postMessage({
  104. channel: channelId,
  105. blocks: [
  106. { type: 'divider' },
  107. markdownSectionBlock(`${this.appendSpeechBaloon(`*${this.generatePageLinkMrkdwn(pathname, href)}*`, commentCount)}`),
  108. {
  109. type: 'context',
  110. elements: [
  111. {
  112. type: 'mrkdwn',
  113. text: `<${decodeURI(appUrl)}|*${appTitle}*> | Last updated: ${this.generateLastUpdateMrkdwn(updatedAt, now)} | Shared by *${user.username}*`,
  114. },
  115. ],
  116. },
  117. ],
  118. });
  119. }
  120. async dismissSearchResults(client, payload) {
  121. const { response_url: responseUrl } = payload;
  122. return axios.post(responseUrl, {
  123. delete_original: true,
  124. });
  125. }
  126. // Submit action in create Modal
  127. async createPage(client, payload, path, channelId, contentsBody) {
  128. const Page = this.crowi.model('Page');
  129. const pathUtils = require('growi-commons').pathUtils;
  130. const reshapedContentsBody = reshapeContentsBody(contentsBody);
  131. try {
  132. // sanitize path
  133. const sanitizedPath = this.crowi.xss.process(path);
  134. const normalizedPath = pathUtils.normalizePath(sanitizedPath);
  135. // generate a dummy id because Operation to create a page needs ObjectId
  136. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  137. const page = await Page.create(normalizedPath, reshapedContentsBody, dummyObjectIdOfUser, {});
  138. // Send a message when page creation is complete
  139. const growiUri = this.crowi.appService.getSiteUrl();
  140. await client.chat.postEphemeral({
  141. channel: channelId,
  142. user: payload.user.id,
  143. text: `The page <${decodeURI(`${growiUri}/${page._id} | ${decodeURI(growiUri + normalizedPath)}`)}> has been created.`,
  144. });
  145. }
  146. catch (err) {
  147. client.chat.postMessage({
  148. channel: payload.user.id,
  149. blocks: [
  150. markdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${reshapedContentsBody}`)],
  151. });
  152. logger.error('Failed to create page in GROWI.');
  153. throw err;
  154. }
  155. }
  156. async createPageInGrowi(client, payload) {
  157. const path = payload.view.state.values.path.path_input.value;
  158. const channelId = JSON.parse(payload.view.private_metadata).channelId;
  159. const contentsBody = payload.view.state.values.contents.contents_input.value;
  160. await this.createPage(client, payload, path, channelId, contentsBody);
  161. }
  162. async togetterCreatePageInGrowi(client, payload) {
  163. const { response_url: responseUrl } = payload;
  164. const selectedOptions = payload.state.values.selected_messages.checkboxes_changed.selected_options;
  165. const messages = selectedOptions.map((option) => {
  166. const header = option.text.text.concat('\n');
  167. const body = option.description.text.concat('\n');
  168. return header.concat(body);
  169. });
  170. let path = '';
  171. let channelId = '';
  172. if (payload.type === 'block_actions' && payload.actions[0].action_id === 'togetterCreatePage') {
  173. path = payload.state.values.page_path.page_path.value;
  174. channelId = payload.channel.id;
  175. }
  176. const contentsBody = messages.join('');
  177. // dismiss
  178. axios.post(responseUrl, {
  179. delete_original: true,
  180. });
  181. await this.createPage(client, payload, path, channelId, contentsBody);
  182. }
  183. }
  184. module.exports = SlackBotService;