slack.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. const { body, authorizeResult } = req;
  101. // Send response immediately to avoid opelation_timeout error
  102. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  103. res.send();
  104. // pass
  105. if (body.ssl_check != null) {
  106. return;
  107. }
  108. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  109. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  110. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  111. const handleViewSubmission = async(inputValues) => {
  112. const inputGrowiUrl = inputValues.growiDomain.contents_input.value;
  113. const inputGrowiAccessToken = inputValues.growiAccessToken.contents_input.value;
  114. const inputProxyAccessToken = inputValues.proxyToken.contents_input.value;
  115. const order = await this.orderRepository.findOne({ installation: installation?.id, growiUrl: inputGrowiUrl });
  116. if (order != null) {
  117. this.orderRepository.update(
  118. { installation: installation?.id, growiUrl: inputGrowiUrl },
  119. { growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken },
  120. );
  121. }
  122. else {
  123. this.orderRepository.save({
  124. installation: installation?.id, growiUrl: inputGrowiUrl, growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken,
  125. });
  126. }
  127. await this.registerService.sendProxyURL(authorizeResult, body as {[key:string]:string});
  128. res.send();
  129. };
  130. const payload = JSON.parse(body.payload);
  131. const { type } = payload;
  132. const inputValues = payload.view.state.values;
  133. try {
  134. switch (type) {
  135. case 'view_submission':
  136. await handleViewSubmission(inputValues);
  137. break;
  138. default:
  139. break;
  140. }
  141. }
  142. catch (error) {
  143. logger.error(error);
  144. }
  145. }
  146. @Post('/events')
  147. async handleEvent(@BodyParams() body:{[key:string]:string}, @Res() res: Res): Promise<void|string> {
  148. // eslint-disable-next-line max-len
  149. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  150. if (body.type === 'url_verification') {
  151. return body.challenge;
  152. }
  153. logger.info('receive event', body);
  154. return;
  155. }
  156. @Get('/oauth_redirect')
  157. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  158. if (req.query.state === '') {
  159. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  160. res.end('<html>'
  161. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  162. + '<body style="text-align:center; padding-top:20%;">'
  163. + '<h1>Illegal state, try it again.</h1>'
  164. + '<a href="/slack/install">'
  165. + 'Go to install page'
  166. + '</a>'
  167. + '</body></html>');
  168. }
  169. await this.installerService.installer.handleCallback(req, res, {
  170. success: (installation, metadata, req, res) => {
  171. logger.info('Success to install', { installation, metadata });
  172. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  173. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  174. res.end('<html>'
  175. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  176. + '<body style="text-align:center; padding-top:20%;">'
  177. + '<h1>Congratulations!</h1>'
  178. + '<p>GROWI Bot installation has succeeded.</p>'
  179. + `<a href="${appPageUrl}">`
  180. + 'Access to Slack App detail page.'
  181. + '</a>'
  182. + '</body></html>');
  183. },
  184. failure: (error, installOptions, req, res) => {
  185. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  186. res.end('<html>'
  187. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  188. + '<body style="text-align:center; padding-top:20%;">'
  189. + '<h1>GROWI Bot installation failed</h1>'
  190. + '<p>Please contact administrators of your workspace</p>'
  191. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  192. + 'Manage app installation settings for your workspace'
  193. + '</a>'
  194. + '</body></html>');
  195. },
  196. });
  197. }
  198. }