slack.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import {
  2. BodyParams, Controller, Get, Inject, Post, Req, Res, UseBefore,
  3. } from '@tsed/common';
  4. import axios from 'axios';
  5. import { WebAPICallResult } from '@slack/web-api';
  6. import {
  7. generateMarkdownSectionBlock, GrowiCommand, parseSlashCommand, postEphemeralErrors, verifySlackRequest,
  8. } from '@growi/slack';
  9. import { Relation } from '~/entities/relation';
  10. import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
  11. import { InstallationRepository } from '~/repositories/installation';
  12. import { RelationRepository } from '~/repositories/relation';
  13. import { OrderRepository } from '~/repositories/order';
  14. import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
  15. import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
  16. import { ExtractGrowiUriFromReq } from '~/middlewares/slack-to-growi/extract-growi-uri-from-req';
  17. import { InstallerService } from '~/services/InstallerService';
  18. import { SelectGrowiService } from '~/services/SelectGrowiService';
  19. import { RegisterService } from '~/services/RegisterService';
  20. import { UnregisterService } from '~/services/UnregisterService';
  21. import { InvalidUrlError } from '../models/errors';
  22. import loggerFactory from '~/utils/logger';
  23. const logger = loggerFactory('slackbot-proxy:controllers:slack');
  24. @Controller('/slack')
  25. export class SlackCtrl {
  26. @Inject()
  27. installerService: InstallerService;
  28. @Inject()
  29. installationRepository: InstallationRepository;
  30. @Inject()
  31. relationRepository: RelationRepository;
  32. @Inject()
  33. orderRepository: OrderRepository;
  34. @Inject()
  35. selectGrowiService: SelectGrowiService;
  36. @Inject()
  37. registerService: RegisterService;
  38. @Inject()
  39. unregisterService: UnregisterService;
  40. @Get('/install')
  41. async install(): Promise<string> {
  42. const url = await this.installerService.installer.generateInstallUrl({
  43. // Add the scopes your app needs
  44. scopes: [
  45. 'channels:history',
  46. 'commands',
  47. 'groups:history',
  48. 'im:history',
  49. 'mpim:history',
  50. 'chat:write',
  51. 'team:read',
  52. ],
  53. });
  54. return `<a href="${url}">`
  55. // eslint-disable-next-line max-len
  56. + '<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" />'
  57. + '</a>';
  58. }
  59. /**
  60. * Send command to specified GROWIs
  61. * @param growiCommand
  62. * @param relations
  63. * @param body
  64. * @returns
  65. */
  66. private async sendCommand(growiCommand: GrowiCommand, relations: Relation[], body: any) {
  67. if (relations.length === 0) {
  68. throw new Error('relations must be set');
  69. }
  70. const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
  71. const promises = relations.map((relation: Relation) => {
  72. // generate API URL
  73. const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
  74. return axios.post(url.toString(), {
  75. ...body,
  76. growiCommand,
  77. }, {
  78. headers: {
  79. 'x-growi-ptog-tokens': relation.tokenPtoG,
  80. },
  81. });
  82. });
  83. // pickup PromiseRejectedResult only
  84. const results = await Promise.allSettled(promises);
  85. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  86. try {
  87. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  88. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  89. }
  90. catch (err) {
  91. logger.error(err);
  92. }
  93. }
  94. @Post('/commands')
  95. @UseBefore(AddSigningSecretToReq, verifySlackRequest, AuthorizeCommandMiddleware)
  96. async handleCommand(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  97. const { body, authorizeResult } = req;
  98. if (body.text == null) {
  99. return 'No text.';
  100. }
  101. const growiCommand = parseSlashCommand(body);
  102. // register
  103. if (growiCommand.growiCommandType === 'register') {
  104. // Send response immediately to avoid opelation_timeout error
  105. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  106. res.send();
  107. return this.registerService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  108. }
  109. // unregister
  110. if (growiCommand.growiCommandType === 'unregister') {
  111. if (growiCommand.growiCommandArgs.length === 0) {
  112. return 'GROWI Urls is required.';
  113. }
  114. if (!growiCommand.growiCommandArgs.every(v => v.match(/^(https?:\/\/)/))) {
  115. return 'GROWI Urls must be urls.';
  116. }
  117. // Send response immediately to avoid opelation_timeout error
  118. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  119. res.send();
  120. return this.unregisterService.process(growiCommand, authorizeResult, body as {[key:string]:string});
  121. }
  122. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  123. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  124. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  125. // const relations = await this.relationRepository.find({ installation });
  126. const relations = await this.relationRepository.createQueryBuilder('relation')
  127. .where('relation.installationId = :id', { id: installation?.id })
  128. .leftJoinAndSelect('relation.installation', 'installation')
  129. .getMany();
  130. console.log('relations', relations);
  131. if (relations.length === 0) {
  132. return res.json({
  133. blocks: [
  134. generateMarkdownSectionBlock('*No relation found.*'),
  135. generateMarkdownSectionBlock('Run `/growi register` first.'),
  136. ],
  137. });
  138. }
  139. // status
  140. if (growiCommand.growiCommandType === 'status') {
  141. return res.json({
  142. blocks: [
  143. generateMarkdownSectionBlock('*Found Relations to GROWI.*'),
  144. ...relations.map(relation => generateMarkdownSectionBlock(`GROWI url: ${relation.growiUri}.`)),
  145. ],
  146. });
  147. }
  148. // Send response immediately to avoid opelation_timeout error
  149. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  150. res.send();
  151. body.growiUris = [];
  152. relations.forEach((relation) => {
  153. if (relation.siglePostCommands.includes(growiCommand.growiCommandType)) {
  154. body.growiUris.push(relation.growiUri);
  155. }
  156. });
  157. if (body.growiUris != null && body.growiUris.length > 0) {
  158. return this.selectGrowiService.process(growiCommand, authorizeResult, body);
  159. }
  160. /*
  161. * forward to GROWI server
  162. */
  163. this.sendCommand(growiCommand, relations, body);
  164. }
  165. @Post('/interactions')
  166. @UseBefore(AuthorizeInteractionMiddleware, ExtractGrowiUriFromReq)
  167. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  168. logger.info('receive interaction', req.body);
  169. logger.info('receive interaction', req.authorizeResult);
  170. const { body, authorizeResult } = req;
  171. // Send response immediately to avoid opelation_timeout error
  172. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  173. res.send();
  174. // pass
  175. if (body.ssl_check != null) {
  176. return;
  177. }
  178. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  179. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  180. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  181. const payload = JSON.parse(body.payload);
  182. const callBackId = payload?.view?.callback_id;
  183. // register
  184. if (callBackId === 'register') {
  185. try {
  186. await this.registerService.insertOrderRecord(installation, authorizeResult.botToken, payload);
  187. }
  188. catch (err) {
  189. if (err instanceof InvalidUrlError) {
  190. logger.info(err.message);
  191. return;
  192. }
  193. logger.error(err);
  194. }
  195. await this.registerService.notifyServerUriToSlack(authorizeResult.botToken, payload);
  196. return;
  197. }
  198. // unregister
  199. if (callBackId === 'unregister') {
  200. await this.unregisterService.unregister(installation, authorizeResult, payload);
  201. return;
  202. }
  203. // forward to GROWI server
  204. if (callBackId === 'select_growi') {
  205. const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
  206. return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
  207. }
  208. /*
  209. * forward to GROWI server
  210. */
  211. const relation = await this.relationRepository.findOne({ installation, growiUri: req.growiUri });
  212. if (relation == null) {
  213. logger.error('*No relation found.*');
  214. return;
  215. }
  216. try {
  217. // generate API URL
  218. const url = new URL('/_api/v3/slack-integration/proxied/interactions', req.growiUri);
  219. await axios.post(url.toString(), {
  220. ...body,
  221. }, {
  222. headers: {
  223. 'x-growi-ptog-tokens': relation.tokenPtoG,
  224. },
  225. });
  226. }
  227. catch (err) {
  228. logger.error(err);
  229. }
  230. }
  231. @Post('/events')
  232. async handleEvent(@BodyParams() body:{[key:string]:string}, @Res() res: Res): Promise<void|string> {
  233. // eslint-disable-next-line max-len
  234. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  235. if (body.type === 'url_verification') {
  236. return body.challenge;
  237. }
  238. logger.info('receive event', body);
  239. return;
  240. }
  241. @Get('/oauth_redirect')
  242. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  243. if (req.query.state === '') {
  244. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  245. res.end('<html>'
  246. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  247. + '<body style="text-align:center; padding-top:20%;">'
  248. + '<h1>Illegal state, try it again.</h1>'
  249. + '<a href="/slack/install">'
  250. + 'Go to install page'
  251. + '</a>'
  252. + '</body></html>');
  253. }
  254. await this.installerService.installer.handleCallback(req, res, {
  255. success: (installation, metadata, req, res) => {
  256. logger.info('Success to install', { installation, metadata });
  257. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  258. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  259. res.end('<html>'
  260. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  261. + '<body style="text-align:center; padding-top:20%;">'
  262. + '<h1>Congratulations!</h1>'
  263. + '<p>GROWI Bot installation has succeeded.</p>'
  264. + `<a href="${appPageUrl}">`
  265. + 'Access to Slack App detail page.'
  266. + '</a>'
  267. + '</body></html>');
  268. },
  269. failure: (error, installOptions, req, res) => {
  270. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  271. res.end('<html>'
  272. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  273. + '<body style="text-align:center; padding-top:20%;">'
  274. + '<h1>GROWI Bot installation failed</h1>'
  275. + '<p>Please contact administrators of your workspace</p>'
  276. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  277. + 'Manage app installation settings for your workspace'
  278. + '</a>'
  279. + '</body></html>');
  280. },
  281. });
  282. }
  283. }