bolt.js 9.9 KB

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