slack.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. console.log('in sendcommand');
  63. // console.log(relation);
  64. return axios.post(url.toString(), {
  65. ...body,
  66. growiCommand,
  67. }, {
  68. headers: {
  69. 'x-growi-ptog-tokens': relation.tokenPtoG,
  70. },
  71. });
  72. });
  73. // pickup PromiseRejectedResult only
  74. const results = await Promise.allSettled(promises);
  75. const rejectedResults: PromiseRejectedResult[] = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
  76. try {
  77. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  78. return postEphemeralErrors(rejectedResults, body.channel_id, body.user_id, botToken!);
  79. }
  80. catch (err) {
  81. logger.error(err);
  82. }
  83. }
  84. @Post('/commands')
  85. @UseBefore(AddSigningSecretToReq, verifySlackRequest, AuthorizeCommandMiddleware)
  86. async handleCommand(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  87. const { body, authorizeResult } = req;
  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. let isCommandPermitted = false;
  148. if (relationsForSingleUse.length > 0) {
  149. isCommandPermitted = true;
  150. body.growiUrisForSingleUse = relationsForSingleUse.map(v => v.growiUri);
  151. return this.selectGrowiService.process(growiCommand, authorizeResult, body);
  152. }
  153. const relationsForBroadcastUse:RelationMock[] = [];
  154. await Promise.all(relations.map(async(relation) => {
  155. const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relation, growiCommand.growiCommandType, baseDate);
  156. if (isSupported) {
  157. relationsForBroadcastUse.push(relation);
  158. }
  159. }));
  160. /*
  161. * forward to GROWI server
  162. */
  163. if (relationsForBroadcastUse.length > 0) {
  164. isCommandPermitted = true;
  165. this.sendCommand(growiCommand, relationsForBroadcastUse, body);
  166. }
  167. if (!isCommandPermitted) {
  168. const botToken = relations[0].installation?.data.bot?.token;
  169. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  170. const client = generateWebClient(botToken!);
  171. const relationMock = await this.relationMockRepository.findOne({
  172. where: { installation },
  173. });
  174. const permittedChannelsForEachCommand = relationMock?.permittedChannelsForEachCommand;
  175. const canCreateArray = permittedChannelsForEachCommand?.create;
  176. const canSearchArray = permittedChannelsForEachCommand?.search;
  177. if (canCreateArray == null || canSearchArray == null) {
  178. return client.chat.postEphemeral({
  179. text: 'Error occured.',
  180. channel: body.channel_id,
  181. user: body.user_id,
  182. blocks: [
  183. markdownSectionBlock(`It is not allowed to run *'${growiCommand.growiCommandType}'* command to this GROWI.`),
  184. ],
  185. });
  186. }
  187. const isCreate = canCreateArray.includes(body.channel_name);
  188. if (isCreate) {
  189. console.log('isCreate 内部');
  190. console.log(relations[0]);
  191. const relationsForBroadcastUse:RelationMock[] = [];
  192. body.permittedChannelsForEachCommand = relations[0].permittedChannelsForEachCommand;
  193. relationsForBroadcastUse.push(relations[0]);
  194. console.log(relations[0].permittedChannelsForEachCommand);
  195. console.log(body);
  196. return this.sendCommand(growiCommand, relationsForBroadcastUse, body);
  197. }
  198. }
  199. }
  200. @Post('/interactions')
  201. @UseBefore(AuthorizeInteractionMiddleware, ExtractGrowiUriFromReq)
  202. async handleInteraction(@Req() req: SlackOauthReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
  203. logger.info('receive interaction', req.authorizeResult);
  204. logger.debug('receive interaction', req.body);
  205. const { body, authorizeResult } = req;
  206. // Send response immediately to avoid opelation_timeout error
  207. // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
  208. res.send();
  209. // pass
  210. if (body.ssl_check != null) {
  211. return;
  212. }
  213. const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
  214. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  215. const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
  216. const payload = JSON.parse(body.payload);
  217. const callBackId = payload?.view?.callback_id;
  218. // register
  219. if (callBackId === 'register') {
  220. try {
  221. await this.registerService.insertOrderRecord(installation, authorizeResult.botToken, payload);
  222. }
  223. catch (err) {
  224. if (err instanceof InvalidUrlError) {
  225. logger.info(err.message);
  226. return;
  227. }
  228. logger.error(err);
  229. }
  230. await this.registerService.notifyServerUriToSlack(authorizeResult.botToken, payload);
  231. return;
  232. }
  233. // unregister
  234. if (callBackId === 'unregister') {
  235. await this.unregisterService.unregister(installation, authorizeResult, payload);
  236. return;
  237. }
  238. // forward to GROWI server
  239. if (callBackId === 'select_growi') {
  240. const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
  241. return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
  242. }
  243. /*
  244. * forward to GROWI server
  245. */
  246. const relation = await this.relationMockRepository.findOne({ installation, growiUri: req.growiUri });
  247. if (relation == null) {
  248. logger.error('*No relation found.*');
  249. return;
  250. }
  251. try {
  252. // generate API URL
  253. const url = new URL('/_api/v3/slack-integration/proxied/interactions', req.growiUri);
  254. await axios.post(url.toString(), {
  255. ...body,
  256. }, {
  257. headers: {
  258. 'x-growi-ptog-tokens': relation.tokenPtoG,
  259. },
  260. });
  261. }
  262. catch (err) {
  263. logger.error(err);
  264. }
  265. }
  266. @Post('/events')
  267. async handleEvent(@BodyParams() body:{[key:string]:string} /* , @Res() res: Res */): Promise<void|string> {
  268. // eslint-disable-next-line max-len
  269. // see: https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls__request-url-configuration--verification
  270. if (body.type === 'url_verification') {
  271. return body.challenge;
  272. }
  273. logger.info('receive event', body);
  274. return;
  275. }
  276. @Get('/oauth_redirect')
  277. async handleOauthRedirect(@Req() req: Req, @Res() res: Res): Promise<void> {
  278. if (req.query.state === '') {
  279. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  280. res.end('<html>'
  281. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  282. + '<body style="text-align:center; padding-top:20%;">'
  283. + '<h1>Illegal state, try it again.</h1>'
  284. + '<a href="/">'
  285. + 'Go to install page'
  286. + '</a>'
  287. + '</body></html>');
  288. }
  289. await this.installerService.installer.handleCallback(req, res, {
  290. success: (installation, metadata, req, res) => {
  291. logger.info('Success to install', { installation, metadata });
  292. const appPageUrl = `https://slack.com/apps/${installation.appId}`;
  293. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  294. res.end('<html>'
  295. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  296. + '<body style="text-align:center; padding-top:20%;">'
  297. + '<h1>Congratulations!</h1>'
  298. + '<p>GROWI Bot installation has succeeded.</p>'
  299. + `<a href="${appPageUrl}">`
  300. + 'Access to Slack App detail page.'
  301. + '</a>'
  302. + '</body></html>');
  303. },
  304. failure: (error, installOptions, req, res) => {
  305. res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
  306. res.end('<html>'
  307. + '<head><meta name="viewport" content="width=device-width,initial-scale=1"></head>'
  308. + '<body style="text-align:center; padding-top:20%;">'
  309. + '<h1>GROWI Bot installation failed</h1>'
  310. + '<p>Please contact administrators of your workspace</p>'
  311. + 'Reference: <a href="https://slack.com/help/articles/222386767-Manage-app-installation-settings-for-your-workspace">'
  312. + 'Manage app installation settings for your workspace'
  313. + '</a>'
  314. + '</body></html>');
  315. },
  316. });
  317. }
  318. }