slackbot.js 10 KB

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