blob: a5597dfaf7802104108ac72022db2af85d22a037 [file] [log] [blame]
package com.example.myproject.schedule;
import java.util.Arrays;
import java.util.List;
import com.example.myproject.service.TorrentService;
import com.example.myproject.service.UserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.example.myproject.entity.Users;
import com.example.myproject.repository.UserRepository;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor
public class UserLevelSchedule {
private final UserRepository userRepository;
private final UserService userService;
private final TorrentService torrentService;
private final PlatformTransactionManager transactionManager;
// 各级需要的经验
private final List<Integer> EXPERIENCE_ARRAY = Arrays.asList(50, 200, 500, Integer.MAX_VALUE);
@Scheduled(fixedRate = 30000)
public void upgradeUserLevel() {
for (Users user : userRepository.findAll()) {
// check the experience
int level = (int) Math.max(0, Math.min(EXPERIENCE_ARRAY.size() - 1, user.getLevel()));
int targetExperience = EXPERIENCE_ARRAY.get(level -1 );
if (user.getCurrentExperience() < targetExperience) {
// failed to verify
continue;
}
boolean shouldUpgrade = false;
Integer userId = user.getUserId().intValue();
Float userSeedingHours = torrentService.getUserSeedingHours(userId);
Float userShareRate = torrentService.getUserShareRate(userId);
Long userUploadCount = torrentService.getUserUploadCount(userId);
shouldUpgrade = switch (user.getLevel().intValue()) {
case 1 -> // upgrade to cookie
userService.hasConsecutiveLoginDays(user.getUserId());
case 2 -> // upgrade to chocolate
userShareRate >= 0.5 && userUploadCount >= 10 * 1024 * 1024 && userSeedingHours >= 72;
case 3 -> // upgrade to ice-cream
userShareRate >= 0.75 && userUploadCount >= 50 * 1024 * 1024 && userSeedingHours >= 240;
default -> false;
};
if (shouldUpgrade) {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
user.setLevel(user.getLevel() + 1);
userRepository.save(user);
transactionManager.commit(status);
} catch (Exception e) {
transactionManager.rollback(status);
e.printStackTrace();
}
}
}
}
}