Skip to content

Commit 27276a0

Browse files
committed
feat: 새 커밋 수 반영되게 수정
1 parent b589f0c commit 27276a0

File tree

5 files changed

+76
-56
lines changed

5 files changed

+76
-56
lines changed

src/main/java/cmf/commitField/domain/commit/scheduler/CommitScheduler.java

Lines changed: 13 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@
1010
import org.springframework.stereotype.Service;
1111

1212
import java.time.LocalDateTime;
13-
import java.time.format.DateTimeFormatter;
14-
import java.time.format.DateTimeParseException;
1513
import java.util.Set;
1614
import java.util.concurrent.TimeUnit;
1715
import java.util.concurrent.atomic.AtomicInteger;
@@ -52,53 +50,35 @@ public void updateUserCommits() {
5250
// 🔹 유저 커밋 검사 및 반영
5351
private void processUserCommit(String username) {
5452
// 유저가 접속한 동안 추가한 commit수를 확인.
55-
String key = "commit_active:" + username; // active유저의 key
53+
String activeKey = "commit_active:" + username; // active유저의 key
5654
String lastcmKey = "commit_lastCommitted:" + username; // active유저의 key
57-
String currentCommit = redisTemplate.opsForValue().get(key); // 현재까지 확인한 커밋 개수
55+
Long currentCommit = Long.parseLong(redisTemplate.opsForValue().get(activeKey)); // 현재까지 확인한 커밋 개수
5856
String lastcommitted = redisTemplate.opsForValue().get(lastcmKey); // 마지막 커밋 시간
5957
long updateTotalCommit, newCommitCount;
6058

61-
62-
LocalDateTime lastCommittedTime;
63-
try {
64-
lastCommittedTime = LocalDateTime.parse(lastcommitted, DateTimeFormatter.ISO_DATE_TIME);
65-
} catch (DateTimeParseException e) {
66-
System.out.println("lastcommitted 값이 올바르지 않음: " + lastcommitted);
67-
lastCommittedTime = LocalDateTime.now().minusHours(1);
68-
}
69-
7059
// 현재 커밋 개수 조회
71-
updateTotalCommit = totalCommitService.getUpdateCommits(
72-
username,
73-
lastCommittedTime, // 🚀 Redis에 저장된 lastCommitted 기준으로 조회
74-
LocalDateTime.now()
75-
).getCommits();
76-
System.out.println("커밋 개수 불러들이기 완료, 현재까지 업데이트 된 커밋 수 : "+updateTotalCommit);
60+
updateTotalCommit = totalCommitService.getTotalCommitCount(
61+
username
62+
).getTotalCommitContributions();
63+
64+
newCommitCount = updateTotalCommit - currentCommit; // 새로 추가된 커밋 수
65+
System.out.println("커밋 개수 불러들이기 완료, currentCommit : "+currentCommit);
66+
System.out.println("커밋 개수 불러들이기 완료, updateTCommit : "+updateTotalCommit);
7767

78-
if(currentCommit.equals("0") && updateTotalCommit > 0){
68+
if(newCommitCount > 0){
7969
User user = userRepository.findByUsername(username).get();
8070
LocalDateTime now = LocalDateTime.now();
81-
//이번 기간에 처음으로 커밋 수가 갱신된 경우, 이 시간을 기점으로 commitCount를 계산한다.
71+
//커밋 수가 갱신된 경우, 이 시간을 기점으로 lastCommitted를 변경한다.
8272
user.setLastCommitted(now);
8373
userRepository.save(user);
8474

8575
String redisKey = "commit_update:" + username; // 변경 알림을 위한 변수
86-
redisTemplate.opsForValue().set(redisKey, String.valueOf(updateTotalCommit), 3, TimeUnit.HOURS);
87-
76+
redisTemplate.opsForValue().set(activeKey, String.valueOf(updateTotalCommit), 3, TimeUnit.HOURS);
8877
redisTemplate.opsForValue().set(lastcmKey, String.valueOf(now), 3, TimeUnit.HOURS);
89-
}
90-
91-
//기존 커밋이 있고 커밋 수에 변화가 있는 경우 처리
92-
newCommitCount = updateTotalCommit - Long.parseLong(currentCommit); // 새로 추가된 커밋 수
93-
if(newCommitCount>0){
94-
String redisKey = "commit_update:" + username; // 변경 알림을 위한 변수
95-
redisTemplate.opsForValue().set(redisKey, String.valueOf(newCommitCount), 3, TimeUnit.HOURS);
9678

97-
updateTotalCommit+=newCommitCount;
98-
redisTemplate.opsForValue().set(key, String.valueOf(updateTotalCommit), 3, TimeUnit.HOURS);
9979
}
10080

10181
// FIXME: 차후 리팩토링 필요
102-
log.info("🔍 User: {}, LastCommitted: {}, New Commits: {}, Total Commits: {}", username, lastcommitted, newCommitCount, currentCommit);
82+
log.info("🔍 User: {}, LastCommitted: {}, New Commits: {}, Total Commits: {}", username, lastcommitted, newCommitCount, updateTotalCommit);
10383
}
10484
}

src/main/java/cmf/commitField/domain/commit/totalCommit/service/TotalCommitService.java

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package cmf.commitField.domain.commit.totalCommit.service;
22

3-
import cmf.commitField.domain.commit.totalCommit.dto.CommitUpdateDTO;
43
import cmf.commitField.domain.commit.totalCommit.dto.TotalCommitGraphQLResponse;
54
import cmf.commitField.domain.commit.totalCommit.dto.TotalCommitResponseDto;
65
import lombok.RequiredArgsConstructor;
@@ -216,24 +215,25 @@ private StreakResult calculateStreaks(List<LocalDate> commitDates) {
216215
}
217216

218217
// 시간별 커밋 분석
219-
public CommitUpdateDTO getUpdateCommits(String username, LocalDateTime since, LocalDateTime until) {
218+
public long getUpdateCommits(String username, LocalDateTime since, LocalDateTime until) {
220219
String query = String.format("""
221220
query {
222221
user(login: "%s") {
223222
contributionsCollection(from: "%s", to: "%s") {
224223
commitContributionsByRepository {
225224
contributions(first: 100) {
226225
nodes {
227-
occurredAt # 시간 정보 포함
226+
occurredAt
228227
}
229228
}
230229
}
231230
}
232231
}
233-
}""", username, since.format(DateTimeFormatter.ISO_DATE_TIME), until.format(DateTimeFormatter.ISO_DATE_TIME));
232+
}
233+
""", username, since.format(DateTimeFormatter.ISO_DATE_TIME), until.format(DateTimeFormatter.ISO_DATE_TIME));
234234

235235
Map<String, String> requestBody = Map.of("query", query);
236-
236+
System.out.println(username);
237237
TotalCommitGraphQLResponse response = webClient.post()
238238
.header("Authorization", "bearer " + PAT)
239239
.bodyValue(requestBody)
@@ -244,14 +244,52 @@ public CommitUpdateDTO getUpdateCommits(String username, LocalDateTime since, Lo
244244
if (response == null || response.getData() == null || response.getData().getUser() == null) {
245245
throw new RuntimeException("Failed to fetch GitHub data");
246246
}
247+
System.out.println(response);
247248

248-
249-
System.out.println("메소드 작동 확인 : "+response.getData().getUser());
250249
TotalCommitGraphQLResponse.ContributionsCollection contributions =
251250
response.getData().getUser().getContributionsCollection();
251+
// 커밋 발생 시간 리스트 추출
252+
List<LocalDateTime> commitTimes = extractCommitTimes(contributions.getContributionCalendar());
252253

253-
return new CommitUpdateDTO(
254-
contributions.getTotalCommitContributions()
255-
);
254+
// 초 단위로 커밋 수 계산
255+
long commitCount = calculateCommitsInTimeRange(commitTimes, since, until);
256+
257+
return commitCount;
258+
}
259+
260+
// 커밋 발생 시간을 LocalDateTime 형식으로 추출하는 메서드
261+
private List<LocalDateTime> extractCommitTimes(TotalCommitGraphQLResponse.ContributionCalendar contributionCalendar) {
262+
List<LocalDateTime> commitTimes = new ArrayList<>();
263+
264+
if (contributionCalendar == null) {
265+
System.out.println("contributionCalendar is null");
266+
return commitTimes; // 빈 리스트 반환
267+
}
268+
269+
// contributionCalendar에서 각 주 단위로 데이터 추출
270+
contributionCalendar.getWeeks().forEach(week -> {
271+
week.getContributionDays().forEach(contributionDay -> {
272+
if (contributionDay.getContributionCount() > 0) {
273+
// 각 날짜에 커밋이 있는 경우 그 날짜를 커밋 시간으로 추가
274+
LocalDate commitDate = LocalDate.parse(contributionDay.getDate());
275+
// LocalDate를 LocalDateTime으로 변환 (시간은 00:00:00로 설정)
276+
LocalDateTime commitTime = commitDate.atStartOfDay();
277+
commitTimes.add(commitTime);
278+
}
279+
});
280+
});
281+
282+
return commitTimes;
256283
}
284+
285+
286+
287+
// 커밋 시간 리스트에서 since와 until 사이에 발생한 커밋 수 계산
288+
private long calculateCommitsInTimeRange(List<LocalDateTime> commitTimes, LocalDateTime since, LocalDateTime until) {
289+
return commitTimes.stream()
290+
.filter(commitTime -> !commitTime.isBefore(since) && !commitTime.isAfter(until))
291+
.count();
292+
}
293+
294+
257295
}

src/main/java/cmf/commitField/domain/user/service/CustomOAuth2UserService.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.util.ArrayList;
2525
import java.util.Map;
2626
import java.util.Optional;
27+
import java.util.concurrent.TimeUnit;
2728

2829
@Service
2930
@RequiredArgsConstructor
@@ -115,4 +116,12 @@ public Optional<User> getUserById(Long userId) {
115116
public Optional<User> getUserByEmail(String email) {
116117
return userRepository.findByEmail(email);
117118
}
119+
120+
public void setUserActive(String username) {
121+
String count = String.valueOf(userRepository.findByUsername(username).get().getCommitCount());
122+
System.out.println("setUserActive currentCommit:"+ count);
123+
redisTemplate.opsForValue().set("commit_active:" + username, count);
124+
redisTemplate.opsForValue().set("commit_lastCommitted:" + username, LocalDateTime.now().toString(),3, TimeUnit.HOURS);
125+
126+
}
118127
}

src/main/java/cmf/commitField/domain/user/service/UserService.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,16 @@ public UserInfoDto showUserInfo(String username) {
3838
User user = userRepository.findByUsername(username).get();
3939
Pet pet = petRepository.findByUserEmail(user.getEmail()).get(0); // TODO: 확장시 코드 수정 필요
4040

41+
long totalCommit = totalCommitService.getTotalCommitCount(username).getTotalCommitContributions();
4142
// 유저 정보 조회 후 변경사항은 업데이트
4243
// TODO: 스케쥴러 수정 후 펫 부분 수정 필요
44+
user.setCommitCount(totalCommit);
4345
commitUpdateService.updateUserTier(user.getUsername());
4446
petService.getExpPet(user.getUsername(), 0);
4547

46-
long commit = totalCommitService.getUpdateCommits(username, user.getLastCommitted(), LocalDateTime.now()).getCommits();
47-
System.out.println("커밋수 테스트 : "+commit);
48-
4948
String key = "commit_active:" + user.getUsername();
5049
if(redisTemplate.opsForValue().get(key)==null){
51-
redisTemplate.opsForValue().set(key, String.valueOf(0), 3, TimeUnit.HOURS);
50+
redisTemplate.opsForValue().set(key, String.valueOf(user.getCommitCount()), 3, TimeUnit.HOURS);
5251
redisTemplate.opsForValue().set("commit_lastCommitted:" + username, LocalDateTime.now().toString(),3, TimeUnit.HOURS);
5352
}
5453

@@ -57,7 +56,7 @@ public UserInfoDto showUserInfo(String username) {
5756
.email(user.getEmail())
5857
.avatarUrl(user.getAvatarUrl())
5958
.tier(user.getTier().toString())
60-
.commitCount(user.getCommitCount())
59+
.commitCount(totalCommit)
6160
.createdAt(user.getCreatedAt())
6261
.lastCommitted(user.getLastCommitted())
6362
.petType(pet.getType())

src/main/java/cmf/commitField/global/security/SecurityConfig.java

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@
1818
import org.springframework.web.cors.CorsConfigurationSource;
1919
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
2020

21-
import java.time.LocalDateTime;
2221
import java.util.List;
23-
import java.util.concurrent.TimeUnit;
2422

2523
@Configuration
2624
@EnableWebSecurity
@@ -57,7 +55,7 @@ protected SecurityFilterChain config(HttpSecurity http) throws Exception {
5755
String username = principal.getAttribute("login");
5856

5957
// Redis에 유저 활성화 정보 저장
60-
setUserActive(username);
58+
customOAuth2UserService.setUserActive(username);
6159

6260
// 디버깅 로그
6361
System.out.println("OAuth2 로그인 성공: " + username);
@@ -75,6 +73,7 @@ protected SecurityFilterChain config(HttpSecurity http) throws Exception {
7573
String username = principal.getAttribute("login");
7674

7775
redisTemplate.delete("commit_active:" + username); // Redis에서 삭제
76+
redisTemplate.delete("commit_lastCommitted:" + username); // Redis에서 삭제
7877

7978
System.out.println("로그아웃 성공");
8079
response.setStatus(HttpServletResponse.SC_OK);
@@ -100,11 +99,6 @@ public CorsConfigurationSource corsConfigurationSource() {
10099
return source;
101100
}
102101

103-
public void setUserActive(String username) {
104-
redisTemplate.opsForValue().set("commit_active:" + username, "0");
105-
redisTemplate.opsForValue().set("commit_lastCommitted:" + username, LocalDateTime.now().toString(),3, TimeUnit.HOURS);
106-
}
107-
108102
public void removeUserActive(String username) {
109103
redisTemplate.delete("commit_active:" + username);
110104
}

0 commit comments

Comments
 (0)