search.js 10 KB

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