slackbot.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. this.channel_id = '';
  14. }
  15. initialize() {
  16. this.lastLoadedAt = new Date();
  17. }
  18. /**
  19. * @inheritdoc
  20. */
  21. shouldHandleS2sMessage(s2sMessage) {
  22. const { eventName, updatedAt } = s2sMessage;
  23. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  24. return false;
  25. }
  26. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  27. }
  28. /**
  29. * @inheritdoc
  30. */
  31. async handleS2sMessage() {
  32. const { configManager } = this.crowi;
  33. logger.info('Reset slack bot by pubsub notification');
  34. await configManager.loadConfigs();
  35. this.initialize();
  36. }
  37. async publishUpdatedMessage() {
  38. const { s2sMessagingService } = this;
  39. if (s2sMessagingService != null) {
  40. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  41. try {
  42. await s2sMessagingService.publish(s2sMessage);
  43. }
  44. catch (e) {
  45. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  46. }
  47. }
  48. }
  49. async notCommand(client, body) {
  50. logger.error('Invalid first argument');
  51. client.chat.postEphemeral({
  52. channel: body.channel_id,
  53. user: body.user_id,
  54. text: 'No command',
  55. blocks: [
  56. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  57. ],
  58. });
  59. return;
  60. }
  61. getKeywords(args) {
  62. const keywordsArr = args.slice(1);
  63. const keywords = keywordsArr.join(' ');
  64. return keywords;
  65. }
  66. async getSearchResultPaths(client, body, args, offset = 0) {
  67. const firstKeyword = args[1];
  68. if (firstKeyword == null) {
  69. client.chat.postEphemeral({
  70. channel: body.channel_id,
  71. user: body.user_id,
  72. text: 'Input keywords',
  73. blocks: [
  74. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  75. ],
  76. });
  77. return;
  78. }
  79. const keywords = this.getKeywords(args);
  80. const { searchService } = this.crowi;
  81. const options = { limit: 10, offset };
  82. const results = await searchService.searchKeyword(keywords, null, {}, options);
  83. const resultsTotal = results.meta.total;
  84. // no search results
  85. if (results.data.length === 0) {
  86. logger.info(`No page found with "${keywords}"`);
  87. client.chat.postEphemeral({
  88. channel: body.channel_id,
  89. user: body.user_id,
  90. text: `No page found with "${keywords}"`,
  91. blocks: [
  92. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  93. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  94. this.divider(),
  95. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  96. this.divider(),
  97. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  98. this.divider(),
  99. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  100. this.divider(),
  101. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  102. this.divider(),
  103. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  104. this.divider(),
  105. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  106. this.divider(),
  107. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  108. ],
  109. });
  110. return { resultPaths: [] };
  111. }
  112. const resultPaths = results.data.map((data) => {
  113. return data._source.path;
  114. });
  115. return {
  116. resultPaths, offset, resultsTotal,
  117. };
  118. }
  119. async shareSearchResults(client, payload) {
  120. client.chat.postMessage({
  121. channel: payload.channel.id,
  122. text: payload.actions[0].value,
  123. });
  124. }
  125. async showEphemeralSearchResults(client, body, args, offsetNum) {
  126. const {
  127. resultPaths, offset, resultsTotal,
  128. } = await this.getSearchResultPaths(client, body, args, offsetNum);
  129. const keywords = this.getKeywords(args);
  130. if (resultPaths.length === 0) {
  131. return;
  132. }
  133. const base = this.crowi.appService.getSiteUrl();
  134. const urls = resultPaths.map((path) => {
  135. const url = new URL(path, base);
  136. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  137. });
  138. const searchResultsNum = resultPaths.length;
  139. let searchResultsDesc;
  140. switch (searchResultsNum) {
  141. case 10:
  142. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  143. break;
  144. case 1:
  145. searchResultsDesc = `${searchResultsNum} page is found`;
  146. break;
  147. default:
  148. searchResultsDesc = `${searchResultsNum} pages are found`;
  149. break;
  150. }
  151. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  152. try {
  153. // DEFAULT show "Share" button
  154. const actionBlocks = {
  155. type: 'actions',
  156. elements: [
  157. {
  158. type: 'button',
  159. text: {
  160. type: 'plain_text',
  161. text: 'Share',
  162. },
  163. style: 'primary',
  164. action_id: 'shareSearchResults',
  165. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  166. },
  167. ],
  168. };
  169. // show "Next" button if next page exists
  170. if (resultsTotal > offset + PAGINGLIMIT) {
  171. actionBlocks.elements.unshift(
  172. {
  173. type: 'button',
  174. text: {
  175. type: 'plain_text',
  176. text: 'Next',
  177. },
  178. action_id: 'showNextResults',
  179. value: JSON.stringify({ offset, body, args }),
  180. },
  181. );
  182. }
  183. await client.chat.postEphemeral({
  184. channel: body.channel_id,
  185. user: body.user_id,
  186. text: 'Successed To Search',
  187. blocks: [
  188. this.generateMarkdownSectionBlock(keywordsAndDesc),
  189. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  190. actionBlocks,
  191. ],
  192. });
  193. }
  194. catch {
  195. logger.error('Failed to get search results.');
  196. await client.chat.postEphemeral({
  197. channel: body.channel_id,
  198. user: body.user_id,
  199. text: 'Failed To Search',
  200. blocks: [
  201. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  202. ],
  203. });
  204. throw new Error('/growi command:search: Failed to search');
  205. }
  206. }
  207. async createModal(client, body) {
  208. this.channel_id = body.channel_id;
  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. const page = await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  261. // Send a message when page creation is complete
  262. const growiUri = this.crowi.appService.getSiteUrl();
  263. await client.chat.postEphemeral({
  264. channel: this.channel_id,
  265. user: payload.user.id,
  266. text: `The page <${decodeURI(growiUri + path)} | ${decodeURI(`${growiUri}/${page._id}`)}> has been created.`,
  267. });
  268. }
  269. catch (err) {
  270. client.chat.postMessage({
  271. channel: payload.user.id,
  272. blocks: [
  273. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  274. });
  275. logger.error('Failed to create page in GROWI.');
  276. throw err;
  277. }
  278. }
  279. generateMarkdownSectionBlock(blocks) {
  280. return {
  281. type: 'section',
  282. text: {
  283. type: 'mrkdwn',
  284. text: blocks,
  285. },
  286. };
  287. }
  288. divider() {
  289. return {
  290. type: 'divider',
  291. };
  292. }
  293. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  294. return {
  295. type: 'input',
  296. block_id: blockId,
  297. label: {
  298. type: 'plain_text',
  299. text: labelText,
  300. },
  301. element: {
  302. type: 'plain_text_input',
  303. action_id: actionId,
  304. multiline: isMultiline,
  305. placeholder: {
  306. type: 'plain_text',
  307. text: placeholder,
  308. },
  309. },
  310. };
  311. }
  312. }
  313. module.exports = SlackBotService;