slackbot.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const PAGINGLIMIT = 10;
  4. const S2sMessage = require('../models/vo/s2s-message');
  5. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  6. class SlackBotService extends S2sMessageHandlable {
  7. constructor(crowi) {
  8. super();
  9. this.crowi = crowi;
  10. this.s2sMessagingService = crowi.s2sMessagingService;
  11. this.lastLoadedAt = null;
  12. this.initialize();
  13. }
  14. initialize() {
  15. this.lastLoadedAt = new Date();
  16. }
  17. /**
  18. * @inheritdoc
  19. */
  20. shouldHandleS2sMessage(s2sMessage) {
  21. const { eventName, updatedAt } = s2sMessage;
  22. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  23. return false;
  24. }
  25. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  26. }
  27. /**
  28. * @inheritdoc
  29. */
  30. async handleS2sMessage() {
  31. const { configManager } = this.crowi;
  32. logger.info('Reset slack bot by pubsub notification');
  33. await configManager.loadConfigs();
  34. this.initialize();
  35. }
  36. async publishUpdatedMessage() {
  37. const { s2sMessagingService } = this;
  38. if (s2sMessagingService != null) {
  39. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  40. try {
  41. await s2sMessagingService.publish(s2sMessage);
  42. }
  43. catch (e) {
  44. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  45. }
  46. }
  47. }
  48. async notCommand(client, body) {
  49. logger.error('Invalid first argument');
  50. client.chat.postEphemeral({
  51. channel: body.channel_id,
  52. user: body.user_id,
  53. text: 'No command',
  54. blocks: [
  55. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  56. ],
  57. });
  58. return;
  59. }
  60. getKeywords(args) {
  61. const keywordsArr = args.slice(1);
  62. const keywords = keywordsArr.join(' ');
  63. return keywords;
  64. }
  65. async getSearchResultPaths(client, body, args, offset = 0) {
  66. const firstKeyword = args[1];
  67. if (firstKeyword == null) {
  68. client.chat.postEphemeral({
  69. channel: body.channel_id,
  70. user: body.user_id,
  71. text: 'Input keywords',
  72. blocks: [
  73. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  74. ],
  75. });
  76. return;
  77. }
  78. const keywords = this.getKeywords(args);
  79. const { searchService } = this.crowi;
  80. const options = { limit: 10, offset };
  81. const results = await searchService.searchKeyword(keywords, null, {}, options);
  82. const resultsTotal = results.meta.total;
  83. // no search results
  84. if (results.data.length === 0) {
  85. logger.info(`No page found with "${keywords}"`);
  86. client.chat.postEphemeral({
  87. channel: body.channel_id,
  88. user: body.user_id,
  89. text: `No page found with "${keywords}"`,
  90. blocks: [
  91. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  92. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  93. this.divider(),
  94. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  95. this.divider(),
  96. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  97. this.divider(),
  98. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  99. this.divider(),
  100. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  101. this.divider(),
  102. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  103. this.divider(),
  104. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  105. this.divider(),
  106. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  107. ],
  108. });
  109. return { resultPaths: [] };
  110. }
  111. const resultPaths = results.data.map((data) => {
  112. return data._source.path;
  113. });
  114. return {
  115. resultPaths, offset, resultsTotal,
  116. };
  117. }
  118. async shareSearchResults(client, payload) {
  119. client.chat.postMessage({
  120. channel: payload.channel.id,
  121. text: payload.actions[0].value,
  122. });
  123. }
  124. async showEphemeralSearchResults(client, body, args, offsetNum) {
  125. const {
  126. resultPaths, offset, resultsTotal,
  127. } = await this.getSearchResultPaths(client, body, args, offsetNum);
  128. const keywords = this.getKeywords(args);
  129. if (resultPaths.length === 0) {
  130. return;
  131. }
  132. const base = this.crowi.appService.getSiteUrl();
  133. const urls = resultPaths.map((path) => {
  134. const url = new URL(path, base);
  135. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  136. });
  137. const searchResultsNum = resultPaths.length;
  138. let searchResultsDesc;
  139. switch (searchResultsNum) {
  140. case 10:
  141. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  142. break;
  143. case 1:
  144. searchResultsDesc = `${searchResultsNum} page is found`;
  145. break;
  146. default:
  147. searchResultsDesc = `${searchResultsNum} pages are found`;
  148. break;
  149. }
  150. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  151. try {
  152. // DEFAULT show "Share" button
  153. const actionBlocks = {
  154. type: 'actions',
  155. elements: [
  156. {
  157. type: 'button',
  158. text: {
  159. type: 'plain_text',
  160. text: 'Share',
  161. },
  162. style: 'primary',
  163. action_id: 'shareSearchResults',
  164. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  165. },
  166. ],
  167. };
  168. // show "Next" button if next page exists
  169. if (resultsTotal > offset + PAGINGLIMIT) {
  170. actionBlocks.elements.unshift(
  171. {
  172. type: 'button',
  173. text: {
  174. type: 'plain_text',
  175. text: 'Next',
  176. },
  177. action_id: 'showNextResults',
  178. value: JSON.stringify({ offset, body, args }),
  179. },
  180. );
  181. }
  182. await client.chat.postEphemeral({
  183. channel: body.channel_id,
  184. user: body.user_id,
  185. text: 'Successed To Search',
  186. blocks: [
  187. this.generateMarkdownSectionBlock(keywordsAndDesc),
  188. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  189. actionBlocks,
  190. ],
  191. });
  192. }
  193. catch {
  194. logger.error('Failed to get search results.');
  195. await client.chat.postEphemeral({
  196. channel: body.channel_id,
  197. user: body.user_id,
  198. text: 'Failed To Search',
  199. blocks: [
  200. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  201. ],
  202. });
  203. throw new Error('/growi command:search: Failed to search');
  204. }
  205. }
  206. async createModal(client, body) {
  207. try {
  208. await client.views.open({
  209. trigger_id: body.trigger_id,
  210. view: {
  211. type: 'modal',
  212. callback_id: 'createPage',
  213. title: {
  214. type: 'plain_text',
  215. text: 'Create Page',
  216. },
  217. submit: {
  218. type: 'plain_text',
  219. text: 'Submit',
  220. },
  221. close: {
  222. type: 'plain_text',
  223. text: 'Cancel',
  224. },
  225. blocks: [
  226. this.generateMarkdownSectionBlock('Create new page.'),
  227. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  228. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  229. ],
  230. },
  231. });
  232. }
  233. catch (err) {
  234. logger.error('Failed to create a page.');
  235. await client.chat.postEphemeral({
  236. channel: body.channel_id,
  237. user: body.user_id,
  238. text: 'Failed To Create',
  239. blocks: [
  240. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  241. ],
  242. });
  243. throw err;
  244. }
  245. }
  246. // Submit action in create Modal
  247. async createPageInGrowi(client, payload) {
  248. const Page = this.crowi.model('Page');
  249. const pathUtils = require('growi-commons').pathUtils;
  250. const contentsBody = payload.view.state.values.contents.contents_input.value;
  251. try {
  252. let path = payload.view.state.values.path.path_input.value;
  253. // sanitize path
  254. path = this.crowi.xss.process(path);
  255. path = pathUtils.normalizePath(path);
  256. // generate a dummy id because Operation to create a page needs ObjectId
  257. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  258. await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  259. }
  260. catch (err) {
  261. client.chat.postMessage({
  262. channel: payload.user.id,
  263. blocks: [
  264. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  265. });
  266. logger.error('Failed to create page in GROWI.');
  267. throw err;
  268. }
  269. }
  270. generateMarkdownSectionBlock(blocks) {
  271. return {
  272. type: 'section',
  273. text: {
  274. type: 'mrkdwn',
  275. text: blocks,
  276. },
  277. };
  278. }
  279. divider() {
  280. return {
  281. type: 'divider',
  282. };
  283. }
  284. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  285. return {
  286. type: 'input',
  287. block_id: blockId,
  288. label: {
  289. type: 'plain_text',
  290. text: labelText,
  291. },
  292. element: {
  293. type: 'plain_text_input',
  294. action_id: actionId,
  295. multiline: isMultiline,
  296. placeholder: {
  297. type: 'plain_text',
  298. text: placeholder,
  299. },
  300. },
  301. };
  302. }
  303. }
  304. module.exports = SlackBotService;