blob: a5597dfaf7802104108ac72022db2af85d22a037 [file] [log] [blame]
Jinf50fba62025-06-09 22:47:24 +08001package com.example.myproject.schedule;
2
3import java.util.Arrays;
4import java.util.List;
5
6import com.example.myproject.service.TorrentService;
7import com.example.myproject.service.UserService;
8import org.springframework.scheduling.annotation.Scheduled;
9import org.springframework.stereotype.Component;
10import org.springframework.transaction.PlatformTransactionManager;
11import org.springframework.transaction.TransactionStatus;
12import org.springframework.transaction.support.DefaultTransactionDefinition;
13
14import com.example.myproject.entity.Users;
15import com.example.myproject.repository.UserRepository;
16
17import lombok.RequiredArgsConstructor;
18
19@Component
20@RequiredArgsConstructor
21public class UserLevelSchedule {
22 private final UserRepository userRepository;
23 private final UserService userService;
24 private final TorrentService torrentService;
25 private final PlatformTransactionManager transactionManager;
26 // 各级需要的经验
27 private final List<Integer> EXPERIENCE_ARRAY = Arrays.asList(50, 200, 500, Integer.MAX_VALUE);
28
29 @Scheduled(fixedRate = 30000)
30 public void upgradeUserLevel() {
31 for (Users user : userRepository.findAll()) {
32 // check the experience
33 int level = (int) Math.max(0, Math.min(EXPERIENCE_ARRAY.size() - 1, user.getLevel()));
34 int targetExperience = EXPERIENCE_ARRAY.get(level -1 );
35 if (user.getCurrentExperience() < targetExperience) {
36 // failed to verify
37 continue;
38 }
39 boolean shouldUpgrade = false;
40 Integer userId = user.getUserId().intValue();
41 Float userSeedingHours = torrentService.getUserSeedingHours(userId);
42 Float userShareRate = torrentService.getUserShareRate(userId);
43 Long userUploadCount = torrentService.getUserUploadCount(userId);
44 shouldUpgrade = switch (user.getLevel().intValue()) {
45 case 1 -> // upgrade to cookie
46 userService.hasConsecutiveLoginDays(user.getUserId());
47 case 2 -> // upgrade to chocolate
48 userShareRate >= 0.5 && userUploadCount >= 10 * 1024 * 1024 && userSeedingHours >= 72;
49 case 3 -> // upgrade to ice-cream
50 userShareRate >= 0.75 && userUploadCount >= 50 * 1024 * 1024 && userSeedingHours >= 240;
51 default -> false;
52 };
53 if (shouldUpgrade) {
54 TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
55 try {
56 user.setLevel(user.getLevel() + 1);
57 userRepository.save(user);
58 transactionManager.commit(status);
59 } catch (Exception e) {
60 transactionManager.rollback(status);
61 e.printStackTrace();
62 }
63 }
64 }
65 }
66}