slackbot.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. }
  14. initialize() {
  15. this.lastLoadedAt = new Date();
  16. }
  17. /**
  18. * @inheritdoc
  19. */
  20. shouldHandleS2sMessage(s2sMessage) {
  21. const { eventName, updatedAt } = s2sMessage;
  22. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  23. return false;
  24. }
  25. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  26. }
  27. /**
  28. * @inheritdoc
  29. */
  30. async handleS2sMessage() {
  31. const { configManager } = this.crowi;
  32. logger.info('Reset slack bot by pubsub notification');
  33. await configManager.loadConfigs();
  34. this.initialize();
  35. }
  36. async publishUpdatedMessage() {
  37. const { s2sMessagingService } = this;
  38. if (s2sMessagingService != null) {
  39. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  40. try {
  41. await s2sMessagingService.publish(s2sMessage);
  42. }
  43. catch (e) {
  44. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  45. }
  46. }
  47. }
  48. async notCommand(client, body) {
  49. logger.error('Invalid first argument');
  50. client.chat.postEphemeral({
  51. channel: body.channel_id,
  52. user: body.user_id,
  53. text: 'No command',
  54. blocks: [
  55. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  56. ],
  57. });
  58. return;
  59. }
  60. async helpCommand(client, body) {
  61. 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]`';
  62. client.chat.postEphemeral({
  63. channel: body.channel_id,
  64. user: body.user_id,
  65. text: 'Help',
  66. blocks: [
  67. this.generateMarkdownSectionBlock(message),
  68. ],
  69. });
  70. return;
  71. }
  72. getKeywords(args) {
  73. const keywordsArr = args.slice(1);
  74. const keywords = keywordsArr.join(' ');
  75. return keywords;
  76. }
  77. async getSearchResultPaths(client, body, args, offset = 0) {
  78. const firstKeyword = args[1];
  79. if (firstKeyword == null) {
  80. client.chat.postEphemeral({
  81. channel: body.channel_id,
  82. user: body.user_id,
  83. text: 'Input keywords',
  84. blocks: [
  85. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  86. ],
  87. });
  88. return;
  89. }
  90. const keywords = this.getKeywords(args);
  91. const { searchService } = this.crowi;
  92. const options = { limit: 10, offset };
  93. const results = await searchService.searchKeyword(keywords, null, {}, options);
  94. const resultsTotal = results.meta.total;
  95. // no search results
  96. if (results.data.length === 0) {
  97. logger.info(`No page found with "${keywords}"`);
  98. client.chat.postEphemeral({
  99. channel: body.channel_id,
  100. user: body.user_id,
  101. text: `No page found with "${keywords}"`,
  102. blocks: [
  103. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  104. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  105. this.divider(),
  106. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  107. this.divider(),
  108. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  109. this.divider(),
  110. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  111. this.divider(),
  112. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  113. this.divider(),
  114. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  115. this.divider(),
  116. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  117. this.divider(),
  118. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  119. ],
  120. });
  121. return { resultPaths: [] };
  122. }
  123. const resultPaths = results.data.map((data) => {
  124. return data._source.path;
  125. });
  126. return {
  127. resultPaths, offset, resultsTotal,
  128. };
  129. }
  130. async shareSearchResults(client, payload) {
  131. client.chat.postMessage({
  132. channel: payload.channel.id,
  133. text: JSON.parse(payload.actions[0].value).pageList,
  134. });
  135. }
  136. async showEphemeralSearchResults(client, body, args, offsetNum) {
  137. const {
  138. resultPaths, offset, resultsTotal,
  139. } = await this.getSearchResultPaths(client, body, args, offsetNum);
  140. const keywords = this.getKeywords(args);
  141. if (resultPaths.length === 0) {
  142. return;
  143. }
  144. const base = this.crowi.appService.getSiteUrl();
  145. const urls = resultPaths.map((path) => {
  146. const url = new URL(path, base);
  147. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  148. });
  149. const searchResultsNum = resultPaths.length;
  150. let searchResultsDesc;
  151. switch (searchResultsNum) {
  152. case 10:
  153. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  154. break;
  155. case 1:
  156. searchResultsDesc = `${searchResultsNum} page is found`;
  157. break;
  158. default:
  159. searchResultsDesc = `${searchResultsNum} pages are found`;
  160. break;
  161. }
  162. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  163. try {
  164. // DEFAULT show "Share" button
  165. const actionBlocks = {
  166. type: 'actions',
  167. elements: [
  168. {
  169. type: 'button',
  170. text: {
  171. type: 'plain_text',
  172. text: 'Share',
  173. },
  174. style: 'primary',
  175. action_id: 'shareSearchResults',
  176. value: JSON.stringify({
  177. offset, body, args, pageList: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  178. }),
  179. },
  180. ],
  181. };
  182. // show "Next" button if next page exists
  183. if (resultsTotal > offset + PAGINGLIMIT) {
  184. actionBlocks.elements.unshift(
  185. {
  186. type: 'button',
  187. text: {
  188. type: 'plain_text',
  189. text: 'Next',
  190. },
  191. action_id: 'showNextResults',
  192. value: JSON.stringify({ offset, body, args }),
  193. },
  194. );
  195. }
  196. await client.chat.postEphemeral({
  197. channel: body.channel_id,
  198. user: body.user_id,
  199. text: 'Successed To Search',
  200. blocks: [
  201. this.generateMarkdownSectionBlock(keywordsAndDesc),
  202. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  203. actionBlocks,
  204. ],
  205. });
  206. }
  207. catch {
  208. logger.error('Failed to get search results.');
  209. await client.chat.postEphemeral({
  210. channel: body.channel_id,
  211. user: body.user_id,
  212. text: 'Failed To Search',
  213. blocks: [
  214. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  215. ],
  216. });
  217. throw new Error('/growi command:search: Failed to search');
  218. }
  219. }
  220. async createModal(client, body) {
  221. try {
  222. await client.views.open({
  223. trigger_id: body.trigger_id,
  224. view: {
  225. type: 'modal',
  226. callback_id: 'createPage',
  227. title: {
  228. type: 'plain_text',
  229. text: 'Create Page',
  230. },
  231. submit: {
  232. type: 'plain_text',
  233. text: 'Submit',
  234. },
  235. close: {
  236. type: 'plain_text',
  237. text: 'Cancel',
  238. },
  239. blocks: [
  240. this.generateMarkdownSectionBlock('Create new page.'),
  241. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  242. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  243. ],
  244. private_metadata: JSON.stringify({ channelId: body.channel_id }),
  245. },
  246. });
  247. }
  248. catch (err) {
  249. logger.error('Failed to create a page.');
  250. await client.chat.postEphemeral({
  251. channel: body.channel_id,
  252. user: body.user_id,
  253. text: 'Failed To Create',
  254. blocks: [
  255. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  256. ],
  257. });
  258. throw err;
  259. }
  260. }
  261. // Submit action in create Modal
  262. async createPageInGrowi(client, payload) {
  263. const Page = this.crowi.model('Page');
  264. const pathUtils = require('growi-commons').pathUtils;
  265. let contentsBody = payload.view.state.values.contents.contents_input.value;
  266. contentsBody = this.reshapeContentsBody(contentsBody);
  267. try {
  268. let path = payload.view.state.values.path.path_input.value;
  269. // sanitize path
  270. path = this.crowi.xss.process(path);
  271. path = pathUtils.normalizePath(path);
  272. // generate a dummy id because Operation to create a page needs ObjectId
  273. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  274. const page = await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  275. // Send a message when page creation is complete
  276. const growiUri = this.crowi.appService.getSiteUrl();
  277. const channelId = JSON.parse(payload.view.private_metadata).channelId;
  278. await client.chat.postEphemeral({
  279. channel: channelId,
  280. user: payload.user.id,
  281. text: `The page <${decodeURI(`${growiUri}/${page._id} | ${decodeURI(growiUri + path)}`)}> has been created.`,
  282. });
  283. }
  284. catch (err) {
  285. client.chat.postMessage({
  286. channel: payload.user.id,
  287. blocks: [
  288. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  289. });
  290. logger.error('Failed to create page in GROWI.');
  291. throw err;
  292. }
  293. }
  294. generateMarkdownSectionBlock(blocks) {
  295. return {
  296. type: 'section',
  297. text: {
  298. type: 'mrkdwn',
  299. text: blocks,
  300. },
  301. };
  302. }
  303. divider() {
  304. return {
  305. type: 'divider',
  306. };
  307. }
  308. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  309. return {
  310. type: 'input',
  311. block_id: blockId,
  312. label: {
  313. type: 'plain_text',
  314. text: labelText,
  315. },
  316. element: {
  317. type: 'plain_text_input',
  318. action_id: actionId,
  319. multiline: isMultiline,
  320. placeholder: {
  321. type: 'plain_text',
  322. text: placeholder,
  323. },
  324. },
  325. };
  326. }
  327. /**
  328. * Reshape contentsBody
  329. */
  330. reshapeContentsBody(contentsBody) {
  331. let linesBeforeFirstHeader = [];
  332. // Remove everything before the first Header
  333. const removeLinesBeforeFirstHeader = (array) => {
  334. const regexpSectionHeader = new RegExp(/.+\s\s[\d]{1,2}:[\d]{2}(\s[AP]{1}M)?$/);
  335. let i = 0;
  336. while (!regexpSectionHeader.test(array[i]) && i <= array.length) {
  337. i++;
  338. }
  339. linesBeforeFirstHeader = linesBeforeFirstHeader.concat(array.slice(0, i));
  340. return array.slice(i);
  341. };
  342. const reshape = (str) => {
  343. const regexpSectionHeader = new RegExp(/.+\s\s[\d]{1,2}:[\d]{2}(\s[AP]{1}M)?$/);
  344. const regexpTime = new RegExp(/\s\s[\d]{1,2}:[\d]{2}(\s[AP]{1}M)?$/);
  345. const regexpReaction = new RegExp(/^:[+\w-]+:$/);
  346. const splitted = str.split('\n');
  347. const cleanedArray = removeLinesBeforeFirstHeader(splitted);
  348. if (cleanedArray.length === 0) {
  349. return linesBeforeFirstHeader.join('');
  350. }
  351. let didReactionRemoved = false;
  352. const reshapedArray = cleanedArray.map((line) => {
  353. let copyline = line;
  354. // Check 1: Did a reaction removed last time?
  355. if (didReactionRemoved) {
  356. // remove reaction count
  357. copyline = '';
  358. didReactionRemoved = false;
  359. }
  360. // Check 2: Is this line a header?
  361. else if (regexpSectionHeader.test(copyline)) {
  362. // extract time from line
  363. const time = copyline.match(regexpTime)[0];
  364. // </div><div class="slack-talk-bubble">##*username* HH:mm AM
  365. copyline = '</div>\n<div class="slack-talk-bubble">\n\n## **'.concat(copyline);
  366. copyline = copyline.replace(regexpTime, '**'.concat(time), '\n<');
  367. }
  368. // Check 3: Is this line a reaction?
  369. else if (regexpReaction.test(copyline)) {
  370. // remove reaction
  371. copyline = '';
  372. didReactionRemoved = true;
  373. }
  374. return copyline;
  375. });
  376. // remove all blanks
  377. const blanksRemoved = reshapedArray.filter(line => line !== '');
  378. // delete the first </div> and add </div> to the last row
  379. blanksRemoved[0] = blanksRemoved[0].replace(/<\/div>/g, '');
  380. blanksRemoved.push('</div>');
  381. // Add 2 spaces and 1 enter to all lines
  382. const completedArray = blanksRemoved.map(line => line.concat(' \n'));
  383. // join all
  384. const contentsBeforeFirstHeader = linesBeforeFirstHeader.join('');
  385. const contentsAfterFirstHeader = completedArray.join('');
  386. return contentsBeforeFirstHeader.concat(contentsAfterFirstHeader);
  387. };
  388. return reshape(contentsBody);
  389. }
  390. }
  391. module.exports = SlackBotService;