search.js 12 KB

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