slackbot.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const axios = require('axios');
  4. const { formatDistanceStrict } = require('date-fns');
  5. const PAGINGLIMIT = 10;
  6. const { reshapeContentsBody } = require('@growi/slack');
  7. const S2sMessage = require('../models/vo/s2s-message');
  8. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  9. class SlackBotService extends S2sMessageHandlable {
  10. constructor(crowi) {
  11. super();
  12. this.crowi = crowi;
  13. this.s2sMessagingService = crowi.s2sMessagingService;
  14. this.lastLoadedAt = null;
  15. this.initialize();
  16. }
  17. initialize() {
  18. this.lastLoadedAt = new Date();
  19. }
  20. /**
  21. * @inheritdoc
  22. */
  23. shouldHandleS2sMessage(s2sMessage) {
  24. const { eventName, updatedAt } = s2sMessage;
  25. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  26. return false;
  27. }
  28. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. async handleS2sMessage() {
  34. const { configManager } = this.crowi;
  35. logger.info('Reset slack bot by pubsub notification');
  36. await configManager.loadConfigs();
  37. this.initialize();
  38. }
  39. async publishUpdatedMessage() {
  40. const { s2sMessagingService } = this;
  41. if (s2sMessagingService != null) {
  42. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  43. try {
  44. await s2sMessagingService.publish(s2sMessage);
  45. }
  46. catch (e) {
  47. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  48. }
  49. }
  50. }
  51. async notCommand(client, body) {
  52. logger.error('Invalid first argument');
  53. client.chat.postEphemeral({
  54. channel: body.channel_id,
  55. user: body.user_id,
  56. text: 'No command',
  57. blocks: [
  58. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  59. ],
  60. });
  61. return;
  62. }
  63. async helpCommand(client, body) {
  64. 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]`';
  65. client.chat.postEphemeral({
  66. channel: body.channel_id,
  67. user: body.user_id,
  68. text: 'Help',
  69. blocks: [
  70. this.generateMarkdownSectionBlock(message),
  71. ],
  72. });
  73. return;
  74. }
  75. getKeywords(args) {
  76. const keywordsArr = args.slice(1);
  77. const keywords = keywordsArr.join(' ');
  78. return keywords;
  79. }
  80. async retrieveSearchResults(client, body, args, offset = 0) {
  81. const firstKeyword = args[1];
  82. if (firstKeyword == null) {
  83. client.chat.postEphemeral({
  84. channel: body.channel_id,
  85. user: body.user_id,
  86. text: 'Input keywords',
  87. blocks: [
  88. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  89. ],
  90. });
  91. return;
  92. }
  93. const keywords = this.getKeywords(args);
  94. const { searchService } = this.crowi;
  95. const options = { limit: 10, offset };
  96. const results = await searchService.searchKeyword(keywords, null, {}, options);
  97. const resultsTotal = results.meta.total;
  98. // no search results
  99. if (results.data.length === 0) {
  100. logger.info(`No page found with "${keywords}"`);
  101. client.chat.postEphemeral({
  102. channel: body.channel_id,
  103. user: body.user_id,
  104. text: `No page found with "${keywords}"`,
  105. blocks: [
  106. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  107. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  108. this.divider(),
  109. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  110. this.divider(),
  111. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  112. this.divider(),
  113. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  114. this.divider(),
  115. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  116. this.divider(),
  117. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  118. this.divider(),
  119. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  120. this.divider(),
  121. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  122. ],
  123. });
  124. return { pages: [] };
  125. }
  126. const pages = results.data.map((data) => {
  127. const { path, updated_at: updatedAt, comment_count: commentCount } = data._source;
  128. return { path, updatedAt, commentCount };
  129. });
  130. return {
  131. pages, offset, resultsTotal,
  132. };
  133. }
  134. generatePageLinkMrkdwn(pathname, href) {
  135. return `<${decodeURI(href)} | ${decodeURI(pathname)}>`;
  136. }
  137. appendSpeechBaloon(mrkdwn, commentCount) {
  138. return (commentCount != null && commentCount > 0)
  139. ? `${mrkdwn} :speech_balloon: ${commentCount}`
  140. : mrkdwn;
  141. }
  142. generateLastUpdateMrkdwn(updatedAt, baseDate) {
  143. if (updatedAt != null) {
  144. // cast to date
  145. const date = new Date(updatedAt);
  146. return formatDistanceStrict(date, baseDate);
  147. }
  148. return '';
  149. }
  150. async shareSinglePage(client, payload) {
  151. const { channel, user, actions } = payload;
  152. const appUrl = this.crowi.appService.getSiteUrl();
  153. const appTitle = this.crowi.appService.getAppTitle();
  154. const channelId = channel.id;
  155. const action = actions[0]; // shareSinglePage action must have button action
  156. // restore page data from value
  157. const { page, href, pathname } = JSON.parse(action.value);
  158. const { updatedAt, commentCount } = page;
  159. // share
  160. const now = new Date();
  161. return client.chat.postMessage({
  162. channel: channelId,
  163. blocks: [
  164. { type: 'divider' },
  165. this.generateMarkdownSectionBlock(`${this.appendSpeechBaloon(`*${this.generatePageLinkMrkdwn(pathname, href)}*`, commentCount)}`),
  166. {
  167. type: 'context',
  168. elements: [
  169. {
  170. type: 'mrkdwn',
  171. text: `<${decodeURI(appUrl)}|*${appTitle}*> | Last updated: ${this.generateLastUpdateMrkdwn(updatedAt, now)} | Shared by *${user.username}*`,
  172. },
  173. ],
  174. },
  175. ],
  176. });
  177. }
  178. async dismissSearchResults(client, payload) {
  179. const { response_url: responseUrl } = payload;
  180. return axios.post(responseUrl, {
  181. delete_original: true,
  182. });
  183. }
  184. async showEphemeralSearchResults(client, body, args, offsetNum) {
  185. let searchResult;
  186. try {
  187. searchResult = await this.retrieveSearchResults(client, body, args, offsetNum);
  188. }
  189. catch (err) {
  190. logger.error('Failed to get search results.', err);
  191. await client.chat.postEphemeral({
  192. channel: body.channel_id,
  193. user: body.user_id,
  194. text: 'Failed To Search',
  195. blocks: [
  196. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  197. ],
  198. });
  199. throw new Error('/growi command:search: Failed to search');
  200. }
  201. const appUrl = this.crowi.appService.getSiteUrl();
  202. const appTitle = this.crowi.appService.getAppTitle();
  203. const {
  204. pages, offset, resultsTotal,
  205. } = searchResult;
  206. const keywords = this.getKeywords(args);
  207. let searchResultsDesc;
  208. switch (resultsTotal) {
  209. case 1:
  210. searchResultsDesc = `*${resultsTotal}* page is found.`;
  211. break;
  212. default:
  213. searchResultsDesc = `*${resultsTotal}* pages are found.`;
  214. break;
  215. }
  216. const contextBlock = {
  217. type: 'context',
  218. elements: [
  219. {
  220. type: 'mrkdwn',
  221. text: `keyword(s) : *"${keywords}"* | Current: ${offset + 1} - ${offset + pages.length} | Total ${resultsTotal} pages`,
  222. },
  223. ],
  224. };
  225. const now = new Date();
  226. const blocks = [
  227. this.generateMarkdownSectionBlock(`:mag: <${decodeURI(appUrl)}|*${appTitle}*>\n${searchResultsDesc}`),
  228. contextBlock,
  229. { type: 'divider' },
  230. // create an array by map and extract
  231. ...pages.map((page) => {
  232. const { path, updatedAt, commentCount } = page;
  233. // generate URL
  234. const url = new URL(path, appUrl);
  235. const { href, pathname } = url;
  236. return {
  237. type: 'section',
  238. text: {
  239. type: 'mrkdwn',
  240. text: `${this.appendSpeechBaloon(`*${this.generatePageLinkMrkdwn(pathname, href)}*`, commentCount)}`
  241. + `\n Last updated: ${this.generateLastUpdateMrkdwn(updatedAt, now)}`,
  242. },
  243. accessory: {
  244. type: 'button',
  245. action_id: 'shareSingleSearchResult',
  246. text: {
  247. type: 'plain_text',
  248. text: 'Share',
  249. },
  250. value: JSON.stringify({ page, href, pathname }),
  251. },
  252. };
  253. }),
  254. { type: 'divider' },
  255. contextBlock,
  256. ];
  257. // DEFAULT show "Share" button
  258. // const actionBlocks = {
  259. // type: 'actions',
  260. // elements: [
  261. // {
  262. // type: 'button',
  263. // text: {
  264. // type: 'plain_text',
  265. // text: 'Share',
  266. // },
  267. // style: 'primary',
  268. // action_id: 'shareSearchResults',
  269. // },
  270. // ],
  271. // };
  272. const actionBlocks = {
  273. type: 'actions',
  274. elements: [
  275. {
  276. type: 'button',
  277. text: {
  278. type: 'plain_text',
  279. text: 'Dismiss',
  280. },
  281. style: 'danger',
  282. action_id: 'dismissSearchResults',
  283. },
  284. ],
  285. };
  286. // show "Next" button if next page exists
  287. if (resultsTotal > offset + PAGINGLIMIT) {
  288. actionBlocks.elements.unshift(
  289. {
  290. type: 'button',
  291. text: {
  292. type: 'plain_text',
  293. text: 'Next',
  294. },
  295. action_id: 'showNextResults',
  296. value: JSON.stringify({ offset, body, args }),
  297. },
  298. );
  299. }
  300. blocks.push(actionBlocks);
  301. try {
  302. await client.chat.postEphemeral({
  303. channel: body.channel_id,
  304. user: body.user_id,
  305. text: 'Successed To Search',
  306. blocks,
  307. });
  308. }
  309. catch (err) {
  310. logger.error('Failed to post ephemeral message.', err);
  311. await client.chat.postEphemeral({
  312. channel: body.channel_id,
  313. user: body.user_id,
  314. text: 'Failed to post ephemeral message.',
  315. blocks: [
  316. this.generateMarkdownSectionBlock(err.toString()),
  317. ],
  318. });
  319. throw new Error(err);
  320. }
  321. }
  322. async createModal(client, body) {
  323. try {
  324. await client.views.open({
  325. trigger_id: body.trigger_id,
  326. view: {
  327. type: 'modal',
  328. callback_id: 'createPage',
  329. title: {
  330. type: 'plain_text',
  331. text: 'Create Page',
  332. },
  333. submit: {
  334. type: 'plain_text',
  335. text: 'Submit',
  336. },
  337. close: {
  338. type: 'plain_text',
  339. text: 'Cancel',
  340. },
  341. blocks: [
  342. this.generateMarkdownSectionBlock('Create new page.'),
  343. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  344. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  345. ],
  346. private_metadata: JSON.stringify({ channelId: body.channel_id }),
  347. },
  348. });
  349. }
  350. catch (err) {
  351. logger.error('Failed to create a page.');
  352. await client.chat.postEphemeral({
  353. channel: body.channel_id,
  354. user: body.user_id,
  355. text: 'Failed To Create',
  356. blocks: [
  357. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  358. ],
  359. });
  360. throw err;
  361. }
  362. }
  363. // Submit action in create Modal
  364. async createPageInGrowi(client, payload) {
  365. const Page = this.crowi.model('Page');
  366. const pathUtils = require('growi-commons').pathUtils;
  367. const contentsBody = reshapeContentsBody(payload.view.state.values.contents.contents_input.value);
  368. try {
  369. let path = payload.view.state.values.path.path_input.value;
  370. // sanitize path
  371. path = this.crowi.xss.process(path);
  372. path = pathUtils.normalizePath(path);
  373. // generate a dummy id because Operation to create a page needs ObjectId
  374. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  375. const page = await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  376. // Send a message when page creation is complete
  377. const growiUri = this.crowi.appService.getSiteUrl();
  378. const channelId = JSON.parse(payload.view.private_metadata).channelId;
  379. await client.chat.postEphemeral({
  380. channel: channelId,
  381. user: payload.user.id,
  382. text: `The page <${decodeURI(`${growiUri}/${page._id} | ${decodeURI(growiUri + path)}`)}> has been created.`,
  383. });
  384. }
  385. catch (err) {
  386. client.chat.postMessage({
  387. channel: payload.user.id,
  388. blocks: [
  389. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  390. });
  391. logger.error('Failed to create page in GROWI.');
  392. throw err;
  393. }
  394. }
  395. generateMarkdownSectionBlock(blocks) {
  396. return {
  397. type: 'section',
  398. text: {
  399. type: 'mrkdwn',
  400. text: blocks,
  401. },
  402. };
  403. }
  404. divider() {
  405. return {
  406. type: 'divider',
  407. };
  408. }
  409. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  410. return {
  411. type: 'input',
  412. block_id: blockId,
  413. label: {
  414. type: 'plain_text',
  415. text: labelText,
  416. },
  417. element: {
  418. type: 'plain_text_input',
  419. action_id: actionId,
  420. multiline: isMultiline,
  421. placeholder: {
  422. type: 'plain_text',
  423. text: placeholder,
  424. },
  425. },
  426. };
  427. }
  428. }
  429. module.exports = SlackBotService;