Skip to content

Commit b3f8ea9

Browse files
committed
Merge branch 'dev' of https://github.com/CommitField/commitField into Feature/89
2 parents 05bbf6b + 6025330 commit b3f8ea9

File tree

11 files changed

+185
-46
lines changed

11 files changed

+185
-46
lines changed

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

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

1212
import java.time.LocalDateTime;
13+
import java.time.format.DateTimeFormatter;
14+
import java.time.format.DateTimeParseException;
1315
import java.util.Set;
1416
import java.util.concurrent.TimeUnit;
1517
import java.util.concurrent.atomic.AtomicInteger;
@@ -34,56 +36,69 @@ public void updateUserCommits() {
3436
Set<String> activeUsers = redisTemplate.keys("commit_active:*");
3537
log.info("🔍 Active User Count: {}", activeUsers.size());
3638

39+
// 현재 접속 기록이 있는 유저, 커밋 기록이 있는 유저는 주기적으로 갱신
3740
for (String key : activeUsers) {
3841
String username = key.replace("commit_active:", "");
39-
User user = userRepository.findByUsername(username).orElse(null);
40-
if (user != null) {
41-
processUserCommit(user);
42-
}
43-
}
4442

43+
String lastcmKey = "commit_lastCommitted:" + username; // active유저의 key
44+
String lastCommitted = redisTemplate.opsForValue().get(lastcmKey); // 마지막 커밋 시간
45+
46+
System.out.println("username: "+username);
47+
System.out.println("user lastCommitted: "+lastCommitted);
48+
if(username!=null && lastCommitted!=null) processUserCommit(username);
49+
}
4550
}
4651

4752
// 🔹 유저 커밋 검사 및 반영
48-
private void processUserCommit(User user) {
49-
// Redis에서 lastCommitted 값 가져오기
50-
String redisKey = "commit_last:" + user.getUsername();
51-
String lastCommittedStr = redisTemplate.opsForValue().get(redisKey);
52-
LocalDateTime lastCommitted;
53-
if(lastCommittedStr != null){
54-
lastCommitted=LocalDateTime.parse(lastCommittedStr);
55-
}else{
56-
user.setLastCommitted(LocalDateTime.now()); // 레디스에 저장되어있지 않았다면 등록 시점에 lastCommitted를 갱신
57-
lastCommitted=user.getLastCommitted(); // Redis에 없으면 DB값 사용;
53+
private void processUserCommit(String username) {
54+
// 유저가 접속한 동안 추가한 commit수를 확인.
55+
String key = "commit_active:" + username; // active유저의 key
56+
String lastcmKey = "commit_lastCommitted:" + username; // active유저의 key
57+
String currentCommit = redisTemplate.opsForValue().get(key); // 현재까지 확인한 커밋 개수
58+
String lastcommitted = redisTemplate.opsForValue().get(lastcmKey); // 마지막 커밋 시간
59+
long updateTotalCommit, newCommitCount;
60+
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);
5868
}
5969

6070
// 현재 커밋 개수 조회
61-
long currentCommitCount = totalCommitService.getUpdateCommits(
62-
user.getUsername(),
63-
lastCommitted, // 🚀 Redis에 저장된 lastCommitted 기준으로 조회
64-
LocalDateTime.now()
65-
).getTotalCommitContributions();
66-
67-
// Redis에서 이전 커밋 개수 가져오기
68-
Integer previousCommitCount = commitCacheService.getCachedCommitCount(user.getUsername());
69-
long newCommitCount = previousCommitCount == null ? 0 : (currentCommitCount - previousCommitCount);
70-
71-
if (newCommitCount > 0) {
72-
updateCommitData(user, currentCommitCount, newCommitCount);
73-
}
71+
updateTotalCommit = totalCommitService.getUpdateCommits(
72+
username,
73+
lastCommittedTime, // 🚀 Redis에 저장된 lastCommitted 기준으로 조회
74+
LocalDateTime.now()
75+
).getCommits();
76+
System.out.println("커밋 개수 불러들이기 완료, 현재까지 업데이트 된 커밋 수 : "+updateTotalCommit);
7477

75-
log.info("🔍 User: {}, New Commits: {}, Total Commits: {}", user.getUsername(), newCommitCount, currentCommitCount);
76-
}
78+
if(currentCommit.equals("0") && updateTotalCommit > 0){
79+
User user = userRepository.findByUsername(username).get();
80+
LocalDateTime now = LocalDateTime.now();
81+
//이번 기간에 처음으로 커밋 수가 갱신된 경우, 이 시간을 기점으로 commitCount를 계산한다.
82+
user.setLastCommitted(now);
83+
userRepository.save(user);
84+
85+
String redisKey = "commit_update:" + username; // 변경 알림을 위한 변수
86+
redisTemplate.opsForValue().set(redisKey, String.valueOf(updateTotalCommit), 3, TimeUnit.HOURS);
7787

78-
// 🔹 새 커밋이 있으면 데이터 업데이트
79-
private void updateCommitData(User user, long currentCommitCount, long newCommitCount) {
80-
// 1️⃣ Redis에 lastCommitted 업데이트 (3시간 TTL)
81-
String redisKey = "commit_last:" + user.getUsername();
82-
redisTemplate.opsForValue().set(redisKey, LocalDateTime.now().toString(), 3, TimeUnit.HOURS);
88+
redisTemplate.opsForValue().set(lastcmKey, String.valueOf(now), 3, TimeUnit.HOURS);
89+
}
8390

84-
// 2️⃣ Redis에 최신 커밋 개수 저장 (3시간 동안 유지)
85-
commitCacheService.updateCachedCommitCount(user.getUsername(), currentCommitCount);
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);
96+
97+
updateTotalCommit+=newCommitCount;
98+
redisTemplate.opsForValue().set(key, String.valueOf(updateTotalCommit), 3, TimeUnit.HOURS);
99+
}
86100

