slack.ts 12 KB

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