slack.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import {
  2. BodyParams, Controller, Get, Inject, Post, Req, Res, UseBefore,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import { generateMarkdownSectionBlock, generateWebClient, parseSlashCommand } from '@growi/slack';
  6. import { Installation } from '~/entities/installation';
  7. import { InstallationRepository } from '~/repositories/installation';
  8. import { RelationRepository } from '~/repositories/relation';
  9. import { OrderRepository } from '~/repositories/order';
  10. import { InstallerService } from '~/services/InstallerService';
  11. import { RegisterService } from '~/services/RegisterService';
  12. import loggerFactory from '~/utils/logger';
  13. import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/authorizer';
  14. import { AuthedReq } from '~/interfaces/authorized-req';
  15. import { Relation } from '~/entities/relation';
  16. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  17. @Controller('/slack')
  18. export class SlackCtrl {
  19. @Inject()
  20. installerService: InstallerService;
  21. @Inject()
  22. installationRepository: InstallationRepository;
  23. @Inject()
  24. relationRepository: RelationRepository;
  25. @Inject()
  26. orderRepository: OrderRepository;
  27. @Inject()
  28. registerService: RegisterService;
  29. @Get('/testsave')
  30. testsave(): void {
  31. const installation = new Installation();
  32. installation.data = {
  33. team: undefined,
  34. enterprise: undefined,
  35. user: {
  36. id: '',
  37. token: undefined,
  38. scopes: undefined,
  39. },
  40. };
  41. // const installationRepository = getRepository(Installation);
  42. this.installationRepository.save(installation);
  43. }
  44. @Get('/install')
  45. async install(): Promise<string> {
  46. const url = await this.installerService.installer.generateInstallUrl({
  47. // Add the scopes your app needs
  48. scopes: [
  49. 'channels:history',
  50. 'commands',
  51. 'groups:history',
  52. 'im:history',
  53. 'mpim:history',
  54. 'chat:write',
  55. ],
  56. });
  57. return `<a href="${url}">`
  58. // eslint-disable-next-line max-len
  59. + '<img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcSet="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" />'
  60. + '</a>';
  61. }
  62. @Post('/commands')
  63. @UseBefore(AuthorizeCommandMiddleware)
  64. async handleCommand(@Req() req: AuthedReq, @Res() res: Res): Promise<void|string|Res> {
  65. const { body, authorizeResult } = req;
  66. if (body.text == null) {
  67. return 'No text.';
  68. }
  69. const growiCommand = parseSlashCommand(body);
  70. // register
  71. if (growiCommand.growiCommandType === 'register') {
  72. // Send response immediately to avoid opelation_timeout error
  73. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  74. res.send();
  75. return this.registerService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  76. }
  77. /*
  78. * forward to GROWI server
  79. */
  80. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  81. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  82. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  83. const relations = await this.relationRepository.find({ installation: installation?.id });
  84. if (relations.length === 0) {
  85. return res.json({
  86. blocks: [
  87. generateMarkdownSectionBlock('*No relation found.*'),
  88. generateMarkdownSectionBlock('Run `/growi register` first.'),
  89. ],
  90. });
  91. }
  92. // Send response immediately to avoid opelation_timeout error
  93. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  94. res.send();
  95. const promises = relations.map((relation: Relation) => {
  96. // generate API URL
  97. const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
  98. return axios.post(url.toString(), {
  99. ...body,
  100. tokenPtoG: relation.tokenPtoG,
  101. growiCommand,
  102. });
  103. });
  104. // pickup PromiseRejectedResult only
  105. const results = await Promise.allSettled(promises);
  106. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  107. if (rejectedResults.length > 0) {
  108. const botToken = installation?.data.bot?.token;
  109. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  110. const client = generateWebClient(botToken!);
  111. try {
  112. client.chat.postEphemeral({
  113. text: 'Error occured.',
  114. channel: body.channel_id,
  115. user: body.user_id,
  116. blocks: [
  117. generateMarkdownSectionBlock('*Error occured:*'),
  118. ...rejectedResults.map((rejectedResult) => {
  119. const reason = rejectedResult.reason.toString();
  120. const resData = rejectedResult.reason.response?.data;
  121. const resDataMessage = resData?.message || resData.toString();
  122. const errorMessage = `${reason} (${resDataMessage})`;
  123. return generateMarkdownSectionBlock(errorMessage);
  124. }),
  125. ],
  126. });
  127. }
  128. catch (err) {
  129. logger.error(err);
  130. }
  131. }
  132. }
  133. @Post('/interactions')
  134. @UseBefore(AuthorizeInteractionMiddleware)
  135. async handleInteraction(@Req() req: AuthedReq, @Res() res: Res): Promise<void|string> {
  136. logger.info('receive interaction', req.body);
  137. logger.info('receive interaction', req.authorizeResult);
  138. const { body, authorizeResult } = req;
  139. // Send response immediately to avoid opelation_timeout error
  140. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  141. res.send();
  142. // pass
  143. if (body.ssl_check != null) {
  144. return;
  145. }
  146. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  147. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  148. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  149. const handleViewSubmission = async(inputValues) => {
  150. const inputGrowiUrl = inputValues.growiDomain.contents_input.value;
  151. const inputGrowiAccessToken = inputValues.growiAccessToken.contents_input.value;
  152. const inputProxyAccessToken = inputValues.proxyToken.contents_input.value;
  153. const order = await this.orderRepository.findOne({ installation: installation?.id, growiUrl: inputGrowiUrl });
  154. if (order != null) {
  155. this.orderRepository.update(
  156. { installation: installation?.id, growiUrl: inputGrowiUrl },
  157. { growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken },
  158. );
  159. }
  160. else {
  161. this.orderRepository.save({
  162. installation: installation?.id, growiUrl: inputGrowiUrl, growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken,
  163. });
  164. }
  165. };
  166. const payload = JSON.parse(body.payload);
  167. const { type } = payload;
  168. const inputValues = payload.view.state.values;
  169. try {
  170. switch (type) {
  171. case 'view_submission':
  172. await handleViewSubmission(inputValues);
  173. break;
  174. default:
  175. break;
  176. }
  177. }
  178. catch (error) {
  179. logger.error(error);
  180. }
  181. }
  182. @Post('/events')
  183. async handleEvent(@BodyParams() body:{[key:string]:string}, @Res() res: Res): Promise<void|string> {
  184. // eslint-disable-next-line max-len
  185. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  186. if (body.type === 'url_verification') {
  187. return body.challenge;
  188. }
  189. logger.info('receive event', body);
  190. return;
  191. }
  192. @Get('/oauth_redirect')
  193. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  194. if (req.query.state === '') {
  195. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  196. res.end('<html>'
  197. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  198. + '<body style="text-align:center; padding-top:20%;">'
  199. + '<h1>Illegal state, try it again.</h1>'
  200. + '<a href="/slack/install">'
  201. + 'Go to install page'
  202. + '</a>'
  203. + '</body></html>');
  204. }
  205. await this.installerService.installer.handleCallback(req, res, {
  206. success: (installation, metadata, req, res) => {
  207. logger.info('Success to install', { installation, metadata });
  208. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  209. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  210. res.end('<html>'
  211. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  212. + '<body style="text-align:center; padding-top:20%;">'
  213. + '<h1>Congratulations!</h1>'
  214. + '<p>GROWI Bot installation has succeeded.</p>'
  215. + `<a href="${appPageUrl}">`
  216. + 'Access to Slack App detail page.'
  217. + '</a>'
  218. + '</body></html>');
  219. },
  220. failure: (error, installOptions, req, res) => {
  221. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  222. res.end('<html>'
  223. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  224. + '<body style="text-align:center; padding-top:20%;">'
  225. + '<h1>GROWI Bot installation failed</h1>'
  226. + '<p>Please contact administrators of your workspace</p>'
  227. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  228. + 'Manage app installation settings for your workspace'
  229. + '</a>'
  230. + '</body></html>');
  231. },
  232. });
  233. }
  234. }