bolt.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. const logger = require('@alias/logger')('growi:service:BoltService');
  2. const PAGINGLIMIT = 10;
  3. class BoltReciever {
  4. init(app) {
  5. this.bolt = app;
  6. }
  7. async requestHandler(body) {
  8. if (this.bolt === undefined) {
  9. throw new Error('Slack Bot service is not setup');
  10. }
  11. let ackCalled = false;
  12. const payload = body.payload;
  13. let reqBody;
  14. if (payload != null) {
  15. reqBody = JSON.parse(payload);
  16. }
  17. else {
  18. reqBody = body;
  19. }
  20. const event = {
  21. body: reqBody,
  22. ack: (response) => {
  23. if (ackCalled) {
  24. return;
  25. }
  26. ackCalled = true;
  27. if (response instanceof Error) {
  28. const message = response.message || 'Error occurred';
  29. throw new Error(message);
  30. }
  31. return;
  32. },
  33. };
  34. await this.bolt.processEvent(event);
  35. }
  36. }
  37. const { App } = require('@slack/bolt');
  38. const { WebClient, LogLevel } = require('@slack/web-api');
  39. class BoltService {
  40. constructor(crowi) {
  41. this.crowi = crowi;
  42. this.receiver = new BoltReciever();
  43. const signingSecret = crowi.configManager.getConfig('crowi', 'slackbot:signingSecret');
  44. const token = crowi.configManager.getConfig('crowi', 'slackbot:token');
  45. const client = new WebClient(token, { logLevel: LogLevel.DEBUG });
  46. this.client = client;
  47. if (token != null || signingSecret != null) {
  48. logger.debug('SlackBot: setup is done');
  49. this.bolt = new App({
  50. token,
  51. signingSecret,
  52. receiver: this.receiver,
  53. });
  54. this.init();
  55. }
  56. }
  57. init() {
  58. // Example of listening for event
  59. // See. https://github.com/slackapi/bolt-js#listening-for-events
  60. // or https://slack.dev/bolt-js/concepts#basic
  61. this.bolt.command('/growi-bot', async({ command, ack, say }) => { // demo
  62. await say('Hello');
  63. });
  64. // The echo command simply echoes on command
  65. this.bolt.command('/echo', async({ command, ack, say }) => {
  66. // Acknowledge command request
  67. await ack();
  68. await say(`${command.text}`);
  69. });
  70. this.bolt.command('/growi', async({
  71. command, client, body, ack,
  72. }) => {
  73. await ack();
  74. const args = command.text.split(' ');
  75. const firstArg = args[0];
  76. switch (firstArg) {
  77. case 'search':
  78. await this.showEphemeralSearchResults(command, args);
  79. break;
  80. case 'create':
  81. await this.createModal(command, client, body);
  82. break;
  83. default:
  84. this.notCommand(command);
  85. break;
  86. }
  87. });
  88. this.bolt.view('createPage', async({
  89. ack, view, body, client,
  90. }) => {
  91. await ack();
  92. await this.createPageInGrowi(view, body);
  93. });
  94. this.bolt.action('showNextResults', async({
  95. ack, action,
  96. }) => {
  97. await ack();
  98. const parsedValue = JSON.parse(action.value);
  99. const command = parsedValue.command;
  100. const args = parsedValue.args;
  101. const offset = parsedValue.offset;
  102. const newOffset = offset + 10;
  103. this.showEphemeralSearchResults(command, args, newOffset);
  104. });
  105. this.bolt.action('shareSearchResults', async({
  106. body, ack, say, action,
  107. }) => {
  108. await ack();
  109. await say(action.value);
  110. });
  111. }
  112. notCommand(command) {
  113. logger.error('Invalid first argument');
  114. this.client.chat.postEphemeral({
  115. channel: command.channel_id,
  116. user: command.user_id,
  117. blocks: [
  118. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  119. ],
  120. });
  121. return;
  122. }
  123. getKeywords(args) {
  124. const keywordsArr = [];
  125. for (let i = 1; i < args.length; i++) {
  126. keywordsArr.push(args[i]);
  127. }
  128. const keywords = keywordsArr.join(' ');
  129. return keywords;
  130. }
  131. async getSearchResultPaths(command, args, offset = 0) {
  132. const firstKeyword = args[1];
  133. if (firstKeyword == null) {
  134. this.client.chat.postEphemeral({
  135. channel: command.channel_id,
  136. user: command.user_id,
  137. blocks: [
  138. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  139. ],
  140. });
  141. return;
  142. }
  143. const keywords = this.getKeywords(args);
  144. const { searchService } = this.crowi;
  145. const options = { limit: 10, offset };
  146. const results = await searchService.searchKeyword(keywords, null, {}, options);
  147. const resultsTotal = results.meta.total;
  148. // no search results
  149. if (results.data.length === 0) {
  150. logger.info(`No page found with "${keywords}"`);
  151. this.client.chat.postEphemeral({
  152. channel: command.channel_id,
  153. user: command.user_id,
  154. blocks: [
  155. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  156. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  157. this.divider(),
  158. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  159. this.divider(),
  160. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  161. this.divider(),
  162. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  163. this.divider(),
  164. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  165. this.divider(),
  166. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  167. this.divider(),
  168. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  169. this.divider(),
  170. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  171. ],
  172. });
  173. return;
  174. }
  175. const resultPaths = results.data.map((data) => {
  176. return data._source.path;
  177. });
  178. return {
  179. resultPaths, offset, resultsTotal,
  180. };
  181. }
  182. async showEphemeralSearchResults(command, args, offsetNum) {
  183. const {
  184. resultPaths, offset, resultsTotal,
  185. } = await this.getSearchResultPaths(command, args, offsetNum);
  186. const keywords = this.getKeywords(args);
  187. if (resultPaths == null) {
  188. return;
  189. }
  190. const base = this.crowi.appService.getSiteUrl();
  191. const urls = resultPaths.map((path) => {
  192. const url = new URL(path, base);
  193. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  194. });
  195. const searchResultsNum = resultPaths.length;
  196. let searchResultsDesc;
  197. switch (searchResultsNum) {
  198. case 10:
  199. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  200. break;
  201. case 1:
  202. searchResultsDesc = `${searchResultsNum} page is found`;
  203. break;
  204. default:
  205. searchResultsDesc = `${searchResultsNum} pages are found`;
  206. break;
  207. }
  208. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  209. try {
  210. // DEFAULT show "Share" button
  211. const actionBlocks = {
  212. type: 'actions',
  213. elements: [
  214. {
  215. type: 'button',
  216. text: {
  217. type: 'plain_text',
  218. text: 'Share',
  219. },
  220. style: 'primary',
  221. action_id: 'shareSearchResults',
  222. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  223. },
  224. ],
  225. };
  226. // show "Next" button if next page exists
  227. if (resultsTotal > offset + PAGINGLIMIT) {
  228. actionBlocks.elements.push(
  229. {
  230. type: 'button',
  231. text: {
  232. type: 'plain_text',
  233. text: 'Next',
  234. },
  235. action_id: 'showNextResults',
  236. value: JSON.stringify({ offset, command, args }),
  237. },
  238. );
  239. }
  240. await this.client.chat.postEphemeral({
  241. channel: command.channel_id,
  242. user: command.user_id,
  243. blocks: [
  244. this.generateMarkdownSectionBlock(keywordsAndDesc),
  245. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  246. actionBlocks,
  247. ],
  248. });
  249. }
  250. catch {
  251. logger.error('Failed to get search results.');
  252. await this.client.chat.postEphemeral({
  253. channel: command.channel_id,
  254. user: command.user_id,
  255. blocks: [
  256. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  257. ],
  258. });
  259. throw new Error('/growi command:search: Failed to search');
  260. }
  261. }
  262. async createModal(command, client, body) {
  263. const User = this.crowi.model('User');
  264. const slackUser = await User.findUserByUsername('slackUser');
  265. // if "slackUser" is null, don't show create Modal
  266. if (slackUser == null) {
  267. logger.error('Failed to create a page because slackUser is not found.');
  268. this.client.chat.postEphemeral({
  269. channel: command.channel_id,
  270. user: command.user_id,
  271. blocks: [this.generateMarkdownSectionBlock('*slackUser does not exist.*')],
  272. });
  273. throw new Error('/growi command:create: slackUser is not found');
  274. }
  275. try {
  276. await client.views.open({
  277. trigger_id: body.trigger_id,
  278. view: {
  279. type: 'modal',
  280. callback_id: 'createPage',
  281. title: {
  282. type: 'plain_text',
  283. text: 'Create Page',
  284. },
  285. submit: {
  286. type: 'plain_text',
  287. text: 'Submit',
  288. },
  289. close: {
  290. type: 'plain_text',
  291. text: 'Cancel',
  292. },
  293. blocks: [
  294. this.generateMarkdownSectionBlock('Create new page.'),
  295. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  296. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  297. ],
  298. },
  299. });
  300. }
  301. catch (err) {
  302. logger.error('Failed to create a page.');
  303. await this.client.chat.postEphemeral({
  304. channel: command.channel_id,
  305. user: command.user_id,
  306. blocks: [
  307. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  308. ],
  309. });
  310. throw err;
  311. }
  312. }
  313. // Submit action in create Modal
  314. async createPageInGrowi(view, body) {
  315. const User = this.crowi.model('User');
  316. const Page = this.crowi.model('Page');
  317. const pathUtils = require('growi-commons').pathUtils;
  318. const contentsBody = view.state.values.contents.contents_input.value;
  319. try {
  320. // search "slackUser" to create page in slack
  321. const slackUser = await User.findUserByUsername('slackUser');
  322. let path = view.state.values.path.path_input.value;
  323. // sanitize path
  324. path = this.crowi.xss.process(path);
  325. path = pathUtils.normalizePath(path);
  326. const user = slackUser._id;
  327. await Page.create(path, contentsBody, user, {});
  328. }
  329. catch (err) {
  330. this.client.chat.postMessage({
  331. channel: body.user.id,
  332. blocks: [
  333. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  334. });
  335. logger.error('Failed to create page in GROWI.');
  336. throw err;
  337. }
  338. }
  339. generateMarkdownSectionBlock(blocks) {
  340. return {
  341. type: 'section',
  342. text: {
  343. type: 'mrkdwn',
  344. text: blocks,
  345. },
  346. };
  347. }
  348. divider() {
  349. return {
  350. type: 'divider',
  351. };
  352. }
  353. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  354. return {
  355. type: 'input',
  356. block_id: blockId,
  357. label: {
  358. type: 'plain_text',
  359. text: labelText,
  360. },
  361. element: {
  362. type: 'plain_text_input',
  363. action_id: actionId,
  364. multiline: isMultiline,
  365. placeholder: {
  366. type: 'plain_text',
  367. text: placeholder,
  368. },
  369. },
  370. };
  371. }
  372. }
  373. module.exports = BoltService;