87-
log.info("✅ 커밋 반영 완료 - User: {}, New Commits: {}", user.getUsername(), newCommitCount);
101+
// FIXME: 차후 리팩토링 필요
102+
log.info("🔍 User: {}, LastCommitted: {}, New Commits: {}, Total Commits: {}", username, lastcommitted, newCommitCount, currentCommit);
88103
}
89104
}

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ public UserInfoDto updateUserTier(String username){
2929
userRepository.save(user);
3030

3131
return UserInfoDto.builder()
32-
.userId(user.getId())
3332
.username(user.getUsername())
3433
.email(user.getEmail())
3534
.avatarUrl(user.getAvatarUrl())
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package cmf.commitField.domain.commit.totalCommit.dto;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Builder;
5+
import lombok.Getter;
6+
7+
@Getter
8+
@Builder
9+
@AllArgsConstructor
10+
public class CommitUpdateDTO {
11+
long commits;
12+
}

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

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

3+
import cmf.commitField.domain.commit.totalCommit.dto.CommitUpdateDTO;
34
import cmf.commitField.domain.commit.totalCommit.dto.TotalCommitGraphQLResponse;
45
import cmf.commitField.domain.commit.totalCommit.dto.TotalCommitResponseDto;
56
import lombok.RequiredArgsConstructor;
@@ -215,15 +216,15 @@ private StreakResult calculateStreaks(List<LocalDate> commitDates) {
215216
}
216217

217218
// 시간별 커밋 분석
218-
public TotalCommitResponseDto getUpdateCommits(String username, LocalDateTime since, LocalDateTime until) {
219+
public CommitUpdateDTO getUpdateCommits(String username, LocalDateTime since, LocalDateTime until) {
219220
String query = String.format("""
220221
query {
221222
user(login: "%s") {
222223
contributionsCollection(from: "%s", to: "%s") {
223224
commitContributionsByRepository {
224225
contributions(first: 100) {
225226
nodes {
226-
occurredAt # 시간 정보 포함
227+
occurredAt # 시간 정보 포함
227228
}
228229
}
229230
}
@@ -244,12 +245,13 @@ public TotalCommitResponseDto getUpdateCommits(String username, LocalDateTime si
244245
throw new RuntimeException("Failed to fetch GitHub data");
245246
}
246247

248+
249+
System.out.println("메소드 작동 확인 : "+response.getData().getUser());
247250
TotalCommitGraphQLResponse.ContributionsCollection contributions =
248251
response.getData().getUser().getContributionsCollection();
249252

250-
return new TotalCommitResponseDto(
251-
contributions.getTotalCommitContributions(),
252-
contributions.getRestrictedContributionsCount()
253+
return new CommitUpdateDTO(
254+
contributions.getTotalCommitContributions()
253255
);
254256
}
255257
}

src/main/java/cmf/commitField/domain/pet/repository/PetRepository.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@
1111
public interface PetRepository extends JpaRepository<Pet, Long> {
1212
Optional<Pet> findById(Long id);
1313
List<Pet> findByUserEmail(String email);
14+
List<Pet> findByUserUsername(String username);
1415
}

src/main/java/cmf/commitField/domain/user/controller/AuthController.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public class AuthController {
1515
@GetMapping("/login")
1616
public ResponseEntity<?> user() {
1717
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
18-
18+
System.out.println("/login 호출");
1919
if (authentication instanceof OAuth2AuthenticationToken) {
2020
OAuth2User principal = (OAuth2User) authentication.getPrincipal();
2121
return ResponseEntity.ok(principal.getAttributes()); // 사용자 정보 반환
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package cmf.commitField.domain.user.controller;
2+
3+
import cmf.commitField.domain.commit.totalCommit.service.TotalCommitService;
4+
import cmf.commitField.domain.user.dto.UserInfoDto;
5+
import cmf.commitField.domain.user.entity.CustomOAuth2User;
6+
import cmf.commitField.domain.user.service.UserService;
7+
import lombok.RequiredArgsConstructor;
8+
import org.springframework.http.ResponseEntity;
9+
import org.springframework.security.core.annotation.AuthenticationPrincipal;
10+
import org.springframework.web.bind.annotation.GetMapping;
11+
import org.springframework.web.bind.annotation.RequestMapping;
12+
import org.springframework.web.bind.annotation.RestController;
13+
14+
@RestController
15+
@RequestMapping("/api/user")
16+
@RequiredArgsConstructor
17+
public class UserController {
18+
private final UserService userService;
19+
private final TotalCommitService totalCommitService;
20+
21+
@GetMapping("info")
22+
public ResponseEntity<UserInfoDto> getUserInfo(@AuthenticationPrincipal CustomOAuth2User oAuth2User){
23+
String username = oAuth2User.getName();
24+
25+
//유저 정보의 조회
26+
//이 이벤트가 일어나면 유저의 정보를 확인하고, 조회한 유저를 active 상태로 만든다.
27+
UserInfoDto userInfoDto = userService.showUserInfo(username);
28+
29+
return ResponseEntity.ok(userInfoDto);
30+
}
31+
}

src/main/java/cmf/commitField/domain/user/dto/UserInfoDto.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,16 @@
99
@Getter
1010
public class UserInfoDto {
1111

12-
private Long userId;
1312
private String username;
1413
private String email;
1514
private String avatarUrl;
1615
private LocalDateTime createdAt;
1716
private LocalDateTime lastCommitted;
1817
private long commitCount;
18+
19+
private int petType;
20+
private int petExp;
21+
private String petGrow;
1922
private String tier;
2023

2124
// 펫 생략, 차후 필요시 추가
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,68 @@
11
package cmf.commitField.domain.user.service;
22

3+
import cmf.commitField.domain.commit.scheduler.CommitUpdateService;
4+
import cmf.commitField.domain.commit.totalCommit.service.TotalCommitService;
5+
import cmf.commitField.domain.pet.entity.Pet;
6+
import cmf.commitField.domain.pet.repository.PetRepository;
7+
import cmf.commitField.domain.pet.service.PetService;
8+
import cmf.commitField.domain.user.dto.UserInfoDto;
9+
import cmf.commitField.domain.user.entity.User;
310
import cmf.commitField.domain.user.repository.UserRepository;
411
import lombok.RequiredArgsConstructor;
12+
import org.springframework.data.redis.core.StringRedisTemplate;
513
import org.springframework.stereotype.Service;
614
import org.springframework.transaction.annotation.Transactional;
715

16+
import java.time.LocalDateTime;
17+
import java.util.concurrent.TimeUnit;
18+
819
@Service
920
@RequiredArgsConstructor
1021
public class UserService {
22+
private final StringRedisTemplate redisTemplate;
1123
private final UserRepository userRepository;
24+
private final PetRepository petRepository;
25+
// FIXME: 수정 필요
26+
private final TotalCommitService totalCommitService;
27+
private final CommitUpdateService commitUpdateService;
28+
private final PetService petService;
1229

1330
@Transactional
1431
public void updateUserStatus(String username, boolean status) {
1532
System.out.println("Updating status for " + username + " to " + status);
1633
userRepository.updateStatus(username, status);
1734
}
35+
36+
@Transactional
37+
public UserInfoDto showUserInfo(String username) {
38+
User user = userRepository.findByUsername(username).get();
39+
Pet pet = petRepository.findByUserEmail(user.getEmail()).get(0); // TODO: 확장시 코드 수정 필요
40+
41+
// 유저 정보 조회 후 변경사항은 업데이트
42+
// TODO: 스케쥴러 수정 후 펫 부분 수정 필요
43+
commitUpdateService.updateUserTier(user.getUsername());
44+
petService.getExpPet(user.getUsername(), 0);
45+
46+
long commit = totalCommitService.getUpdateCommits(username, user.getLastCommitted(), LocalDateTime.now()).getCommits();
47+
System.out.println("커밋수 테스트 : "+commit);
48+
49+
String key = "commit_active:" + user.getUsername();
50+
if(redisTemplate.opsForValue().get(key)==null){
51+
redisTemplate.opsForValue().set(key, String.valueOf(0), 3, TimeUnit.HOURS);
52+
redisTemplate.opsForValue().set("commit_lastCommitted:" + username, LocalDateTime.now().toString(),3, TimeUnit.HOURS);
53+
}
54+
55+
return UserInfoDto.builder()
56+
.username(user.getUsername())
57+
.email(user.getEmail())
58+
.avatarUrl(user.getAvatarUrl())
59+
.tier(user.getTier().toString())
60+
.commitCount(user.getCommitCount())
61+
.createdAt(user.getCreatedAt())
62+
.lastCommitted(user.getLastCommitted())
63+
.petType(pet.getType())
64+
.petExp(pet.getExp())
65+
.petGrow(pet.getGrow().toString())
66+
.build();
67+
}
1868
}

src/main/java/cmf/commitField/global/config/RedisConfig.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,5 @@ public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConne
4242
template.setConnectionFactory(redisConnectionFactory);
4343
return template;
4444
}
45+
4546
}

0 commit comments

Comments
 (0)