search.js 12 KB

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