slackbot.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const PAGINGLIMIT = 10;
  4. const { generateWebClient } = 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.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 currentBotType = this.crowi.configManager.getConfig('crowi', 'slackbot:currentBotType');
  21. if (currentBotType != null) {
  22. let serverUri;
  23. let token;
  24. // connect to proxy
  25. if (currentBotType !== 'customBotWithoutProxy') {
  26. // TODO: https://youtrack.weseek.co.jp/issue/GW-5896
  27. serverUri = 'http://localhost:8080/slack-api-proxy/';
  28. }
  29. // connect directly
  30. else {
  31. token = this.crowi.configManager.getConfig('crowi', 'slackbot:token');
  32. }
  33. this.client = generateWebClient(token, serverUri);
  34. logger.debug('SlackBot: setup is done');
  35. await this.sendAuthTest();
  36. }
  37. this.lastLoadedAt = new Date();
  38. }
  39. /**
  40. * @inheritdoc
  41. */
  42. shouldHandleS2sMessage(s2sMessage) {
  43. const { eventName, updatedAt } = s2sMessage;
  44. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  45. return false;
  46. }
  47. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  48. }
  49. /**
  50. * @inheritdoc
  51. */
  52. async handleS2sMessage() {
  53. const { configManager } = this.crowi;
  54. logger.info('Reset slack bot by pubsub notification');
  55. await configManager.loadConfigs();
  56. this.initialize();
  57. }
  58. async publishUpdatedMessage() {
  59. const { s2sMessagingService } = this;
  60. if (s2sMessagingService != null) {
  61. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  62. try {
  63. await s2sMessagingService.publish(s2sMessage);
  64. }
  65. catch (e) {
  66. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  67. }
  68. }
  69. }
  70. async sendAuthTest() {
  71. await this.client.api.test();
  72. this.isConnectedToSlack = true;
  73. }
  74. notCommand(body) {
  75. logger.error('Invalid first argument');
  76. this.client.chat.postEphemeral({
  77. channel: body.channel_id,
  78. user: body.user_id,
  79. blocks: [
  80. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  81. ],
  82. });
  83. return;
  84. }
  85. getKeywords(args) {
  86. const keywordsArr = args.slice(1);
  87. const keywords = keywordsArr.join(' ');
  88. return keywords;
  89. }
  90. async getSearchResultPaths(body, args, offset = 0) {
  91. const firstKeyword = args[1];
  92. if (firstKeyword == null) {
  93. this.client.chat.postEphemeral({
  94. channel: body.channel_id,
  95. user: body.user_id,
  96. blocks: [
  97. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  98. ],
  99. });
  100. return;
  101. }
  102. const keywords = this.getKeywords(args);
  103. const { searchService } = this.crowi;
  104. const options = { limit: 10, offset };
  105. const results = await searchService.searchKeyword(keywords, null, {}, options);
  106. const resultsTotal = results.meta.total;
  107. // no search results
  108. if (results.data.length === 0) {
  109. logger.info(`No page found with "${keywords}"`);
  110. this.client.chat.postEphemeral({
  111. channel: body.channel_id,
  112. user: body.user_id,
  113. blocks: [
  114. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  115. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  116. this.divider(),
  117. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  118. this.divider(),
  119. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  120. this.divider(),
  121. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  122. this.divider(),
  123. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  124. this.divider(),
  125. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  126. this.divider(),
  127. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  128. this.divider(),
  129. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  130. ],
  131. });
  132. return { resultPaths: [] };
  133. }
  134. const resultPaths = results.data.map((data) => {
  135. return data._source.path;
  136. });
  137. return {
  138. resultPaths, offset, resultsTotal,
  139. };
  140. }
  141. async getSlackChannelName() {
  142. const slackTeamInfo = await this.client.team.info();
  143. return slackTeamInfo.team.name;
  144. }
  145. shareSearchResults(payload) {
  146. this.client.chat.postMessage({
  147. channel: payload.channel.id,
  148. text: payload.actions[0].value,
  149. });
  150. }
  151. async showEphemeralSearchResults(body, args, offsetNum) {
  152. const {
  153. resultPaths, offset, resultsTotal,
  154. } = await this.getSearchResultPaths(body, args, offsetNum);
  155. const keywords = this.getKeywords(args);
  156. if (resultPaths.length === 0) {
  157. return;
  158. }
  159. const base = this.crowi.appService.getSiteUrl();
  160. const urls = resultPaths.map((path) => {
  161. const url = new URL(path, base);
  162. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  163. });
  164. const searchResultsNum = resultPaths.length;
  165. let searchResultsDesc;
  166. switch (searchResultsNum) {
  167. case 10:
  168. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  169. break;
  170. case 1:
  171. searchResultsDesc = `${searchResultsNum} page is found`;
  172. break;
  173. default:
  174. searchResultsDesc = `${searchResultsNum} pages are found`;
  175. break;
  176. }
  177. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  178. try {
  179. // DEFAULT show "Share" button
  180. const actionBlocks = {
  181. type: 'actions',
  182. elements: [
  183. {
  184. type: 'button',
  185. text: {
  186. type: 'plain_text',
  187. text: 'Share',
  188. },
  189. style: 'primary',
  190. action_id: 'shareSearchResults',
  191. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  192. },
  193. ],
  194. };
  195. // show "Next" button if next page exists
  196. if (resultsTotal > offset + PAGINGLIMIT) {
  197. actionBlocks.elements.unshift(
  198. {
  199. type: 'button',
  200. text: {
  201. type: 'plain_text',
  202. text: 'Next',
  203. },
  204. action_id: 'showNextResults',
  205. value: JSON.stringify({ offset, body, args }),
  206. },
  207. );
  208. }
  209. await this.client.chat.postEphemeral({
  210. channel: body.channel_id,
  211. user: body.user_id,
  212. blocks: [
  213. this.generateMarkdownSectionBlock(keywordsAndDesc),
  214. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  215. actionBlocks,
  216. ],
  217. });
  218. }
  219. catch {
  220. logger.error('Failed to get search results.');
  221. await this.client.chat.postEphemeral({
  222. channel: body.channel_id,
  223. user: body.user_id,
  224. blocks: [
  225. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  226. ],
  227. });
  228. throw new Error('/growi command:search: Failed to search');
  229. }
  230. }
  231. async createModal(body) {
  232. try {
  233. await this.client.views.open({
  234. trigger_id: body.trigger_id,
  235. view: {
  236. type: 'modal',
  237. callback_id: 'createPage',
  238. title: {
  239. type: 'plain_text',
  240. text: 'Create Page',
  241. },
  242. submit: {
  243. type: 'plain_text',
  244. text: 'Submit',
  245. },
  246. close: {
  247. type: 'plain_text',
  248. text: 'Cancel',
  249. },
  250. blocks: [
  251. this.generateMarkdownSectionBlock('Create new page.'),
  252. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  253. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  254. ],
  255. },
  256. });
  257. }
  258. catch (err) {
  259. logger.error('Failed to create a page.');
  260. await this.client.chat.postEphemeral({
  261. channel: body.channel_id,
  262. user: body.user_id,
  263. blocks: [
  264. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  265. ],
  266. });
  267. throw err;
  268. }
  269. }
  270. // Submit action in create Modal
  271. async createPageInGrowi(payload) {
  272. const Page = this.crowi.model('Page');
  273. const pathUtils = require('growi-commons').pathUtils;
  274. const contentsBody = payload.view.state.values.contents.contents_input.value;
  275. try {
  276. let path = payload.view.state.values.path.path_input.value;
  277. // sanitize path
  278. path = this.crowi.xss.process(path);
  279. path = pathUtils.normalizePath(path);
  280. // generate a dummy id because Operation to create a page needs ObjectId
  281. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  282. await Page.create(path, contentsBody, dummyObjectIdOfUser, {});
  283. }
  284. catch (err) {
  285. this.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. module.exports = SlackBotService;