slackbot.js 10 KB

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