search.js 9.9 KB

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