search.js 10 KB

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