slack.ts 13 KB

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