-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStarwatchClient.cs
374 lines (308 loc) · 15.6 KB
/
StarwatchClient.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
using KoalaBot.Starwatch.Entities;
using KoalaBot.Starwatch.Exceptions;
using KoalaBot.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using KoalaBot.Starwatch.Responses;
namespace KoalaBot.Starwatch
{
public class StarwatchClient
{
public string Host { get; }
private HttpClient _httpClient;
private string _authorization;
public StarwatchClient(string host, string username, string password)
{
Host = host.TrimEnd('/');
_httpClient = new HttpClient();
//Set the auth header
var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
_authorization = Convert.ToBase64String(byteArray);
//_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
/// <summary>
/// Searches for an account
/// </summary>
/// <param name="account"></param>
/// <param name="character"></param>
/// <param name="ip"></param>
/// <param name="uuid"></param>
/// <returns></returns>
public async Task<Response<Session[]>> GetSessionsAsync(string account = null, string character = null, string ip = null, string uuid = null)
{
var queries = new Dictionary<string, object>();
if (!string.IsNullOrEmpty(account)) queries.Add("account", account);
if (!string.IsNullOrEmpty(character)) queries.Add("username", character);
if (!string.IsNullOrEmpty(ip)) queries.Add("ip", ip);
if (!string.IsNullOrEmpty(uuid)) queries.Add("uuid", uuid);
return await GetRequestAsync<Session[]>("/session", queries);
}
/// <summary>
/// Reloads the server settings
/// </summary>
/// <param name="wait"></param>
/// <returns></returns>
public async Task<RestResponse> ReloadAsync(bool wait)
{
return await PutRequestAsync<object>(
"/server",
new Dictionary<string, object>() { ["async"] = !wait, ["reload"] = true },
new Dictionary<string, object>() { }
);
}
/// <summary>
/// Restarts the server
/// </summary>
/// <param name="reason"></param>
/// <param name="wait"></param>
/// <returns></returns>
public async Task<RestResponse> RestartAsync(string reason, bool wait)
{
return await DeleteRequestAsync<object>("/server", new Dictionary<string, object>() { ["reason"] = reason, ["async"] = !wait });
}
#region protection
/// <summary>
/// Gets a protection for the world
/// </summary>
/// <param name="world"></param>
/// <returns></returns>
public async Task<Response<Protection>> GetProtectionAsync(World world) => await GetRequestAsync<Protection>($"/world/{world.Whereami}/protection");
/// <summary>
/// Creates a new world protection
/// </summary>
/// <param name="protection"></param>
/// <returns></returns>
public async Task<Response<Protection>> CreateProtectionAsync(Protection protection) => await PostRequestAsync<Protection>($"/world/{protection.Whereami}/protection", payload: protection);
/// <summary>
/// Deletes a world protection
/// </summary>
/// <param name="world"></param>
/// <returns></returns>
public async Task<RestResponse> DeleteProtectionAsync(World world) => await DeleteRequestAsync<object>($"/world{world.Whereami}/protection");
/// <summary>
/// Gets the protected account
/// </summary>
/// <param name="world"></param>
/// <param name="account"></param>
/// <returns></returns>
public async Task<Response<ProtectedAccount>> GetProtectionAccountAsync(World world, string account) => await GetRequestAsync<ProtectedAccount>($"/world/{world.Whereami}/protection/{account}");
/// <summary>
/// Adds an account to the list
/// </summary>
/// <param name="world"></param>
/// <param name="account"></param>
/// <param name="reason"></param>
/// <returns></returns>
public async Task<Response<object>> CreateProtectedAccountAsync(World world, string account, string reason) => await PostRequestAsync<object>($"/world/{world.Whereami}/protection/{account}", new Dictionary<string, object>() { ["reason"] = reason });
/// <summary>
/// Deletes an account from the list
/// </summary>
/// <param name="world"></param>
/// <param name="account"></param>
/// <param name="reason"></param>
/// <returns></returns>
public async Task<Response<bool>> DeleteProtectedAccountAsync(World world, string account, string reason) => await DeleteRequestAsync<bool>($"/world/{world.Whereami}/protection/{account}", new Dictionary<string, object>() { ["reason"] = reason });
#endregion
#region Backup
/// <summary>
/// Gets the restore information
/// </summary>
/// <param name="world"></param>
/// <returns></returns>
public async Task<Response<Restore>> GetRestoreAsync(World world) => await GetRequestAsync<Restore>($"/world/{world.Whereami}/restore");
/// <summary>
/// Sets the mirror information
/// </summary>
/// <param name="world"></param>
/// <param name="backup"></param>
/// <returns></returns>
public async Task<Response<Restore>> SetRestoreMirrorAsync(World world, World mirror) => await PutRequestAsync<Restore>($"/world/{world.Whereami}/restore", payload: new Restore() { World = world.Whereami, Mirror = mirror.Whereami });
/// <summary>
/// Deletes the restore
/// </summary>
/// <param name="world"></param>
/// <param name="backup"></param>
/// <returns></returns>
public async Task<Response<bool>> DeleteRestoreAsync(World world) => await DeleteRequestAsync<bool>($"/world/{world.Whereami}/restore");
/// <summary>
/// Creates a new restore.
/// </summary>
/// <param name="world"></param>
/// <returns></returns>
public async Task<Response<Restore>> CreateRestoreAsync(World world) => await PostRequestAsync<Restore>($"/world/{world.Whereami}/restore", payload: new Restore() { World = world.Whereami });
#endregion
#region Ban
/// <summary>
/// Creates a new ban
/// </summary>
/// <param name="ban"></param>
/// <returns></returns>
public async Task<Response<Ban>> BanAsync(Ban ban) => await PostRequestAsync<Ban>("/ban", payload: ban);
/// <summary>
/// Gets the ban
/// </summary>
/// <param name="ticket"></param>
/// <returns></returns>
public async Task<Response<Ban>> GetBanAsync(long ticket) => await GetRequestAsync<Ban>($"/ban/{ticket}");
/// <summary>
/// Deletes the ban
/// </summary>
/// <param name="ticket"></param>
/// <returns></returns>
public async Task<Response<bool>> DeleteBanAsync(long ticket) => await DeleteRequestAsync<bool>($"/ban/{ticket}");
#endregion
#region Account
public async Task<Response<Account>> GetAccountAsync(string name) => await GetRequestAsync<Account>($"/account/{name}");
public async Task<Response<Account>> CreateAccountAsync(Account account)
{
if (account is null)
throw new ArgumentNullException(nameof(account));
return await PostRequestAsync<Account>($"/account", payload: account);
}
public async Task<Response<Account>> UpdateAccountAsync(string name, Account account) => await PutRequestAsync<Account>($"/account/{name}", payload: account);
public async Task<Response<bool>> DeleteAccountAsync(string name) => await DeleteRequestAsync<bool>($"/account/{name}");
public async Task<Response<PlayerKickResponse>> KickPlayerAsync(Player player, string reason = null, int? duration = null)
{
string reasonParam = string.Empty;
string durationParam = string.Empty;
if (!(reason is null))
reasonParam = $"&reason={HttpUtility.UrlEncode(reason)}";
if (!(duration is null))
durationParam = $"&duration={duration}";
string url = $"/player/kick?{player.EncodeAsParameters()}{reasonParam}{durationParam}";
return await DeleteRequestAsync<PlayerKickResponse>(url);
}
#endregion
public async Task<Response<Announcement>> GetAnnouncementAsync(long id) => await GetRequestAsync<Announcement>($"/announcement?id={id}");
public async Task<Response<int>> GetAnnouncementCountAsync() => await GetRequestAsync<int>($"/announcement");
public async Task<Response<object>> DeleteAnnouncementAsync(long id) => await DeleteRequestAsync<object>($"/announcement?id={id}");
public async Task<Response<object>> PostAnnouncementAsync(string message, bool enabled, double interval) => await PostRequestAsync<object>($"/announcement?message={message}&enabled={enabled}&interval={interval}");
public async Task<Response<Announcement>> PutAnnouncementAsync (AnnouncementPatch announcement)
{
if (announcement is null)
throw new ArgumentNullException(nameof(announcement));
return await PutRequestAsync<Announcement>($"/announcement",
new Dictionary<string, object> { },
announcement);
}
/// <summary>
/// Gets the statistics of the server
/// </summary>
/// <returns></returns>
public async Task<Response<Statistics>> GetStatisticsAsync() => await GetRequestAsync<Statistics>("/server/statistics");
public async Task<Response<string>> GetVersionAsync() => await GetRequestAsync<string>("/version");
#region Request Fetching
/// <summary>
/// Sends a GET request to a specified endpoint.
/// </summary>
public async Task<Response<object>> GetRequestAsync(string endpoint)
{
return await GetRequestAsync<object>(endpoint);
}
/// <summary>
/// Sends a GET request to a specified endpoint.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <returns></returns>
private async Task<Response<T>> GetRequestAsync<T>(string endpoint, IEnumerable<KeyValuePair<string, object>> queries = null)
{
Uri url = BuildUrl(endpoint, queries);
var _client = _httpClient;
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _authorization);
var response = await _client.GetAsync(url);
return await ProcessResponseMessage<T>(response);
}
/// <summary>
/// Sends a DELETE request to a specific endpoint
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="queries"></param>
/// <returns></returns>
private async Task<Response<T>> DeleteRequestAsync<T>(string endpoint, IEnumerable<KeyValuePair<string, object>> queries = null)
{
Uri url = BuildUrl(endpoint, queries);
var _client = _httpClient;
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _authorization);
var response = await _client.DeleteAsync(url);
return await ProcessResponseMessage<T>(response);
}
/// <summary>
/// Sends a PUT request to a specific endpoint
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="queries"></param>
/// <returns></returns>
private async Task<Response<T>> PutRequestAsync<T>(string endpoint, IEnumerable<KeyValuePair<string, object>> queries = null, object payload = null)
{
Uri url = BuildUrl(endpoint, queries);
var json = JsonConvert.SerializeObject(payload);
var _client = _httpClient;
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _authorization);
var request = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PutAsync(url, request);
return await ProcessResponseMessage<T>(response);
}
/// <summary>
/// Sends a POST request to a specific endpoint
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="queries"></param>
/// <returns></returns>
private async Task<Response<T>> PostRequestAsync<T>(string endpoint, IEnumerable<KeyValuePair<string, object>> queries = null, object payload = null)
{
Uri url = BuildUrl(endpoint, queries);
var json = payload == null ? "{}" : JsonConvert.SerializeObject(payload);
var _client = _httpClient;
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _authorization);
var request = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(url, request);
return await ProcessResponseMessage<T>(response);
}
private async Task<Response<T>> ProcessResponseMessage<T>(HttpResponseMessage response)
{
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden || response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
throw new HttpRequestException("Forbidden");
//Read the json
string json = await response.Content.ReadAsStringAsync();
//Return the json object deserialized.
var res = JsonConvert.DeserializeObject<Response<JToken>>(json);
if (res == null) throw new Exception("Failed to get any response from the server. Got: " + json);
switch (res.Status)
{
case RestStatus.Forbidden:
throw new RestForbiddenException(res);
case RestStatus.RouteNotFound:
throw new RestRouteNotFoundException(res);
case RestStatus.NotImplemented:
throw new NotImplementedException("Endpoint is not implemented.");
case RestStatus.TooManyRequests:
throw new RestRateLimitException(new Response<RateLimit>(res));
//Return the response. Everything else can be handled.
default:
return new Response<T>(res);
}
}
private Uri BuildUrl(string endpoint, IEnumerable<KeyValuePair<string, object>> queries)
{
string url = $"{Host}/api{endpoint.TrimEnd('/')}";
if (queries != null)
{
var q = string.Join("&", queries.Select(kp => $"{kp.Key}={HttpUtility.UrlEncode(kp.Value.ToString())}"));
if (!string.IsNullOrEmpty(q)) url += $"?{q}";
}
return new Uri(url);
}
#endregion
}
}