package net.frozenorb.apiv3.model; import com.google.common.collect.ImmutableSet; import com.mongodb.async.client.MongoCollection; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import fr.javatic.mongo.jacksonCodec.Entity; import fr.javatic.mongo.jacksonCodec.objectId.Id; import lombok.Getter; import lombok.Setter; import net.frozenorb.apiv3.APIv3; import net.frozenorb.apiv3.serialization.gson.ExcludeFromReplies; import net.frozenorb.apiv3.unsorted.BlockingCallback; import net.frozenorb.apiv3.util.SyncUtils; import org.bson.Document; import java.time.Instant; import java.util.*; import java.util.concurrent.TimeUnit; @Entity public final class Server { private static final MongoCollection serversCollection = APIv3.getDatabase().getCollection("servers", Server.class); private static Map serverCache = null; private static List serverCacheAlt = null; private static long serverCacheUpdated = 0; @Getter @Id private String id; @Getter private String displayName; @Getter @ExcludeFromReplies String apiKey; @Getter private String serverGroup; @Getter private String serverIp; @Getter @Setter private Instant lastUpdatedAt; @Getter @Setter private double lastTps; @Getter @Setter @ExcludeFromReplies private Set players; public static List findAll() { updateCacheIfNeeded(); return serverCacheAlt; } public static Server findById(String id) { updateCacheIfNeeded(); return serverCache.get(id); } public Server() {} // For Morphia public Server(String id, String displayName, String apiKey, ServerGroup serverGroup, String serverIp) { this.id = id; this.displayName = displayName; this.apiKey = apiKey; this.serverGroup = serverGroup.getId(); this.serverIp = serverIp; this.lastUpdatedAt = Instant.now(); this.lastTps = 0; this.players = new HashSet<>(); } private static void updateCacheIfNeeded() { if (serverCache == null || (System.currentTimeMillis() - serverCacheUpdated) > TimeUnit.MINUTES.toMillis(1)) { Map working = new HashMap<>(); List workingAlt = new ArrayList<>(); for (Server server : SyncUtils.blockMulti(serversCollection.find())) { working.put(server.getId(), server); workingAlt.add(server); } serverCache = working; serverCacheAlt = workingAlt; serverCacheUpdated = System.currentTimeMillis(); } } public void receivedHeartbeat(double tps, Iterable players) { this.lastUpdatedAt = Instant.now(); this.lastTps = tps; this.players = ImmutableSet.copyOf(players); } public void insert() { BlockingCallback callback = new BlockingCallback<>(); serversCollection.insertOne(this, callback); callback.get(); } public void save() { BlockingCallback callback = new BlockingCallback<>(); serversCollection.replaceOne(new Document("_id", id), this, callback); callback.get(); } public void delete() { BlockingCallback callback = new BlockingCallback<>(); serversCollection.deleteOne(new Document("_id", id), callback); callback.get(); } }