-
Notifications
You must be signed in to change notification settings - Fork 0
/
Api.cs
271 lines (247 loc) · 9.01 KB
/
Api.cs
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
namespace CodeGame.Client;
using System.Globalization;
using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Numerics;
using System.Reactive.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Websocket.Client;
/// <summary>
/// JsonNamingPolicy for snake_case.
/// </summary>
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
/// <summary>
/// Converts name to snake_case.
/// </summary>
/// <param name="name">The key name.</param>
/// <returns>The key name converted to snake_case.</returns>
public override string ConvertName(string name)
{
StringBuilder sbuilder = new StringBuilder();
for (var i = 0; i < name.Length; i++)
{
if (char.IsLower(name[i]) && i < name.Length - 1 && char.IsUpper(name[i + 1]))
{
sbuilder.Append(name[i]);
sbuilder.Append('_');
continue;
}
if (char.IsUpper(name[i]) && i > 0 && i < name.Length - 1 && char.IsUpper(name[i - 1]) && char.IsLower(name[i + 1]))
{
sbuilder.Append('_');
sbuilder.Append(name[i]);
continue;
}
sbuilder.Append(name[i]);
}
return sbuilder.ToString().ToLower();
}
}
/// <summary>
/// Common methods for interfacing with CodeGame game servers.
/// </summary>
public class Api
{
/// <summary>
/// Game info from the <c>/api/info</c> endpoint.
/// </summary>
public class GameInfo
{
#pragma warning disable 1591
public string Name { get; set; } = "";
public string CGVersion { get; set; } = "";
public string? DisplayName { get; set; }
public string? Description { get; set; }
public string? Version { get; set; }
public string? RepositoryURL { get; set; }
#pragma warning restore 1591
}
/// <summary>
/// The URL of the game server without any protocol or trailing slashes.
/// </summary>
public string URL { get; private set; }
/// <summary>
/// Whether the game server supports TLS.
/// </summary>
public bool TLS { get; private set; }
/// <summary>
/// The URL of the game server including the protocol and without a trailing slash.
/// </summary>
public string BaseURL { get; private set; }
internal static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
AllowTrailingCommas = true,
PropertyNamingPolicy = new SnakeCaseNamingPolicy(),
DictionaryKeyPolicy = new SnakeCaseNamingPolicy(),
Converters = {
new JsonStringEnumConverter(new SnakeCaseNamingPolicy(), false),
}
};
private static readonly HttpClient http = new HttpClient();
/// <summary>
/// Fetches the game info from the /api/info endpoint.
/// </summary>
/// <returns></returns>
/// <exception cref="HttpRequestException">Thrown when the request fails.</exception>
/// <exception cref="JsonException">Thrown when the decoding of the response body fails.</exception>
public async Task<GameInfo> FetchInfo()
{
var gameInfo = await http.GetFromJsonAsync<GameInfo>(BaseURL + "/api/info", JsonOptions);
if (gameInfo == null || gameInfo.Name == "" || gameInfo.CGVersion == "")
{
throw new JsonException("Invalid server response.");
}
return gameInfo;
}
private class GameConfigResponse<T>
{
public T? Config { get; set; }
}
/// <summary>
/// Fetches the game config from the server.
/// </summary>
/// <typeparam name="T">The type of the game config.</typeparam>
/// <param name="gameId">The ID of the game.</param>
/// <returns>The config of the game.</returns>
/// <exception cref="JsonException">Thrown when the response of the server is invalid.</exception>
public async Task<T> FetchGameConfig<T>(string gameId)
{
var result = await http.GetFromJsonAsync<GameConfigResponse<T>>(BaseURL + "/api/games/" + gameId, JsonOptions);
if (result == null || result.Config == null)
{
throw new JsonException("Invalid server response.");
}
return result.Config;
}
internal async Task<WebsocketClient> ConnectWebSocket(string endpoint, Func<ResponseMessage, Task> onMessage)
{
var client = new WebsocketClient(new Uri(GetBaseURL("ws", TLS, URL) + endpoint));
client.ReconnectTimeout = null;
client.ErrorReconnectTimeout = null;
client.MessageReceived.Select(msg => Observable.FromAsync(async () => await onMessage(msg))).Concat().Subscribe();
await client.StartOrFail();
return client;
}
internal async Task<(string gameId, string joinSecret)> CreateGame(bool makePublic, bool protect, object? config = null)
{
var requestData = new
{
Public = makePublic,
Protected = protect,
Config = config
};
var res = await http.PostAsJsonAsync(BaseURL + "/api/games", requestData, JsonOptions);
await ensureSuccessful(res);
var result = await res.Content.ReadFromJsonAsync<Dictionary<string, string>>(JsonOptions);
if (result == null || !result.ContainsKey("game_id") || (protect && !result.ContainsKey("join_secret")))
{
throw new JsonException("Invaild server response.");
}
return (result["game_id"], protect ? result["join_secret"] : "");
}
internal async Task<(string playerId, string playerSecret)> CreatePlayer(string gameId, string username, string joinSecret = "")
{
var requestData = new
{
Username = username,
JoinSecret = joinSecret
};
var res = await http.PostAsJsonAsync(BaseURL + "/api/games/" + gameId + "/players", requestData, JsonOptions);
await ensureSuccessful(res);
var result = await res.Content.ReadFromJsonAsync<Dictionary<string, string>>(JsonOptions);
if (result == null || !result.ContainsKey("player_id") || !result.ContainsKey("player_secret"))
{
throw new JsonException("Invaild server response.");
}
return (result["player_id"], result["player_secret"]);
}
internal async Task<string> FetchUsername(string gameId, string playerId)
{
var res = await http.GetAsync(BaseURL + "/api/games/" + gameId + "/players/" + playerId);
if (res.StatusCode == HttpStatusCode.NotFound) throw new CodeGameException("The player does not exist in the game.");
await ensureSuccessful(res);
var result = await res.Content.ReadFromJsonAsync<Dictionary<string, string>>(JsonOptions);
if (result == null || !result.ContainsKey("username"))
{
throw new JsonException("Invalid server response.");
}
return result["username"];
}
internal async Task<Dictionary<string, string>> FetchPlayers(string gameId)
{
var result = await http.GetFromJsonAsync<Dictionary<string, string>>(BaseURL + "/api/games/" + gameId + "/players", JsonOptions);
if (result == null)
{
throw new JsonException("Invalid server response.");
}
return result;
}
internal static async Task<Api> Create(string url)
{
url = TrimURL(url);
var tls = await IsTLS(url);
return new Api(url, tls);
}
private Api(string trimmedURL, bool tls)
{
this.URL = trimmedURL;
this.TLS = tls;
this.BaseURL = GetBaseURL("http", tls, trimmedURL);
}
internal static string TrimURL(string url)
{
url = url.TrimEnd('/');
string[] parts = url.Split("://");
if (parts.Length < 2)
{
return url;
}
return string.Join("://", parts.Skip(1).ToArray());
}
internal static string GetBaseURL(string protocol, bool tls, string trimmedURL)
{
if (tls)
{
return protocol + "s://" + trimmedURL;
}
return protocol + "://" + trimmedURL;
}
internal static async Task<bool> IsTLS(string trimmedURL)
{
try
{
var res = await http.GetAsync("https://" + trimmedURL);
return res.IsSuccessStatusCode || res.StatusCode == HttpStatusCode.NotFound;
}
catch (HttpRequestException)
{
return false;
}
}
private async static Task ensureSuccessful(HttpResponseMessage? res)
{
if (res == null) throw new HttpRequestException("Received no response from the server.");
try
{
res.EnsureSuccessStatusCode();
}
catch (HttpRequestException e)
{
try
{
var msg = await res.Content.ReadAsStringAsync();
if (msg != null && msg != "")
throw new CodeGameException(msg, e);
}
catch (Exception ex)
{
if (ex is CodeGameException) throw;
}
throw;
}
}
}