slackbot.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. const logger = require('@alias/logger')('growi:service:SlackBotService');
  2. const mongoose = require('mongoose');
  3. const axios = require('axios');
  4. const { markdownSectionBlock, divider } = require('@growi/slack');
  5. const { reshapeContentsBody } = require('@growi/slack');
  6. const { formatDistanceStrict, parse, format } = require('date-fns');
  7. const S2sMessage = require('../models/vo/s2s-message');
  8. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  9. class SlackBotService extends S2sMessageHandlable {
  10. constructor(crowi) {
  11. super();
  12. this.crowi = crowi;
  13. this.s2sMessagingService = crowi.s2sMessagingService;
  14. this.lastLoadedAt = null;
  15. this.initialize();
  16. }
  17. initialize() {
  18. this.lastLoadedAt = new Date();
  19. }
  20. /**
  21. * @inheritdoc
  22. */
  23. shouldHandleS2sMessage(s2sMessage) {
  24. const { eventName, updatedAt } = s2sMessage;
  25. if (eventName !== 'slackBotServiceUpdated' || updatedAt == null) {
  26. return false;
  27. }
  28. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. async handleS2sMessage() {
  34. const { configManager } = this.crowi;
  35. logger.info('Reset slack bot by pubsub notification');
  36. await configManager.loadConfigs();
  37. this.initialize();
  38. }
  39. async publishUpdatedMessage() {
  40. const { s2sMessagingService } = this;
  41. if (s2sMessagingService != null) {
  42. const s2sMessage = new S2sMessage('slackBotServiceUpdated', { updatedAt: new Date() });
  43. try {
  44. await s2sMessagingService.publish(s2sMessage);
  45. }
  46. catch (e) {
  47. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  48. }
  49. }
  50. }
  51. /**
  52. * Handle /commands endpoint
  53. */
  54. async handleCommand(command, client, body, ...opt) {
  55. const module = `./slack-command-handler/${command}`;
  56. try {
  57. const handler = require(module)(this.crowi);
  58. await handler.handleCommand(client, body, ...opt);
  59. }
  60. catch (err) {
  61. this.notCommand(client, body);
  62. }
  63. }
  64. async notCommand(client, body) {
  65. logger.error('Invalid first argument');
  66. client.chat.postEphemeral({
  67. channel: body.channel_id,
  68. user: body.user_id,
  69. text: 'No command',
  70. blocks: [
  71. markdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  72. ],
  73. });
  74. return;
  75. }
  76. generatePageLinkMrkdwn(pathname, href) {
  77. return `<${decodeURI(href)} | ${decodeURI(pathname)}>`;
  78. }
  79. appendSpeechBaloon(mrkdwn, commentCount) {
  80. return (commentCount != null && commentCount > 0)
  81. ? `${mrkdwn} :speech_balloon: ${commentCount}`
  82. : mrkdwn;
  83. }
  84. generateLastUpdateMrkdwn(updatedAt, baseDate) {
  85. if (updatedAt != null) {
  86. // cast to date
  87. const date = new Date(updatedAt);
  88. return formatDistanceStrict(date, baseDate);
  89. }
  90. return '';
  91. }
  92. async shareSinglePage(client, payload) {
  93. const { channel, user, actions } = payload;
  94. const appUrl = this.crowi.appService.getSiteUrl();
  95. const appTitle = this.crowi.appService.getAppTitle();
  96. const channelId = channel.id;
  97. const action = actions[0]; // shareSinglePage action must have button action
  98. // restore page data from value
  99. const { page, href, pathname } = JSON.parse(action.value);
  100. const { updatedAt, commentCount } = page;
  101. // share
  102. const now = new Date();
  103. return client.chat.postMessage({
  104. channel: channelId,
  105. blocks: [
  106. { type: 'divider' },
  107. markdownSectionBlock(`${this.appendSpeechBaloon(`*${this.generatePageLinkMrkdwn(pathname, href)}*`, commentCount)}`),
  108. {
  109. type: 'context',
  110. elements: [
  111. {
  112. type: 'mrkdwn',
  113. text: `<${decodeURI(appUrl)}|*${appTitle}*> | Last updated: ${this.generateLastUpdateMrkdwn(updatedAt, now)} | Shared by *${user.username}*`,
  114. },
  115. ],
  116. },
  117. ],
  118. });
  119. }
  120. async dismissSearchResults(client, payload) {
  121. const { response_url: responseUrl } = payload;
  122. return axios.post(responseUrl, {
  123. delete_original: true,
  124. });
  125. }
  126. // Submit action in create Modal
  127. async createPage(client, payload, path, channelId, contentsBody) {
  128. const Page = this.crowi.model('Page');
  129. const pathUtils = require('growi-commons').pathUtils;
  130. const reshapedContentsBody = reshapeContentsBody(contentsBody);
  131. try {
  132. // sanitize path
  133. const sanitizedPath = this.crowi.xss.process(path);
  134. const normalizedPath = pathUtils.normalizePath(sanitizedPath);
  135. // generate a dummy id because Operation to create a page needs ObjectId
  136. const dummyObjectIdOfUser = new mongoose.Types.ObjectId();
  137. const page = await Page.create(normalizedPath, reshapedContentsBody, dummyObjectIdOfUser, {});
  138. // Send a message when page creation is complete
  139. const growiUri = this.crowi.appService.getSiteUrl();
  140. await client.chat.postEphemeral({
  141. channel: channelId,
  142. user: payload.user.id,
  143. text: `The page <${decodeURI(`${growiUri}/${page._id} | ${decodeURI(growiUri + normalizedPath)}`)}> has been created.`,
  144. });
  145. }
  146. catch (err) {
  147. client.chat.postMessage({
  148. channel: payload.user.id,
  149. blocks: [
  150. markdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${reshapedContentsBody}`)],
  151. });
  152. logger.error('Failed to create page in GROWI.');
  153. throw err;
  154. }
  155. }
  156. async createPageInGrowi(client, payload) {
  157. const path = payload.view.state.values.path.path_input.value;
  158. const channelId = JSON.parse(payload.view.private_metadata).channelId;
  159. const contentsBody = payload.view.state.values.contents.contents_input.value;
  160. await this.createPage(client, payload, path, channelId, contentsBody);
  161. }
  162. async togetterCreatePageInGrowi(client, payload) {
  163. let result = [];
  164. const channel = payload.channel.id;
  165. try {
  166. // validate form
  167. const { path, oldest, latest } = await this.togetterValidateForm(client, payload);
  168. // get messages
  169. result = await this.togetterGetMessages(client, payload, channel, path, latest, oldest);
  170. // clean messages
  171. const cleanedContents = await this.togetterCleanMessages(result.messages);
  172. const contentsBody = cleanedContents.join('');
  173. // create and send url message
  174. await this.togetterCreatePageAndSendPreview(client, payload, path, channel, contentsBody);
  175. }
  176. catch (err) {
  177. await client.chat.postMessage({
  178. channel: payload.user.id,
  179. text: err.message,
  180. blocks: [
  181. markdownSectionBlock(err.message),
  182. ],
  183. });
  184. return;
  185. }
  186. }
  187. async togetterGetMessages(client, payload, channel, path, latest, oldest) {
  188. const result = await client.conversations.history({
  189. channel,
  190. latest,
  191. oldest,
  192. limit: 100,
  193. inclusive: true,
  194. });
  195. // return if no message found
  196. if (!result.messages.length) {
  197. throw new Error('No message found from togetter command. Try again.');
  198. }
  199. return result;
  200. }
  201. async togetterValidateForm(client, payload) {
  202. const grwTzoffset = this.crowi.appService.getTzoffset() * 60;
  203. const path = payload.state.values.page_path.page_path.value;
  204. let oldest = payload.state.values.oldest.oldest.value;
  205. let latest = payload.state.values.latest.latest.value;
  206. oldest = oldest.trim();
  207. latest = latest.trim();
  208. if (!path) {
  209. throw new Error('Page path is required.');
  210. }
  211. /**
  212. * RegExp for datetime yyyy/MM/dd-HH:mm
  213. * @see https://regex101.com/r/xiQoTb/1
  214. */
  215. const regexpDatetime = new RegExp(/^[12]\d\d\d\/(0[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])-(0[0-9]|1[012]):[0-5][0-9]$/);
  216. if (!regexpDatetime.test(oldest)) {
  217. throw new Error('Datetime format for oldest must be yyyy/MM/dd-HH:mm');
  218. }
  219. if (!regexpDatetime.test(latest)) {
  220. throw new Error('Datetime format for latest must be yyyy/MM/dd-HH:mm');
  221. }
  222. oldest = parse(oldest, 'yyyy/MM/dd-HH:mm', new Date()).getTime() / 1000 + grwTzoffset;
  223. // + 60s in order to include messages between hh:mm.00s and hh:mm.59s
  224. latest = parse(latest, 'yyyy/MM/dd-HH:mm', new Date()).getTime() / 1000 + grwTzoffset + 60;
  225. if (oldest > latest) {
  226. throw new Error('Oldest datetime must be older than the latest date time.');
  227. }
  228. return { path, oldest, latest };
  229. }
  230. async togetterCleanMessages(messages) {
  231. const cleanedContents = [];
  232. let lastMessage = {};
  233. const grwTzoffset = this.crowi.appService.getTzoffset() * 60;
  234. messages
  235. .sort((a, b) => {
  236. return a.ts - b.ts;
  237. })
  238. .forEach((message) => {
  239. // increment contentsBody while removing the same headers
  240. // exclude header
  241. const lastMessageTs = Math.floor(lastMessage.ts / 60);
  242. const messageTs = Math.floor(message.ts / 60);
  243. if (lastMessage.user === message.user && lastMessageTs === messageTs) {
  244. cleanedContents.push(`${message.text}\n`);
  245. }
  246. // include header
  247. else {
  248. const ts = (parseInt(message.ts) - grwTzoffset) * 1000;
  249. const time = format(new Date(ts), 'h:mm a');
  250. cleanedContents.push(`${message.user} ${time}\n${message.text}\n`);
  251. lastMessage = message;
  252. }
  253. });
  254. return cleanedContents;
  255. }
  256. async togetterCreatePageAndSendPreview(client, payload, path, channel, contentsBody) {
  257. try {
  258. await this.createPage(client, payload, path, channel, contentsBody);
  259. // send preview to dm
  260. await client.chat.postMessage({
  261. channel: payload.user.id,
  262. text: 'Preview from togetter command',
  263. blocks: [
  264. markdownSectionBlock('*Preview*'),
  265. divider(),
  266. markdownSectionBlock(contentsBody),
  267. divider(),
  268. ],
  269. });
  270. // dismiss message
  271. const responseUrl = payload.response_url;
  272. axios.post(responseUrl, {
  273. delete_original: true,
  274. });
  275. }
  276. catch (err) {
  277. throw new Error('Error occurred while creating a page.');
  278. }
  279. }
  280. async togetterCancel(client, payload) {
  281. const responseUrl = payload.response_url;
  282. axios.post(responseUrl, {
  283. delete_original: true,
  284. });
  285. }
  286. }
  287. module.exports = SlackBotService;