2024-06-24 13:56:01 +01:00
|
|
|
package cc.fascinated.bat.service;
|
|
|
|
|
2024-06-25 11:55:26 +01:00
|
|
|
import cc.fascinated.bat.model.BatUser;
|
2024-06-24 13:56:01 +01:00
|
|
|
import cc.fascinated.bat.repository.UserRepository;
|
2024-06-27 13:00:45 +01:00
|
|
|
import lombok.Getter;
|
2024-06-24 13:56:01 +01:00
|
|
|
import lombok.NonNull;
|
|
|
|
import lombok.extern.log4j.Log4j2;
|
2024-06-27 23:51:40 +01:00
|
|
|
import net.jodah.expiringmap.ExpiringMap;
|
2024-06-24 13:56:01 +01:00
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.context.annotation.DependsOn;
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
2024-06-27 13:00:45 +01:00
|
|
|
import java.util.Map;
|
2024-06-24 13:56:01 +01:00
|
|
|
import java.util.Optional;
|
2024-06-27 23:51:40 +01:00
|
|
|
import java.util.concurrent.TimeUnit;
|
2024-06-24 13:56:01 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @author Fascinated (fascinated7)
|
|
|
|
*/
|
2024-06-28 03:01:21 +01:00
|
|
|
@Service
|
|
|
|
@Log4j2
|
|
|
|
@Getter
|
2024-06-24 13:56:01 +01:00
|
|
|
@DependsOn("discordService")
|
|
|
|
public class UserService {
|
2024-06-27 13:00:45 +01:00
|
|
|
/**
|
|
|
|
* The cached users
|
|
|
|
*/
|
2024-06-27 23:51:40 +01:00
|
|
|
private final Map<String, BatUser> users = ExpiringMap.builder()
|
|
|
|
.expiration(6, TimeUnit.HOURS)
|
|
|
|
.build();
|
2024-06-27 13:00:45 +01:00
|
|
|
|
2024-06-24 13:56:01 +01:00
|
|
|
/**
|
|
|
|
* The user repository to use
|
|
|
|
*/
|
|
|
|
private final UserRepository userRepository;
|
|
|
|
|
|
|
|
@Autowired
|
|
|
|
public UserService(@NonNull UserRepository userRepository) {
|
|
|
|
this.userRepository = userRepository;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets a user by their ID
|
|
|
|
*
|
|
|
|
* @param id The ID of the user
|
|
|
|
* @return The user
|
|
|
|
*/
|
|
|
|
public BatUser getUser(@NonNull String id) {
|
2024-06-27 13:00:45 +01:00
|
|
|
if (users.containsKey(id)) {
|
|
|
|
return users.get(id);
|
|
|
|
}
|
|
|
|
|
2024-06-24 13:56:01 +01:00
|
|
|
long start = System.currentTimeMillis();
|
|
|
|
Optional<BatUser> optionalUser = userRepository.findById(id);
|
|
|
|
if (optionalUser.isPresent()) {
|
2024-06-27 13:00:45 +01:00
|
|
|
BatUser user = optionalUser.get();
|
|
|
|
users.put(id, user);
|
|
|
|
return user;
|
2024-06-24 13:56:01 +01:00
|
|
|
}
|
|
|
|
BatUser user = userRepository.save(new BatUser(id));
|
2024-06-27 17:38:28 +01:00
|
|
|
log.info("Created user for \"{}\" in {}ms", user.getDiscordUser().getName(), System.currentTimeMillis() - start);
|
2024-06-24 13:56:01 +01:00
|
|
|
return user;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Saves a user
|
|
|
|
*
|
|
|
|
* @param user The user to save
|
|
|
|
*/
|
|
|
|
public void saveUser(@NonNull BatUser user) {
|
|
|
|
userRepository.save(user);
|
|
|
|
}
|
|
|
|
}
|