keep.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import {
  2. inputBlock, actionsBlock, buttonElement, markdownSectionBlock,
  3. } from '@growi/slack/dist/utils/block-kit-builder';
  4. import { format } from 'date-fns/format';
  5. import { parse } from 'date-fns/parse';
  6. import { SlackCommandHandlerError } from '~/server/models/vo/slack-command-handler-error';
  7. import loggerFactory from '~/utils/logger';
  8. const logger = loggerFactory('growi:service:SlackBotService:keep');
  9. module.exports = (crowi) => {
  10. const CreatePageService = require('./create-page-service');
  11. const createPageService = new CreatePageService(crowi);
  12. const BaseSlackCommandHandler = require('./slack-command-handler');
  13. const handler = new BaseSlackCommandHandler();
  14. const { User } = crowi.models;
  15. handler.handleCommand = async function(growiCommand, client, body, respondUtil) {
  16. await respondUtil.respond({
  17. text: 'Select messages to use.',
  18. blocks: this.keepMessageBlocks(body.channel_name),
  19. });
  20. return;
  21. };
  22. handler.handleInteractions = async function(client, interactionPayload, interactionPayloadAccessor, handlerMethodName, respondUtil) {
  23. await this[handlerMethodName](client, interactionPayload, interactionPayloadAccessor, respondUtil);
  24. };
  25. handler.cancel = async function(client, payload, interactionPayloadAccessor, respondUtil) {
  26. await respondUtil.deleteOriginal();
  27. };
  28. handler.createPage = async function(client, payload, interactionPayloadAccessor, respondUtil) {
  29. let result = [];
  30. const channelId = payload.channel.id; // this must exist since the type is always block_actions
  31. const user = await User.findUserBySlackMemberId(payload.user.id);
  32. // validate form
  33. const { path, oldest, newest } = await this.keepValidateForm(client, payload, interactionPayloadAccessor);
  34. // get messages
  35. result = await this.keepGetMessages(client, channelId, newest, oldest);
  36. // clean messages
  37. const cleanedContents = await this.keepCleanMessages(result.messages);
  38. const contentsBody = cleanedContents.join('');
  39. // create and send url message
  40. await this.keepCreatePageAndSendPreview(client, interactionPayloadAccessor, path, user, contentsBody, respondUtil);
  41. };
  42. handler.keepValidateForm = async function(client, payload, interactionPayloadAccessor) {
  43. const grwTzoffset = crowi.appService.getTzoffset() * 60;
  44. const path = interactionPayloadAccessor.getStateValues()?.page_path.page_path.value;
  45. let oldest = interactionPayloadAccessor.getStateValues()?.oldest.oldest.value;
  46. let newest = interactionPayloadAccessor.getStateValues()?.newest.newest.value;
  47. if (oldest == null || newest == null || path == null) {
  48. throw new SlackCommandHandlerError('All parameters are required. (Oldest datetime, Newst datetime and Page path)');
  49. }
  50. /**
  51. * RegExp for datetime yyyy/MM/dd-HH:mm
  52. * @see https://regex101.com/r/XbxdNo/1
  53. */
  54. const regexpDatetime = new RegExp(/^[12]\d\d\d\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])-([01][0-9]|2[0123]):[0-5][0-9]$/);
  55. if (!regexpDatetime.test(oldest.trim())) {
  56. throw new SlackCommandHandlerError('Datetime format for oldest must be yyyy/MM/dd-HH:mm');
  57. }
  58. if (!regexpDatetime.test(newest.trim())) {
  59. throw new SlackCommandHandlerError('Datetime format for newest must be yyyy/MM/dd-HH:mm');
  60. }
  61. oldest = parse(oldest, 'yyyy/MM/dd-HH:mm', new Date()).getTime() / 1000 + grwTzoffset;
  62. // + 60s in order to include messages between hh:mm.00s and hh:mm.59s
  63. newest = parse(newest, 'yyyy/MM/dd-HH:mm', new Date()).getTime() / 1000 + grwTzoffset + 60;
  64. if (oldest > newest) {
  65. throw new SlackCommandHandlerError('Oldest datetime must be older than the newest date time.');
  66. }
  67. return { path, oldest, newest };
  68. };
  69. async function retrieveHistory(client, channelId, newest, oldest) {
  70. return client.conversations.history({
  71. channel: channelId,
  72. newest,
  73. oldest,
  74. limit: 100,
  75. inclusive: true,
  76. });
  77. }
  78. handler.keepGetMessages = async function(client, channelId, newest, oldest) {
  79. let result;
  80. // first attempt
  81. try {
  82. result = await retrieveHistory(client, channelId, newest, oldest);
  83. }
  84. catch (err) {
  85. const errorCode = err.data?.errorCode;
  86. if (errorCode === 'not_in_channel') {
  87. // join and retry
  88. await client.conversations.join({
  89. channel: channelId,
  90. });
  91. result = await retrieveHistory(client, channelId, newest, oldest);
  92. }
  93. else if (errorCode === 'channel_not_found') {
  94. const message = ':cry: GROWI Bot couldn\'t get history data because *this channel was private*.'
  95. + '\nPlease add GROWI bot to this channel.'
  96. + '\n';
  97. throw new SlackCommandHandlerError(message, {
  98. respondBody: {
  99. text: message,
  100. blocks: [
  101. markdownSectionBlock(message),
  102. {
  103. type: 'image',
  104. image_url: 'https://user-images.githubusercontent.com/1638767/135658794-a8d2dbc8-580f-4203-b368-e74e2f3c7b3a.png',
  105. alt_text: 'Add app to this channel',
  106. },
  107. ],
  108. },
  109. });
  110. }
  111. else {
  112. throw err;
  113. }
  114. }
  115. // return if no message found
  116. if (result.messages.length === 0) {
  117. throw new SlackCommandHandlerError('No message found from keep command. Try different datetime.');
  118. }
  119. return result;
  120. };
  121. /**
  122. * Get all growi users from messages
  123. * @param {*} messages (array of messages)
  124. * @returns users object with matching Slack Member ID
  125. */
  126. handler.getGrowiUsersFromMessages = async function(messages) {
  127. const users = messages.map((message) => {
  128. return message.user;
  129. });
  130. const growiUsers = await User.findUsersBySlackMemberIds(users);
  131. return growiUsers;
  132. };
  133. /**
  134. * Convert slack member ID to growi user if slack member ID is found in messages
  135. * @param {*} messages
  136. */
  137. handler.injectGrowiUsernameToMessages = async function(messages) {
  138. const growiUsers = await this.getGrowiUsersFromMessages(messages);
  139. messages.map(async(message) => {
  140. const growiUser = growiUsers.find(user => user.slackMemberId === message.user);
  141. if (growiUser != null) {
  142. message.user = `${growiUser.name} (@${growiUser.username})`;
  143. }
  144. else {
  145. message.user = `This slack member ID is not registered (${message.user})`;
  146. }
  147. });
  148. };
  149. handler.keepCleanMessages = async function(messages) {
  150. const cleanedContents = [];
  151. let lastMessage = {};
  152. const grwTzoffset = crowi.appService.getTzoffset() * 60;
  153. await this.injectGrowiUsernameToMessages(messages);
  154. messages
  155. .sort((a, b) => {
  156. return a.ts - b.ts;
  157. })
  158. .forEach((message) => {
  159. // increment contentsBody while removing the same headers
  160. // exclude header
  161. const lastMessageTs = Math.floor(lastMessage.ts / 60);
  162. const messageTs = Math.floor(message.ts / 60);
  163. if (lastMessage.user === message.user && lastMessageTs === messageTs) {
  164. cleanedContents.push(`${message.text}\n`);
  165. }
  166. // include header
  167. else {
  168. const ts = (parseInt(message.ts) - grwTzoffset) * 1000;
  169. const time = format(new Date(ts), 'h:mm a');
  170. cleanedContents.push(`${message.user} ${time}\n${message.text}\n`);
  171. lastMessage = message;
  172. }
  173. });
  174. return cleanedContents;
  175. };
  176. handler.keepCreatePageAndSendPreview = async function(client, interactionPayloadAccessor, path, user, contentsBody, respondUtil) {
  177. await createPageService.createPageInGrowi(interactionPayloadAccessor, path, contentsBody, respondUtil, user);
  178. // TODO: contentsBody text characters must be less than 3001
  179. // send preview to dm
  180. // await client.chat.postMessage({
  181. // channel: userChannelId,
  182. // text: 'Preview from keep command',
  183. // blocks: [
  184. // markdownSectionBlock('*Preview*'),
  185. // divider(),
  186. // markdownSectionBlock(contentsBody),
  187. // divider(),
  188. // ],
  189. // });
  190. // dismiss
  191. await respondUtil.deleteOriginal();
  192. };
  193. handler.keepMessageBlocks = function(channelName) {
  194. const tzDateSec = new Date().getTime();
  195. const grwTzoffset = crowi.appService.getTzoffset() * 60 * 1000;
  196. const now = tzDateSec - grwTzoffset;
  197. const oldest = now - 60 * 60 * 1000;
  198. const newest = now;
  199. const initialOldest = format(oldest, 'yyyy/MM/dd-HH:mm');
  200. const initialNewest = format(newest, 'yyyy/MM/dd-HH:mm');
  201. const initialPagePath = `/slack/keep/${channelName}/${format(oldest, 'yyyyMMdd-HH:mm')} - ${format(newest, 'yyyyMMdd-HH:mm')}`;
  202. return [
  203. markdownSectionBlock('*The keep command is in alpha.*'),
  204. markdownSectionBlock('Select the oldest and newest datetime of the messages to use.'),
  205. inputBlock({
  206. type: 'plain_text_input',
  207. action_id: 'oldest',
  208. initial_value: initialOldest,
  209. }, 'oldest', 'Oldest datetime'),
  210. inputBlock({
  211. type: 'plain_text_input',
  212. action_id: 'newest',
  213. initial_value: initialNewest,
  214. }, 'newest', 'Newest datetime'),
  215. inputBlock({
  216. type: 'plain_text_input',
  217. placeholder: {
  218. type: 'plain_text',
  219. text: 'Input page path to create.',
  220. },
  221. initial_value: initialPagePath,
  222. action_id: 'page_path',
  223. }, 'page_path', 'Page path'),
  224. actionsBlock(
  225. buttonElement({ text: 'Cancel', actionId: 'keep:cancel' }),
  226. buttonElement({ text: 'Create page', actionId: 'keep:createPage', style: 'primary' }),
  227. ),
  228. ];
  229. };
  230. return handler;
  231. };