slack.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import {
  2. BodyParams, Controller, Get, Inject, Post, Req, Res, UseBefore,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import { 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> {
  65. const { body, authorizeResult } = req;
  66. if (body.text == null) {
  67. return 'No text.';
  68. }
  69. // Send response immediately to avoid opelation_timeout error
  70. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  71. res.send();
  72. const growiCommand = parseSlashCommand(body);
  73. // register
  74. if (growiCommand.growiCommandType === 'register') {
  75. await this.registerService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  76. return;
  77. }
  78. /*
  79. * forward to GROWI server
  80. */
  81. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  82. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  83. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  84. const relations = await this.relationRepository.find({ installation: installation?.id });
  85. await relations.map((relation: Relation) => {
  86. // generate API URL
  87. const url = new URL('/_api/v3/slack-bot/commands', relation.growiUri);
  88. return axios.post(url.toString(), {
  89. ...body,
  90. tokenPtoG: relation.tokenPtoG,
  91. growiCommand,
  92. });
  93. });
  94. }
  95. @Post('/interactions')
  96. @UseBefore(AuthorizeInteractionMiddleware)
  97. async handleInteraction(@Req() req: AuthedReq, @Res() res: Res): Promise<void|string> {
  98. logger.info('receive interaction', req.body);
  99. logger.info('receive interaction', req.authorizeResult);
  100. return;
  101. }
  102. @Post('/events')
  103. async handleEvent(@BodyParams() body:{[key:string]:string}, @Res() res: Res): Promise<void|string> {
  104. // eslint-disable-next-line max-len
  105. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  106. if (body.type === 'url_verification') {
  107. return body.challenge;
  108. }
  109. logger.info('receive event', body);
  110. return;
  111. }
  112. @Get('/oauth_redirect')
  113. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  114. if (req.query.state === '') {
  115. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  116. res.end('<html>'
  117. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  118. + '<body style="text-align:center; padding-top:20%;">'
  119. + '<h1>Illegal state, try it again.</h1>'
  120. + '<a href="/slack/install">'
  121. + 'Go to install page'
  122. + '</a>'
  123. + '</body></html>');
  124. }
  125. await this.installerService.installer.handleCallback(req, res, {
  126. success: (installation, metadata, req, res) => {
  127. logger.info('Success to install', { installation, metadata });
  128. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  129. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  130. res.end('<html>'
  131. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  132. + '<body style="text-align:center; padding-top:20%;">'
  133. + '<h1>Congratulations!</h1>'
  134. + '<p>GROWI Bot installation has succeeded.</p>'
  135. + `<a href="${appPageUrl}">`
  136. + 'Access to Slack App detail page.'
  137. + '</a>'
  138. + '</body></html>');
  139. },
  140. failure: (error, installOptions, req, res) => {
  141. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  142. res.end('<html>'
  143. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  144. + '<body style="text-align:center; padding-top:20%;">'
  145. + '<h1>GROWI Bot installation failed</h1>'
  146. + '<p>Please contact administrators of your workspace</p>'
  147. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  148. + 'Manage app installation settings for your workspace'
  149. + '</a>'
  150. + '</body></html>');
  151. },
  152. });
  153. }
  154. }