UnregisterService.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Inject, Service } from '@tsed/di';
  2. import { WebClient, LogLevel } from '@slack/web-api';
  3. import { GrowiCommand, markdownSectionBlock } from '@growi/slack';
  4. import { AuthorizeResult } from '@slack/oauth';
  5. import { GrowiCommandProcessor } from '~/interfaces/slack-to-growi/growi-command-processor';
  6. import { RelationRepository } from '~/repositories/relation';
  7. import { Installation } from '~/entities/installation';
  8. const isProduction = process.env.NODE_ENV === 'production';
  9. @Service()
  10. export class UnregisterService implements GrowiCommandProcessor {
  11. @Inject()
  12. relationRepository: RelationRepository;
  13. async process(growiCommand: GrowiCommand, authorizeResult: AuthorizeResult, body: {[key:string]:string}): Promise<void> {
  14. const { botToken } = authorizeResult;
  15. const client = new WebClient(botToken, { logLevel: isProduction ? LogLevel.DEBUG : LogLevel.INFO });
  16. const growiUrls = growiCommand.growiCommandArgs;
  17. await client.views.open({
  18. trigger_id: body.trigger_id,
  19. view: {
  20. type: 'modal',
  21. callback_id: 'unregister',
  22. title: {
  23. type: 'plain_text',
  24. text: 'Unregister Credentials',
  25. },
  26. submit: {
  27. type: 'plain_text',
  28. text: 'Submit',
  29. },
  30. close: {
  31. type: 'plain_text',
  32. text: 'Close',
  33. },
  34. private_metadata: JSON.stringify({ channel: body.channel_name, growiUrls }),
  35. blocks: [
  36. ...growiUrls.map(growiCommandArg => markdownSectionBlock(`GROWI url: ${growiCommandArg}.`)),
  37. ],
  38. },
  39. });
  40. }
  41. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  42. async unregister(installation: Installation | undefined, authorizeResult: AuthorizeResult, payload: any):Promise<void> {
  43. const { botToken } = authorizeResult;
  44. const { channel, growiUrls } = JSON.parse(payload.view.private_metadata);
  45. const client = new WebClient(botToken, { logLevel: isProduction ? LogLevel.DEBUG : LogLevel.INFO });
  46. const deleteResult = await this.relationRepository.createQueryBuilder('relation')
  47. .where('relation.growiUri IN (:uris)', { uris: growiUrls })
  48. .andWhere('relation.installationId = :installationId', { installationId: installation?.id })
  49. .delete()
  50. .execute();
  51. await client.chat.postEphemeral({
  52. channel,
  53. user: payload.user.id,
  54. // Recommended including 'text' to provide a fallback when using blocks
  55. // refer to https://api.slack.com/methods/chat.postEphemeral#text_usage
  56. text: 'Delete Relations',
  57. blocks: [
  58. markdownSectionBlock(`Deleted ${deleteResult.affected} Relations.`),
  59. ],
  60. });
  61. return;
  62. }
  63. }