Skip to content

Commit

Permalink
Merge pull request #15 from Leets-Official/13-bug-ec2-oauth-login
Browse files Browse the repository at this point in the history
13 bug ec2 oauth login
  • Loading branch information
yechan-kim authored Jul 21, 2024
2 parents 3342001 + c79641d commit 0dea327
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 6 deletions.
4 changes: 2 additions & 2 deletions appspec.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ os: linux

files:
- source: /
destination: /home/ubuntu/enhance
destination: /home/ubuntu/commitato
permissions:
- object: /home/ubuntu/enhance/
- object: /home/ubuntu/commitato/
owner: ubuntu
group: ubuntu
hooks:
Expand Down
2 changes: 1 addition & 1 deletion scripts/after-deploy.sh
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env bash

REPOSITORY=/home/ubuntu/commitato-BE
REPOSITORY=/home/ubuntu/commitato
cd $REPOSITORY

APP_NAME=commitato-BE
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
package com.leets.commitatobe.domain.commit.presentation;
import com.leets.commitatobe.domain.commit.presentation.dto.response.CommitResponse;
import com.leets.commitatobe.domain.commit.usecase.FetchCommits;
import com.leets.commitatobe.domain.commit.usecase.FetchCommitsTest;
import com.leets.commitatobe.global.response.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;


@Tag(name = "Commit 컨트롤러", description = "GitHub에서 사용자의 Commit 정보를 호출하고 데이터 가공을 처리합니다.")
@RestController
@RequiredArgsConstructor
@RequestMapping("/commit")
public class CommitController {
private final FetchCommits fetchCommits;
private final FetchCommitsTest fetchCommitsTest;

@Operation(
summary = "커밋 기록 불러오기",
Expand All @@ -21,4 +25,12 @@ public class CommitController {
public ApiResponse<CommitResponse> fetchCommits(HttpServletRequest request) {
return ApiResponse.onSuccess(fetchCommits.execute(request));
}

@Operation(
summary = "커밋 기록 불러오기 (테스트)",
description = "commit/fetch가 정상적으로 실행이 될 동안 사용할 임시 API")
@PostMapping("test/fetch")
public ApiResponse<CommitResponse> fetchCommits(HttpServletRequest request, @RequestHeader String accessToken) {
return ApiResponse.onSuccess(fetchCommitsTest.execute(request, accessToken));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ public CommitResponse execute(HttpServletRequest request) {
.orElseThrow(() -> new ApiException(ErrorStatus._COMMIT_NOT_FOUND))
.getUpdatedAt();
} catch (ApiException e) {
dateTime = LocalDateTime.now();
// dateTime = LocalDateTime.of(2024, 07, 01, 0, 0, 0); // test 용
dateTime = user.getCreatedAt().toLocalDate().atStartOfDay();
}

try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.leets.commitatobe.domain.commit.usecase;

import com.leets.commitatobe.domain.commit.domain.Commit;
import com.leets.commitatobe.domain.commit.domain.repository.CommitRepository;
import com.leets.commitatobe.domain.commit.presentation.dto.response.CommitResponse;
import com.leets.commitatobe.domain.login.usecase.LoginQueryService;
import com.leets.commitatobe.domain.user.domain.User;
import com.leets.commitatobe.domain.user.domain.repository.UserRepository;
import com.leets.commitatobe.global.exception.ApiException;
import com.leets.commitatobe.global.response.code.status.ErrorStatus;
import com.leets.commitatobe.global.response.code.status.SuccessStatus;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@RequiredArgsConstructor
public class FetchCommitsTest {
private final CommitRepository commitRepository;
private final UserRepository userRepository;
private final GitHubService gitHubService; // GitHub API 통신
private final LoginQueryService loginQueryService;

public CommitResponse execute(HttpServletRequest request, String accessToken) {
String gitHubId = loginQueryService.getGitHubId(request);
User user = userRepository.findByGithubId(gitHubId)
.orElseThrow(() -> new UsernameNotFoundException("해당하는 깃허브 닉네임과 일치하는 유저를 찾을 수 없음: " + gitHubId));

LocalDateTime dateTime;
try {
dateTime = commitRepository.findAllByUser(user).stream()
.max(Comparator.comparing(Commit::getUpdatedAt))
.orElseThrow(() -> new ApiException(ErrorStatus._COMMIT_NOT_FOUND))
.getUpdatedAt();
} catch (ApiException e) {
dateTime = LocalDateTime.of(2024, 7, 1, 0, 0, 0);
}

try {
// Github API Access Token 저장
gitHubService.updateToken(accessToken);

List<String> repos = gitHubService.fetchRepos(gitHubId);
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<CompletableFuture<Void>> futures = new ArrayList<>();
LocalDateTime finalDateTime = dateTime; // 오류 방지

for (String fullName : repos) {
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
try {
gitHubService.countCommits(fullName, gitHubId, finalDateTime);
} catch (IOException e) {
throw new ApiException(ErrorStatus._GIT_URL_INCORRECT);
}
}, executor);
futures.add(voidCompletableFuture);
}

CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allFutures.join();

executor.shutdown();

saveCommits(user);

} catch (Exception e) {
throw new RuntimeException(e);
}

return new CommitResponse(SuccessStatus._OK.getMessage());
}

private void saveCommits(User user) {
// 날짜별 커밋 수 DB에 저장
for (Map.Entry<LocalDateTime, Integer> entry : gitHubService.getCommitsByDate().entrySet()) {
Commit commit = commitRepository.findByCommitDateAndUser(entry.getKey(), user)
.orElse(Commit.create(entry.getKey(), 0, user));
commit.updateCnt(entry.getValue());
commitRepository.save(commit);
}
}
}
2 changes: 1 addition & 1 deletion src/main/resources/application-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ spring:
client-id: ${CLIENT_ID}
client-secret: ${CLIENT_SECRET}
scope: read:user
redirect-uri: "http://localhost:8080/login/callback"
redirect-uri: ${REDIRECT_URL}

jwt:
secret: ${JWT_SECRET}

0 comments on commit 0dea327

Please sign in to comment.