package market.guess.ui.client; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import market.guess.api.Result; import market.guess.model.chat.ChatMessageDTO; import market.guess.model.event.EventDetailDTO; import market.guess.model.event.EventSummaryDTO; import market.guess.model.ledger.LedgerDTO; import market.guess.model.ledger.UserSummaryDTO; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; public final class ServerClient implements AutoCloseable { private static final Gson GSON = new Gson(); record Snapshot( long version, List events, Map details, List users, LedgerDTO account) {} private record SyncReply( boolean changed, long version, List events, List users, LedgerDTO account) {} private final HttpUrl api; private final OkHttpClient http; private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor( r -> { var t = new Thread(r, "gm-poller"); t.setDaemon(true); return t; }); private volatile Snapshot snapshot = new Snapshot(-1, List.of(), Map.of(), List.of(), null); private long lastChatId; // touched only under the pullChat lock public ServerClient(String apiUrl) { this.api = HttpUrl.get(apiUrl); var cookies = new ConcurrentHashMap>(); this.http = new OkHttpClient.Builder() .cookieJar( new CookieJar() { @Override public void saveFromResponse(HttpUrl url, List list) { cookies.put(url.host(), list); } @Override public List loadForRequest(HttpUrl url) { return cookies.getOrDefault(url.host(), List.of()); } }) .build(); } public Result login(String username) { Result res = post(JsonObject.class, new FormBody.Builder().add("username", username).build(), "login"); return res.isSuccess() ? Result.ok(res.getData().get("username").getAsString()) : Result.error(res.getMessage(), res.getDetails()); } public void logout() { post(JsonObject.class, new FormBody.Builder().build(), "logout"); } Snapshot snapshot() { return snapshot; } String eventName(String eventKey) { return snapshot.events().stream() .filter(e -> e.key().equals(eventKey)) .map(EventSummaryDTO::name) .findFirst() .orElse(null); } public synchronized boolean pull() { var url = url("sync").newBuilder().addQueryParameter("since", "" + snapshot.version()).build(); Result res = call(new Request.Builder().url(url).build(), SyncReply.class); if (!res.isSuccess() || !res.getData().changed()) { return false; } var reply = res.getData(); var details = new HashMap(); for (var e : reply.events()) { Result detail = get(EventDetailDTO.class, "events", e.name()); if (detail.isSuccess()) { details.put(e.key(), detail.getData()); } } snapshot = new Snapshot(reply.version(), reply.events(), details, reply.users(), reply.account()); return true; } public synchronized List pullChat() { var url = url("chat").newBuilder().addQueryParameter("since", "" + lastChatId).build(); Result> res = call( new Request.Builder().url(url).build(), new TypeToken>() {}.getType()); if (!res.isSuccess() || res.getData().isEmpty()) { return List.of(); } lastChatId = res.getData().getLast().id(); return res.getData(); } public Result say(String text) { return post(ChatMessageDTO.class, new FormBody.Builder().add("text", text).build(), "chat"); } public void startPolling(Runnable onChange, Consumer> onChat) { poller.scheduleWithFixedDelay( () -> { try { if (pull()) { onChange.run(); } var said = pullChat(); if (!said.isEmpty()) { onChat.accept(said); } } catch (RuntimeException e) { } }, 1, 1, TimeUnit.SECONDS); } Result get(Type type, String... path) { return call(new Request.Builder().url(url(path)).build(), type); } Result post(Type type, RequestBody body, String... path) { return call(new Request.Builder().url(url(path)).post(body).build(), type); } private HttpUrl url(String... path) { var b = api.newBuilder(); for (var segment : path) { b.addPathSegment(segment); // percent-encodes, so event names may hold spaces and '?' } return b.build(); } private Result call(Request request, Type type) { try (var res = http.newCall(request).execute()) { var body = res.body().string(); if (res.isSuccessful()) { return Result.ok(GSON.fromJson(body, type)); } var message = "The server answered " + res.code() + "."; try { message = GSON.fromJson(body, JsonObject.class).get("message").getAsString(); } catch (RuntimeException notOurJson) { } return Result.error(message, message); } catch (IOException | RuntimeException e) { var message = "Cannot reach the server: " + e.getMessage(); return Result.error(message, message); } } @Override public void close() { poller.shutdownNow(); http.dispatcher().executorService().shutdown(); http.connectionPool().evictAll(); } }