search.js 10 KB

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