bolt.js 11 KB

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