keep.js 9.4 KB

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