Liam
a001f2dd4c
All checks were successful
Deploy to Dokku / docker (ubuntu-latest) (push) Successful in 38s
85 lines
2.6 KiB
Java
85 lines
2.6 KiB
Java
package cc.fascinated.bat.service;
|
|
|
|
import cc.fascinated.bat.common.TimerUtils;
|
|
import cc.fascinated.bat.event.EventListener;
|
|
import cc.fascinated.bat.model.BatUser;
|
|
import com.mongodb.client.model.Filters;
|
|
import lombok.Getter;
|
|
import lombok.NonNull;
|
|
import lombok.extern.log4j.Log4j2;
|
|
import org.bson.Document;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.context.annotation.DependsOn;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
/**
|
|
* @author Fascinated (fascinated7)
|
|
*/
|
|
@Service
|
|
@Log4j2(topic = "User Service")
|
|
@Getter
|
|
@DependsOn({"discordService", "mongoService"})
|
|
public class UserService implements EventListener {
|
|
private static final long SAVE_INTERVAL = TimeUnit.MINUTES.toMillis(5);
|
|
|
|
/**
|
|
* The cached users
|
|
*/
|
|
private final Map<String, BatUser> users = new HashMap<>();
|
|
|
|
@Autowired
|
|
public UserService() {
|
|
TimerUtils.scheduleRepeating(() -> {
|
|
long before = System.currentTimeMillis();
|
|
for (BatUser user : users.values()) {
|
|
user.save();
|
|
}
|
|
log.info("Saved {} users in {}ms", users.size(), System.currentTimeMillis() - before);
|
|
}, SAVE_INTERVAL, SAVE_INTERVAL);
|
|
}
|
|
|
|
/**
|
|
* Gets a user by its ID
|
|
*
|
|
* @param id The ID of the user
|
|
* @return The user
|
|
*/
|
|
public BatUser getUser(@NonNull String id) {
|
|
long before = System.currentTimeMillis();
|
|
// User is cached
|
|
if (users.containsKey(id)) {
|
|
return users.get(id);
|
|
}
|
|
if (DiscordService.JDA.getUserById(id) == null) {
|
|
log.warn("Attempted to get user with ID \"{}\" but it does not exist", id);
|
|
return null;
|
|
}
|
|
// User is not cached
|
|
Document document = MongoService.INSTANCE.getUsersCollection().find(Filters.eq("_id", id)).first();
|
|
if (document != null) {
|
|
BatUser user = new BatUser(id, document);
|
|
users.put(id, user);
|
|
log.info("Loaded user \"{}\" in {}ms", user.getName(),System.currentTimeMillis() - before);
|
|
return user;
|
|
}
|
|
// New user
|
|
BatUser user = new BatUser(id, new Document());
|
|
users.put(id, user);
|
|
log.info("Created user \"{}\" - \"{}\"", user.getName(), user.getId());
|
|
return user;
|
|
}
|
|
|
|
@Override
|
|
public void onSpringShutdown() {
|
|
log.info("Saving all users before shutdown...");
|
|
for (BatUser user : users.values()) {
|
|
user.save();
|
|
}
|
|
log.info("Saved all users.");
|
|
}
|
|
}
|