slackbot.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const PAGINGLIMIT = 10;
  4. const { WebClient, LogLevel } = require('@slack/web-api');
  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.client = null;
  13. this.searchService = null;
  14. this.isConnectedToSlack = false;
  15. this.lastLoadedAt = null;
  16. this.initialize();
  17. }
  18. async initialize() {
  19. this.isConnectedToSlack = false;
  20. const token = this.crowi.configManager.getConfig('crowi', 'slackbot:token');
  21. if (token != null) {
  22. this.client = new WebClient(token, { logLevel: LogLevel.DEBUG });
  23. logger.debug('SlackBot: setup is done');
  24. await this.sendAuthTest();
  25. }
  26. this.lastLoadedAt = new Date();
  27. }
  28. /**
  29. * @inheritdoc
  30. */
  31. shouldHandleS2sMessage(s2sMessage) {
  32. const { eventName, updatedAt } = s2sMessage;
  33. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  34. return false;
  35. }
  36. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  37. }
  38. /**
  39. * @inheritdoc
  40. */
  41. async handleS2sMessage() {
  42. const { configManager } = this.crowi;
  43. logger.info('Reset slack bot by pubsub notification');
  44. await configManager.loadConfigs();
  45. this.initialize();
  46. }
  47. async publishUpdatedMessage() {
  48. const { s2sMessagingService } = this;
  49. if (s2sMessagingService != null) {
  50. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  51. try {
  52. await s2sMessagingService.publish(s2sMessage);
  53. }
  54. catch (e) {
  55. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  56. }
  57. }
  58. }
  59. async sendAuthTest() {
  60. await this.client.api.test();
  61. this.isConnectedToSlack = true;
  62. }
  63. notCommand(body) {
  64. logger.error('Invalid first argument');
  65. this.client.chat.postEphemeral({
  66. channel: body.channel_id,
  67. user: body.user_id,
  68. blocks: [
  69. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  70. ],
  71. });
  72. return;
  73. }
  74. getKeywords(args) {
  75. const keywordsArr = args.slice(1);
  76. const keywords = keywordsArr.join(' ');
  77. return keywords;
  78. }
  79. async getSearchResultPaths(body, args, offset = 0) {
  80. const firstKeyword = args[1];
  81. if (firstKeyword == null) {
  82. this.client.chat.postEphemeral({
  83. channel: body.channel_id,
  84. user: body.user_id,
  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. this.client.chat.postEphemeral({
  100. channel: body.channel_id,
  101. user: body.user_id,
  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 getSlackChannelName() {
  131. const slackTeamInfo = await this.client.team.info();
  132. return slackTeamInfo.team.name;
  133. }
  134. shareSearchResults(payload) {
  135. this.client.chat.postMessage({
  136. channel: payload.channel.id,
  137. text: payload.actions[0].value,
  138. });
  139. }
  140. async showEphemeralSearchResults(body, args, offsetNum) {
  141. const {
  142. resultPaths, offset, resultsTotal,
  143. } = await this.getSearchResultPaths(body, args, offsetNum);
  144. const keywords = this.getKeywords(args);
  145. if (resultPaths.length === 0) {
  146. return;
  147. }
  148. const base = this.crowi.appService.getSiteUrl();
  149. const urls = resultPaths.map((path) => {
  150. const url = new URL(path, base);
  151. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  152. });
  153. const searchResultsNum = resultPaths.length;
  154. let searchResultsDesc;
  155. switch (searchResultsNum) {
  156. case 10:
  157. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  158. break;
  159. case 1:
  160. searchResultsDesc = `${searchResultsNum} page is found`;
  161. break;
  162. default:
  163. searchResultsDesc = `${searchResultsNum} pages are found`;
  164. break;
  165. }
  166. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  167. try {
  168. // DEFAULT show "Share" button
  169. const actionBlocks = {
  170. type: 'actions',
  171. elements: [
  172. {
  173. type: 'button',
  174. text: {
  175. type: 'plain_text',
  176. text: 'Share',
  177. },
  178. style: 'primary',
  179. action_id: 'shareSearchResults',
  180. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  181. },
  182. ],
  183. };
  184. // show "Next" button if next page exists
  185. if (resultsTotal > offset + PAGINGLIMIT) {
  186. actionBlocks.elements.unshift(
  187. {
  188. type: 'button',
  189. text: {
  190. type: 'plain_text',
  191. text: 'Next',
  192. },
  193. action_id: 'showNextResults',
  194. value: JSON.stringify({ offset, body, args }),
  195. },
  196. );
  197. }
  198. await this.client.chat.postEphemeral({
  199. channel: body.channel_id,
  200. user: body.user_id,
  201. blocks: [
  202. this.generateMarkdownSectionBlock(keywordsAndDesc),
  203. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  204. actionBlocks,
  205. ],
  206. });
  207. }
  208. catch {
  209. logger.error('Failed to get search results.');
  210. await this.client.chat.postEphemeral({
  211. channel: body.channel_id,
  212. user: body.user_id,
  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(body) {
  221. try {
  222. await this.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. },
  245. });
  246. }
  247. catch (err) {
  248. logger.error('Failed to create a page.');
  249. await this.client.chat.postEphemeral({
  250. channel: body.channel_id,
  251. user: body.user_id,
  252. blocks: [
  253. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  254. ],
  255. });
  256. throw err;
  257. }
  258. }
  259. // Submit action in create Modal
  260. async createPageInGrowi(payload) {
  261. const Page = this.crowi.model('Page');
  262. const pathUtils = require('growi-commons').pathUtils;
  263. const contentsBody = payload.view.state.values.contents.contents_input.value;
  264. try {
  265. let path = payload.view.state.values.path.path_input.value;
  266. // sanitize path
  267. path = this.crowi.xss.process(path);
  268. path = pathUtils.normalizePath(path);
  269. // generate a dummy id because Operation to create a page needs ObjectId
  270. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  271. await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  272. }
  273. catch (err) {
  274. this.client.chat.postMessage({
  275. channel: payload.user.id,
  276. blocks: [
  277. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  278. });
  279. logger.error('Failed to create page in GROWI.');
  280. throw err;
  281. }
  282. }
  283. generateMarkdownSectionBlock(blocks) {
  284. return {
  285. type: 'section',
  286. text: {
  287. type: 'mrkdwn',
  288. text: blocks,
  289. },
  290. };
  291. }
  292. divider() {
  293. return {
  294. type: 'divider',
  295. };
  296. }
  297. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  298. return {
  299. type: 'input',
  300. block_id: blockId,
  301. label: {
  302. type: 'plain_text',
  303. text: labelText,
  304. },
  305. element: {
  306. type: 'plain_text_input',
  307. action_id: actionId,
  308. multiline: isMultiline,
  309. placeholder: {
  310. type: 'plain_text',
  311. text: placeholder,
  312. },
  313. },
  314. };
  315. }
  316. }
  317. module.exports = SlackBotService;