search.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import {
  2. markdownSectionBlock, divider,
  3. } from '@growi/slack/dist/utils/block-kit-builder';
  4. import { generateLastUpdateMrkdwn } from '@growi/slack/dist/utils/generate-last-update-markdown';
  5. import loggerFactory from '~/utils/logger';
  6. import { growiInfoService } from '../growi-info';
  7. const logger = loggerFactory('growi:service:SlackCommandHandler:search');
  8. const PAGINGLIMIT = 7;
  9. /** @param {import('~/server/crowi').default} crowi Crowi instance */
  10. module.exports = (crowi) => {
  11. const BaseSlackCommandHandler = require('./slack-command-handler');
  12. const handler = new BaseSlackCommandHandler(crowi);
  13. function getKeywords(growiCommandArgs) {
  14. const keywords = growiCommandArgs.join(' ');
  15. return keywords;
  16. }
  17. function appendSpeechBaloon(mrkdwn, commentCount) {
  18. return (commentCount != null && commentCount > 0)
  19. ? `${mrkdwn} :speech_balloon: ${commentCount}`
  20. : mrkdwn;
  21. }
  22. function generateSearchResultPageLinkMrkdwn(appUrl, growiCommandArgs) {
  23. const url = new URL('/_search', appUrl);
  24. url.searchParams.append('q', growiCommandArgs.map(kwd => encodeURIComponent(kwd)).join('+'));
  25. return `<${url.href} | Results page>`;
  26. }
  27. function generatePageLinkMrkdwn(pathname, href) {
  28. return `<${decodeURI(href)} | ${decodeURI(pathname)}>`;
  29. }
  30. async function retrieveSearchResults(growiCommandArgs, offset = 0) {
  31. const keywords = getKeywords(growiCommandArgs);
  32. const { searchService } = crowi;
  33. const options = { limit: PAGINGLIMIT, offset };
  34. const [results] = await searchService.searchKeyword(keywords, null, {}, options);
  35. const resultsTotal = results.meta.total;
  36. const pages = results.data.map((data) => {
  37. const { path, updated_at: updatedAt, comment_count: commentCount } = data._source;
  38. return { path, updatedAt, commentCount };
  39. });
  40. return {
  41. pages, offset, resultsTotal,
  42. };
  43. }
  44. function buildRespondBodyForSearchResult(searchResult, growiCommandArgs) {
  45. const appUrl = growiInfoService.getSiteUrl();
  46. const appTitle = crowi.appService.getAppTitle();
  47. const {
  48. pages, offset, resultsTotal,
  49. } = searchResult;
  50. const keywords = getKeywords(growiCommandArgs);
  51. let searchResultsDesc;
  52. switch (resultsTotal) {
  53. case 1:
  54. searchResultsDesc = `*${resultsTotal}* page is found.`;
  55. break;
  56. default:
  57. searchResultsDesc = `*${resultsTotal}* pages are found.`;
  58. break;
  59. }
  60. const contextBlock = {
  61. type: 'context',
  62. elements: [
  63. {
  64. type: 'mrkdwn',
  65. text: `keyword(s) : *"${keywords}"*`
  66. + ` | Total ${resultsTotal} pages`
  67. + ` | Current: ${offset + 1} - ${offset + pages.length}`
  68. + ` | ${generateSearchResultPageLinkMrkdwn(appUrl, growiCommandArgs)}`,
  69. },
  70. ],
  71. };
  72. const now = new Date();
  73. const blocks = [
  74. markdownSectionBlock(`:mag: <${decodeURI(appUrl)}|*${appTitle}*>\n${searchResultsDesc}`),
  75. contextBlock,
  76. { type: 'divider' },
  77. // create an array by map and extract
  78. ...pages.map((page) => {
  79. const { path, updatedAt, commentCount } = page;
  80. // generate URL
  81. const url = new URL(path, appUrl);
  82. const { href, pathname } = url;
  83. return {
  84. type: 'section',
  85. text: {
  86. type: 'mrkdwn',
  87. text: `${appendSpeechBaloon(`*${generatePageLinkMrkdwn(pathname, href)}*`, commentCount)}`
  88. + ` \`${generateLastUpdateMrkdwn(updatedAt, now)}\``,
  89. },
  90. accessory: {
  91. type: 'button',
  92. action_id: 'search:shareSinglePageResult',
  93. text: {
  94. type: 'plain_text',
  95. text: 'Share',
  96. },
  97. value: JSON.stringify({ page, href, pathname }),
  98. },
  99. };
  100. }),
  101. { type: 'divider' },
  102. contextBlock,
  103. ];
  104. const actionBlocks = {
  105. type: 'actions',
  106. elements: [],
  107. };
  108. // add "Dismiss" button
  109. actionBlocks.elements.push(
  110. {
  111. type: 'button',
  112. text: {
  113. type: 'plain_text',
  114. text: 'Dismiss',
  115. },
  116. style: 'danger',
  117. action_id: 'search:dismissSearchResults',
  118. },
  119. );
  120. // show "Prev" button if previous page exists
  121. // eslint-disable-next-line yoda
  122. if (0 < offset) {
  123. actionBlocks.elements.push(
  124. {
  125. type: 'button',
  126. text: {
  127. type: 'plain_text',
  128. text: '< Prev',
  129. },
  130. action_id: 'search:showPrevResults',
  131. value: JSON.stringify({ offset, growiCommandArgs }),
  132. },
  133. );
  134. }
  135. // show "Next" button if next page exists
  136. if (offset + PAGINGLIMIT < resultsTotal) {
  137. actionBlocks.elements.push(
  138. {
  139. type: 'button',
  140. text: {
  141. type: 'plain_text',
  142. text: 'Next >',
  143. },
  144. action_id: 'search:showNextResults',
  145. value: JSON.stringify({ offset, growiCommandArgs }),
  146. },
  147. );
  148. }
  149. blocks.push(actionBlocks);
  150. return {
  151. text: 'Successed To Search',
  152. blocks,
  153. };
  154. }
  155. async function buildRespondBody(growiCommandArgs) {
  156. const firstKeyword = growiCommandArgs[0];
  157. // enpty keyword
  158. if (firstKeyword == null) {
  159. return {
  160. text: 'Input keywords',
  161. blocks: [
  162. markdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  163. ],
  164. };
  165. }
  166. const searchResult = await retrieveSearchResults(growiCommandArgs);
  167. // no search results
  168. if (searchResult.resultsTotal === 0) {
  169. const keywords = getKeywords(growiCommandArgs);
  170. logger.info(`No page found with "${keywords}"`);
  171. return {
  172. text: `No page found with "${keywords}"`,
  173. blocks: [
  174. markdownSectionBlock(`*No page matches your keyword(s) "${keywords}".*`),
  175. markdownSectionBlock(':mag: *Help: Searching*'),
  176. divider(),
  177. markdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  178. divider(),
  179. markdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  180. divider(),
  181. markdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  182. divider(),
  183. markdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  184. divider(),
  185. markdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  186. divider(),
  187. markdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  188. divider(),
  189. markdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  190. ],
  191. };
  192. }
  193. return buildRespondBodyForSearchResult(searchResult, growiCommandArgs);
  194. }
  195. handler.handleCommand = async function(growiCommand, client, body, respondUtil) {
  196. const { growiCommandArgs } = growiCommand;
  197. const respondBody = await buildRespondBody(growiCommandArgs);
  198. await respondUtil.respond(respondBody);
  199. };
  200. handler.handleInteractions = async function(client, interactionPayload, interactionPayloadAccessor, handlerMethodName, respondUtil) {
  201. await this[handlerMethodName](client, interactionPayload, interactionPayloadAccessor, respondUtil);
  202. };
  203. handler.shareSinglePageResult = async function(client, payload, interactionPayloadAccessor, respondUtil) {
  204. const { user } = payload;
  205. const appUrl = growiInfoService.getSiteUrl();
  206. const appTitle = crowi.appService.getAppTitle();
  207. const value = interactionPayloadAccessor.firstAction()?.value; // shareSinglePage action must have button action
  208. if (value == null) {
  209. await respondUtil.respond({
  210. text: 'Error occurred',
  211. blocks: [
  212. markdownSectionBlock('Failed to share the result.'),
  213. ],
  214. });
  215. return;
  216. }
  217. const parsedValue = interactionPayloadAccessor.getOriginalData() || JSON.parse(value);
  218. // restore page data from value
  219. const { page, href, pathname } = parsedValue;
  220. const { updatedAt, commentCount } = page;
  221. // share
  222. const now = new Date();
  223. return respondUtil.respondInChannel({
  224. blocks: [
  225. { type: 'divider' },
  226. markdownSectionBlock(`${appendSpeechBaloon(`*${generatePageLinkMrkdwn(pathname, href)}*`, commentCount)}`),
  227. {
  228. type: 'context',
  229. elements: [
  230. {
  231. type: 'mrkdwn',
  232. text: `<${decodeURI(appUrl)}|*${appTitle}*>`
  233. + ` | Last updated: \`${generateLastUpdateMrkdwn(updatedAt, now)}\``
  234. + ` | Shared by *${user.username}*`,
  235. },
  236. ],
  237. },
  238. ],
  239. });
  240. };
  241. async function showPrevOrNextResults(interactionPayloadAccessor, isNext = true, respondUtil) {
  242. const value = interactionPayloadAccessor.firstAction()?.value;
  243. if (value == null) {
  244. await respondUtil.respond({
  245. text: 'Error occurred',
  246. blocks: [
  247. markdownSectionBlock('Failed to show the next results.'),
  248. ],
  249. });
  250. return;
  251. }
  252. const parsedValue = interactionPayloadAccessor.getOriginalData() || JSON.parse(value);
  253. const { growiCommandArgs, offset: offsetNum } = parsedValue;
  254. const newOffsetNum = isNext
  255. ? offsetNum + PAGINGLIMIT
  256. : offsetNum - PAGINGLIMIT;
  257. const searchResult = await retrieveSearchResults(growiCommandArgs, newOffsetNum);
  258. await respondUtil.replaceOriginal(buildRespondBodyForSearchResult(searchResult, growiCommandArgs));
  259. }
  260. handler.showPrevResults = async function(client, payload, interactionPayloadAccessor, respondUtil) {
  261. return showPrevOrNextResults(interactionPayloadAccessor, false, respondUtil);
  262. };
  263. handler.showNextResults = async function(client, payload, interactionPayloadAccessor, respondUtil) {
  264. return showPrevOrNextResults(interactionPayloadAccessor, true, respondUtil);
  265. };
  266. handler.dismissSearchResults = async function(client, payload, interactionPayloadAccessor, respondUtil) {
  267. return respondUtil.deleteOriginal();
  268. };
  269. return handler;
  270. };