slackbot.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const PAGINGLIMIT = 10;
  4. const { reshapeContentsBody } = require('@growi/slack');
  5. const S2sMessage = require('../models/vo/s2s-message');
  6. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  7. class SlackBotService extends S2sMessageHandlable {
  8. constructor(crowi) {
  9. super();
  10. this.crowi = crowi;
  11. this.s2sMessagingService = crowi.s2sMessagingService;
  12. this.lastLoadedAt = null;
  13. this.initialize();
  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. async helpCommand(client, body) {
  62. const message = '*Help*\n growi-bot usage\n `/growi [command] [args]`\n\n Create new page\n `create`\n\n Search pages\n `search [keyword]`';
  63. client.chat.postEphemeral({
  64. channel: body.channel_id,
  65. user: body.user_id,
  66. text: 'Help',
  67. blocks: [
  68. this.generateMarkdownSectionBlock(message),
  69. ],
  70. });
  71. return;
  72. }
  73. getKeywords(args) {
  74. const keywordsArr = args.slice(1);
  75. const keywords = keywordsArr.join(' ');
  76. return keywords;
  77. }
  78. async getSearchResultPaths(client, body, args, offset = 0) {
  79. const firstKeyword = args[1];
  80. if (firstKeyword == null) {
  81. client.chat.postEphemeral({
  82. channel: body.channel_id,
  83. user: body.user_id,
  84. text: 'Input keywords',
  85. blocks: [
  86. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  87. ],
  88. });
  89. return;
  90. }
  91. const keywords = this.getKeywords(args);
  92. const { searchService } = this.crowi;
  93. const options = { limit: 10, offset };
  94. const results = await searchService.searchKeyword(keywords, null, {}, options);
  95. const resultsTotal = results.meta.total;
  96. // no search results
  97. if (results.data.length === 0) {
  98. logger.info(`No page found with "${keywords}"`);
  99. client.chat.postEphemeral({
  100. channel: body.channel_id,
  101. user: body.user_id,
  102. text: `No page found with "${keywords}"`,
  103. blocks: [
  104. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  105. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  106. this.divider(),
  107. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  108. this.divider(),
  109. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  110. this.divider(),
  111. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  112. this.divider(),
  113. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  114. this.divider(),
  115. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  116. this.divider(),
  117. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  118. this.divider(),
  119. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  120. ],
  121. });
  122. return { resultPaths: [] };
  123. }
  124. const resultPaths = results.data.map((data) => {
  125. return data._source.path;
  126. });
  127. return {
  128. resultPaths, offset, resultsTotal,
  129. };
  130. }
  131. async shareSearchResults(client, payload) {
  132. client.chat.postMessage({
  133. channel: payload.channel.id,
  134. text: JSON.parse(payload.actions[0].value).pageList,
  135. });
  136. }
  137. async showEphemeralSearchResults(client, body, args, offsetNum) {
  138. let searchResult;
  139. try {
  140. searchResult = await this.getSearchResultPaths(client, body, args, offsetNum);
  141. }
  142. catch (err) {
  143. logger.error('Failed to get search results.', err);
  144. await client.chat.postEphemeral({
  145. channel: body.channel_id,
  146. user: body.user_id,
  147. text: 'Failed To Search',
  148. blocks: [
  149. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  150. ],
  151. });
  152. throw new Error('/growi command:search: Failed to search');
  153. }
  154. const {
  155. resultPaths, offset, resultsTotal,
  156. } = searchResult;
  157. const keywords = this.getKeywords(args);
  158. if (resultPaths.length === 0) {
  159. return;
  160. }
  161. const appUrl = this.crowi.appService.getSiteUrl();
  162. const appTitle = this.crowi.appService.getAppTitle();
  163. const urls = resultPaths.map((path) => {
  164. const url = new URL(path, appUrl);
  165. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  166. });
  167. const searchResultsNum = resultPaths.length;
  168. let searchResultsDesc;
  169. switch (searchResultsNum) {
  170. case 10:
  171. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  172. break;
  173. case 1:
  174. searchResultsDesc = `${searchResultsNum} page is found`;
  175. break;
  176. default:
  177. searchResultsDesc = `${searchResultsNum} pages are found`;
  178. break;
  179. }
  180. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  181. // DEFAULT show "Share" button
  182. const actionBlocks = {
  183. type: 'actions',
  184. elements: [
  185. {
  186. type: 'button',
  187. text: {
  188. type: 'plain_text',
  189. text: 'Share',
  190. },
  191. style: 'primary',
  192. action_id: 'shareSearchResults',
  193. value: JSON.stringify({
  194. offset, body, args, pageList: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  195. }),
  196. },
  197. ],
  198. };
  199. // show "Next" button if next page exists
  200. if (resultsTotal > offset + PAGINGLIMIT) {
  201. actionBlocks.elements.unshift(
  202. {
  203. type: 'button',
  204. text: {
  205. type: 'plain_text',
  206. text: 'Next',
  207. },
  208. action_id: 'showNextResults',
  209. value: JSON.stringify({ offset, body, args }),
  210. },
  211. );
  212. }
  213. try {
  214. await client.chat.postEphemeral({
  215. channel: body.channel_id,
  216. user: body.user_id,
  217. text: 'Successed To Search',
  218. blocks: [
  219. this.generateMarkdownSectionBlock(`<${decodeURI(appUrl)}|*${appTitle}*>`),
  220. this.generateMarkdownSectionBlock(keywordsAndDesc),
  221. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  222. actionBlocks,
  223. ],
  224. });
  225. }
  226. catch (err) {
  227. logger.error('Failed to post ephemeral message.', err);
  228. await client.chat.postEphemeral({
  229. channel: body.channel_id,
  230. user: body.user_id,
  231. text: 'Failed to post ephemeral message.',
  232. blocks: [
  233. this.generateMarkdownSectionBlock(err.toString()),
  234. ],
  235. });
  236. throw new Error(err);
  237. }
  238. }
  239. async createModal(client, body) {
  240. try {
  241. await client.views.open({
  242. trigger_id: body.trigger_id,
  243. view: {
  244. type: 'modal',
  245. callback_id: 'createPage',
  246. title: {
  247. type: 'plain_text',
  248. text: 'Create Page',
  249. },
  250. submit: {
  251. type: 'plain_text',
  252. text: 'Submit',
  253. },
  254. close: {
  255. type: 'plain_text',
  256. text: 'Cancel',
  257. },
  258. blocks: [
  259. this.generateMarkdownSectionBlock('Create new page.'),
  260. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  261. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  262. ],
  263. private_metadata: JSON.stringify({ channelId: body.channel_id }),
  264. },
  265. });
  266. }
  267. catch (err) {
  268. logger.error('Failed to create a page.');
  269. await client.chat.postEphemeral({
  270. channel: body.channel_id,
  271. user: body.user_id,
  272. text: 'Failed To Create',
  273. blocks: [
  274. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  275. ],
  276. });
  277. throw err;
  278. }
  279. }
  280. // Submit action in create Modal
  281. async createPageInGrowi(client, payload) {
  282. const Page = this.crowi.model('Page');
  283. const pathUtils = require('growi-commons').pathUtils;
  284. const contentsBody = reshapeContentsBody(payload.view.state.values.contents.contents_input.value);
  285. try {
  286. let path = payload.view.state.values.path.path_input.value;
  287. // sanitize path
  288. path = this.crowi.xss.process(path);
  289. path = pathUtils.normalizePath(path);
  290. // generate a dummy id because Operation to create a page needs ObjectId
  291. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  292. const page = await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  293. // Send a message when page creation is complete
  294. const growiUri = this.crowi.appService.getSiteUrl();
  295. const channelId = JSON.parse(payload.view.private_metadata).channelId;
  296. await client.chat.postEphemeral({
  297. channel: channelId,
  298. user: payload.user.id,
  299. text: `The page <${decodeURI(`${growiUri}/${page._id} | ${decodeURI(growiUri + path)}`)}> has been created.`,
  300. });
  301. }
  302. catch (err) {
  303. client.chat.postMessage({
  304. channel: payload.user.id,
  305. blocks: [
  306. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  307. });
  308. logger.error('Failed to create page in GROWI.');
  309. throw err;
  310. }
  311. }
  312. generateMarkdownSectionBlock(blocks) {
  313. return {
  314. type: 'section',
  315. text: {
  316. type: 'mrkdwn',
  317. text: blocks,
  318. },
  319. };
  320. }
  321. divider() {
  322. return {
  323. type: 'divider',
  324. };
  325. }
  326. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  327. return {
  328. type: 'input',
  329. block_id: blockId,
  330. label: {
  331. type: 'plain_text',
  332. text: labelText,
  333. },
  334. element: {
  335. type: 'plain_text_input',
  336. action_id: actionId,
  337. multiline: isMultiline,
  338. placeholder: {
  339. type: 'plain_text',
  340. text: placeholder,
  341. },
  342. },
  343. };
  344. }
  345. }
  346. module.exports = SlackBotService;