slackbot.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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: JSON.parse(payload.actions[0].value).pageList,
  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: JSON.stringify({
  165. offset, body, args, pageList: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  166. }),
  167. },
  168. ],
  169. };
  170. // show "Next" button if next page exists
  171. if (resultsTotal > offset + PAGINGLIMIT) {
  172. actionBlocks.elements.unshift(
  173. {
  174. type: 'button',
  175. text: {
  176. type: 'plain_text',
  177. text: 'Next',
  178. },
  179. action_id: 'showNextResults',
  180. value: JSON.stringify({ offset, body, args }),
  181. },
  182. );
  183. }
  184. await client.chat.postEphemeral({
  185. channel: body.channel_id,
  186. user: body.user_id,
  187. text: 'Successed To Search',
  188. blocks: [
  189. this.generateMarkdownSectionBlock(keywordsAndDesc),
  190. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  191. actionBlocks,
  192. ],
  193. });
  194. }
  195. catch {
  196. logger.error('Failed to get search results.');
  197. await client.chat.postEphemeral({
  198. channel: body.channel_id,
  199. user: body.user_id,
  200. text: 'Failed To Search',
  201. blocks: [
  202. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  203. ],
  204. });
  205. throw new Error('/growi command:search: Failed to search');
  206. }
  207. }
  208. async createModal(client, body) {
  209. try {
  210. await client.views.open({
  211. trigger_id: body.trigger_id,
  212. view: {
  213. type: 'modal',
  214. callback_id: 'createPage',
  215. title: {
  216. type: 'plain_text',
  217. text: 'Create Page',
  218. },
  219. submit: {
  220. type: 'plain_text',
  221. text: 'Submit',
  222. },
  223. close: {
  224. type: 'plain_text',
  225. text: 'Cancel',
  226. },
  227. blocks: [
  228. this.generateMarkdownSectionBlock('Create new page.'),
  229. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  230. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  231. ],
  232. },
  233. });
  234. }
  235. catch (err) {
  236. logger.error('Failed to create a page.');
  237. await client.chat.postEphemeral({
  238. channel: body.channel_id,
  239. user: body.user_id,
  240. text: 'Failed To Create',
  241. blocks: [
  242. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  243. ],
  244. });
  245. throw err;
  246. }
  247. }
  248. // Submit action in create Modal
  249. async createPageInGrowi(client, payload) {
  250. const Page = this.crowi.model('Page');
  251. const pathUtils = require('growi-commons').pathUtils;
  252. const contentsBody = payload.view.state.values.contents.contents_input.value;
  253. try {
  254. let path = payload.view.state.values.path.path_input.value;
  255. // sanitize path
  256. path = this.crowi.xss.process(path);
  257. path = pathUtils.normalizePath(path);
  258. // generate a dummy id because Operation to create a page needs ObjectId
  259. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  260. await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  261. }
  262. catch (err) {
  263. client.chat.postMessage({
  264. channel: payload.user.id,
  265. blocks: [
  266. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  267. });
  268. logger.error('Failed to create page in GROWI.');
  269. throw err;
  270. }
  271. }
  272. generateMarkdownSectionBlock(blocks) {
  273. return {
  274. type: 'section',
  275. text: {
  276. type: 'mrkdwn',
  277. text: blocks,
  278. },
  279. };
  280. }
  281. divider() {
  282. return {
  283. type: 'divider',
  284. };
  285. }
  286. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  287. return {
  288. type: 'input',
  289. block_id: blockId,
  290. label: {
  291. type: 'plain_text',
  292. text: labelText,
  293. },
  294. element: {
  295. type: 'plain_text_input',
  296. action_id: actionId,
  297. multiline: isMultiline,
  298. placeholder: {
  299. type: 'plain_text',
  300. text: placeholder,
  301. },
  302. },
  303. };
  304. }
  305. }
  306. module.exports = SlackBotService;