aboutsummaryrefslogtreecommitdiffstats
path: root/ui-client/src/main/java/market/guess/ui/client/ServerClient.java
blob: 00f3d6881975561e697a085d3da2809446b74f8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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<EventSummaryDTO> events,
      Map<String, EventDetailDTO> details,
      List<UserSummaryDTO> users,
      LedgerDTO account) {}

  private record SyncReply(
      boolean changed,
      long version,
      List<EventSummaryDTO> events,
      List<UserSummaryDTO> 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<String, List<Cookie>>();
    this.http =
        new OkHttpClient.Builder()
            .cookieJar(
                new CookieJar() {
                  @Override
                  public void saveFromResponse(HttpUrl url, List<Cookie> list) {
                    cookies.put(url.host(), list);
                  }

                  @Override
                  public List<Cookie> loadForRequest(HttpUrl url) {
                    return cookies.getOrDefault(url.host(), List.of());
                  }
                })
            .build();
  }

  public Result<String> login(String username) {
    Result<JsonObject> 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<SyncReply> 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<String, EventDetailDTO>();
    for (var e : reply.events()) {
      Result<EventDetailDTO> 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<ChatMessageDTO> pullChat() {
    var url = url("chat").newBuilder().addQueryParameter("since", "" + lastChatId).build();
    Result<List<ChatMessageDTO>> res =
        call(
            new Request.Builder().url(url).build(),
            new TypeToken<List<ChatMessageDTO>>() {}.getType());
    if (!res.isSuccess() || res.getData().isEmpty()) {
      return List.of();
    }
    lastChatId = res.getData().getLast().id();
    return res.getData();
  }

  public Result<ChatMessageDTO> say(String text) {
    return post(ChatMessageDTO.class, new FormBody.Builder().add("text", text).build(), "chat");
  }

  public void startPolling(Runnable onChange, Consumer<List<ChatMessageDTO>> onChat) {
    poller.scheduleWithFixedDelay(
        () -> {
          try {
            if (pull()) {
              onChange.run();
            }
            var said = pullChat();
            if (!said.isEmpty()) {
              onChat.accept(said);
            }
          } catch (RuntimeException e) {
          }
        },
        1,
        1,
        TimeUnit.SECONDS);
  }

  <T> Result<T> get(Type type, String... path) {
    return call(new Request.Builder().url(url(path)).build(), type);
  }

  <T> Result<T> 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 <T> Result<T> 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();
  }
}