Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] refactoring api call slack api #493

Merged
merged 4 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,36 @@
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gg.server.data.noti.Noti;
import com.gg.server.domain.noti.dto.UserNotiDto;
import com.gg.server.domain.noti.exception.SlackJsonParseException;
import com.gg.server.domain.noti.exception.SlackSendException;
import com.gg.server.domain.noti.exception.SlackUserGetFailedException;
import com.gg.server.domain.noti.service.NotiService;
import com.gg.server.domain.user.dto.UserDto;
import com.gg.server.global.utils.external.ApiUtil;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@RequiredArgsConstructor
public class SlackbotService {
@Value("${slack.xoxbToken}")
private String authenticationToken;

private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
private final NotiService notiService;
private final ApiUtil apiUtil;

public SlackbotService(RestTemplateBuilder builder, ObjectMapper objectMapper, NotiService notiService) {
this.restTemplate = builder.build();
this.objectMapper = objectMapper;
this.notiService = notiService;
}

private String getSlackUserId(String intraId) throws SlackUserGetFailedException {
private String getSlackUserId(String intraId) {
String userEmail = intraId + intraEmailSuffix;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
Expand All @@ -57,40 +44,24 @@ private String getSlackUserId(String intraId) throws SlackUserGetFailedException
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("email", userEmail);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(parameters, headers);

ResponseEntity<SlackUserInfoResponse> responseEntity = restTemplate
.exchange(userIdGetUrl, HttpMethod.POST, request, SlackUserInfoResponse.class);
if (!responseEntity.getBody().ok) {
throw new SlackUserGetFailedException();
}
return responseEntity.getBody().user.id;
SlackUserInfoResponse res = apiUtil.apiCall(userIdGetUrl, SlackUserInfoResponse.class,
headers, parameters, HttpMethod.POST);
return res.user.id;
}

private String getDmChannelId(String slackUserId) throws SlackJsonParseException {
private String getDmChannelId(String slackUserId) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION,
authenticationPrefix + authenticationToken);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);

Map<String, String> map = new HashMap<>();
map.put("users", slackUserId);
String contentBody = null;
try {
contentBody = objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
throw new SlackJsonParseException();
}
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("users", slackUserId);

HttpEntity<String> entity = new HttpEntity<>(contentBody, httpHeaders);
ConversationResponse res = apiUtil.apiCall(conversationsUrl, ConversationResponse.class,
httpHeaders, bodyMap, HttpMethod.POST);

ResponseEntity<ConversationResponse> responseEntity = restTemplate
.exchange(conversationsUrl, HttpMethod.POST, entity, ConversationResponse.class);
if (!responseEntity.getBody().ok) {
log.error("fail to get user dm channel id");
throw new SlackUserGetFailedException();
}
return responseEntity.getBody().channel.id;
return res.channel.id;
}

@Async("asyncExecutor")
Expand All @@ -113,7 +84,7 @@ public void send(UserDto user, Noti noti) {
}
}

private void startSendNoti(String intraId, Noti noti) throws SlackSendException {
private void startSendNoti(String intraId, Noti noti) {
String slackUserId = getSlackUserId(intraId);
String slackChannelId = getDmChannelId(slackUserId);
String message = notiService.getMessage(noti);
Expand All @@ -126,21 +97,7 @@ private void startSendNoti(String intraId, Noti noti) throws SlackSendException
Map<String, String> map = new HashMap<>();
map.put("channel", slackChannelId);
map.put("text", message);
String contentBody = null;
try {
contentBody = objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
log.error("start send Slack Noti", e);
throw new SlackJsonParseException();
}

HttpEntity<String> entity = new HttpEntity<>(contentBody, httpHeaders);

ResponseEntity<String> respEntity = restTemplate
.exchange(sendMessageUrl, HttpMethod.POST, entity, String.class);
if (respEntity.getStatusCode() != HttpStatus.OK) {
throw new SlackSendException();
}
apiUtil.apiCall(sendMessageUrl, String.class, httpHeaders, map, HttpMethod.POST);
}

@Getter
Expand Down
52 changes: 52 additions & 0 deletions src/main/java/com/gg/server/global/utils/external/ApiUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.gg.server.global.utils.external;

import java.util.Map;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class ApiUtil {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;

public ApiUtil(ObjectMapper objectMapper, RestTemplateBuilder restTemplateBuilder) {
this.objectMapper = objectMapper;
this.restTemplate = restTemplateBuilder.build();
}

public <T> T apiCall(String url, Class<T> responseType, HttpHeaders headers,
MultiValueMap<String, String> parameters, HttpMethod method) {
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(parameters, headers);
ResponseEntity<T> res = restTemplate.exchange(url, method, request, responseType);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("api call error");
}
return res.getBody();
}

public <T> T apiCall(String url, Class<T> responseType, HttpHeaders headers,
Map<String, String> bodyJson, HttpMethod method) {
String contentBody = null;
try {
contentBody = objectMapper.writeValueAsString(bodyJson);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
HttpEntity<String> request = new HttpEntity<>(contentBody, headers);
ResponseEntity<T> res = restTemplate.exchange(url, method, request, responseType);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("api call error");
}
return res.getBody();
}
}
Loading