slackbot.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. const { channel, container } = payload;
  133. const channelId = channel.id;
  134. const originalMessageTs = container.message_ts;
  135. console.log({ container });
  136. // get original message data
  137. const historyResult = await client.conversations.history({
  138. channel: channelId,
  139. inclusive: true,
  140. latest: originalMessageTs,
  141. limit: 1,
  142. });
  143. if (!historyResult.ok || historyResult.messages.length !== 1) {
  144. logger.error('Failed to share search results.');
  145. await client.chat.postEphemeral({
  146. channel: channelId,
  147. text: 'Failed to share search results.',
  148. });
  149. throw new Error('Failed to share search results.');
  150. }
  151. const originalMessage = historyResult.messages[0];
  152. console.log({ originalMessage });
  153. // // share
  154. // const postPromise = client.chat.postMessage({
  155. // channel: channelId,
  156. // as_user: true,
  157. // text: message.text,
  158. // blocks: message.blocks,
  159. // });
  160. // // remove
  161. // const deletePromise = client.chat.delete({
  162. // channel: channelId,
  163. // as_user: false,
  164. // ts: originalMessageTs,
  165. // });
  166. // return Promise.all([postPromise, deletePromise]);
  167. }
  168. async showEphemeralSearchResults(client, body, args, offsetNum) {
  169. let searchResult;
  170. try {
  171. searchResult = await this.getSearchResultPaths(client, body, args, offsetNum);
  172. }
  173. catch (err) {
  174. logger.error('Failed to get search results.', err);
  175. await client.chat.postEphemeral({
  176. channel: body.channel_id,
  177. user: body.user_id,
  178. text: 'Failed To Search',
  179. blocks: [
  180. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  181. ],
  182. });
  183. throw new Error('/growi command:search: Failed to search');
  184. }
  185. const {
  186. resultPaths, offset, resultsTotal,
  187. } = searchResult;
  188. const keywords = this.getKeywords(args);
  189. if (resultPaths.length === 0) {
  190. return;
  191. }
  192. const appUrl = this.crowi.appService.getSiteUrl();
  193. const appTitle = this.crowi.appService.getAppTitle();
  194. const urls = resultPaths.map((path) => {
  195. const url = new URL(path, appUrl);
  196. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  197. });
  198. const searchResultsNum = resultPaths.length;
  199. let searchResultsDesc;
  200. switch (searchResultsNum) {
  201. case 10:
  202. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  203. break;
  204. case 1:
  205. searchResultsDesc = `${searchResultsNum} page is found`;
  206. break;
  207. default:
  208. searchResultsDesc = `${searchResultsNum} pages are found`;
  209. break;
  210. }
  211. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  212. // DEFAULT show "Share" button
  213. const actionBlocks = {
  214. type: 'actions',
  215. elements: [
  216. {
  217. type: 'button',
  218. text: {
  219. type: 'plain_text',
  220. text: 'Share',
  221. },
  222. style: 'primary',
  223. action_id: 'shareSearchResults',
  224. },
  225. ],
  226. };
  227. // show "Next" button if next page exists
  228. if (resultsTotal > offset + PAGINGLIMIT) {
  229. actionBlocks.elements.unshift(
  230. {
  231. type: 'button',
  232. text: {
  233. type: 'plain_text',
  234. text: 'Next',
  235. },
  236. action_id: 'showNextResults',
  237. value: JSON.stringify({ offset, body, args }),
  238. },
  239. );
  240. }
  241. try {
  242. await client.chat.postEphemeral({
  243. channel: body.channel_id,
  244. user: body.user_id,
  245. text: 'Successed To Search',
  246. blocks: [
  247. this.generateMarkdownSectionBlock(`<${decodeURI(appUrl)}|*${appTitle}*>`),
  248. this.generateMarkdownSectionBlock(keywordsAndDesc),
  249. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  250. actionBlocks,
  251. ],
  252. });
  253. }
  254. catch (err) {
  255. logger.error('Failed to post ephemeral message.', err);
  256. await client.chat.postEphemeral({
  257. channel: body.channel_id,
  258. user: body.user_id,
  259. text: 'Failed to post ephemeral message.',
  260. blocks: [
  261. this.generateMarkdownSectionBlock(err.toString()),
  262. ],
  263. });
  264. throw new Error(err);
  265. }
  266. }
  267. async createModal(client, body) {
  268. try {
  269. await client.views.open({
  270. trigger_id: body.trigger_id,
  271. view: {
  272. type: 'modal',
  273. callback_id: 'createPage',
  274. title: {
  275. type: 'plain_text',
  276. text: 'Create Page',
  277. },
  278. submit: {
  279. type: 'plain_text',
  280. text: 'Submit',
  281. },
  282. close: {
  283. type: 'plain_text',
  284. text: 'Cancel',
  285. },
  286. blocks: [
  287. this.generateMarkdownSectionBlock('Create new page.'),
  288. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  289. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  290. ],
  291. private_metadata: JSON.stringify({ channelId: body.channel_id }),
  292. },
  293. });
  294. }
  295. catch (err) {
  296. logger.error('Failed to create a page.');
  297. await client.chat.postEphemeral({
  298. channel: body.channel_id,
  299. user: body.user_id,
  300. text: 'Failed To Create',
  301. blocks: [
  302. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  303. ],
  304. });
  305. throw err;
  306. }
  307. }
  308. // Submit action in create Modal
  309. async createPageInGrowi(client, payload) {
  310. const Page = this.crowi.model('Page');
  311. const pathUtils = require('growi-commons').pathUtils;
  312. const contentsBody = reshapeContentsBody(payload.view.state.values.contents.contents_input.value);
  313. try {
  314. let path = payload.view.state.values.path.path_input.value;
  315. // sanitize path
  316. path = this.crowi.xss.process(path);
  317. path = pathUtils.normalizePath(path);
  318. // generate a dummy id because Operation to create a page needs ObjectId
  319. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  320. const page = await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  321. // Send a message when page creation is complete
  322. const growiUri = this.crowi.appService.getSiteUrl();
  323. const channelId = JSON.parse(payload.view.private_metadata).channelId;
  324. await client.chat.postEphemeral({
  325. channel: channelId,
  326. user: payload.user.id,
  327. text: `The page <${decodeURI(`${growiUri}/${page._id} | ${decodeURI(growiUri + path)}`)}> has been created.`,
  328. });
  329. }
  330. catch (err) {
  331. client.chat.postMessage({
  332. channel: payload.user.id,
  333. blocks: [
  334. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  335. });
  336. logger.error('Failed to create page in GROWI.');
  337. throw err;
  338. }
  339. }
  340. generateMarkdownSectionBlock(blocks) {
  341. return {
  342. type: 'section',
  343. text: {
  344. type: 'mrkdwn',
  345. text: blocks,
  346. },
  347. };
  348. }
  349. divider() {
  350. return {
  351. type: 'divider',
  352. };
  353. }
  354. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  355. return {
  356. type: 'input',
  357. block_id: blockId,
  358. label: {
  359. type: 'plain_text',
  360. text: labelText,
  361. },
  362. element: {
  363. type: 'plain_text_input',
  364. action_id: actionId,
  365. multiline: isMultiline,
  366. placeholder: {
  367. type: 'plain_text',
  368. text: placeholder,
  369. },
  370. },
  371. };
  372. }
  373. }
  374. module.exports = SlackBotService;