2
0

slack.ts 7.9 KB

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