-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXBLClient.cs
More file actions
317 lines (276 loc) · 9.55 KB
/
XBLClient.cs
File metadata and controls
317 lines (276 loc) · 9.55 KB
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
using System.Net.WebSockets;
using System.Runtime.Serialization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace XboxLiveStatusClient;
public class XBLClient
{
// Status values for each state, feel free to change them to your liking, I just used this for the DevExpress gauges
public enum ServiceStatus
{
Unknown = 0, // Grey/Undefined
Inoperational = 1, // Red
Mostly = 2, // Amber
Fully = 3 // Green
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum XboxLiveMessageType
{
[EnumMember(Value = "stats")] Stats,
[EnumMember(Value = "xbl_status")] XblStatus,
[EnumMember(Value = "xboxlive_status")]
XboxliveStatus,
Unknown
}
public async Task<XboxLiveStatusResult> GetLiveAuthStatusAsync(int timeoutMs = 5000)
{
var result = new XboxLiveStatusResult();
var url = new Uri("wss://kvchecker.com/ws/LIVEAuthentication");
result.LastUpdated = DateTime.UtcNow;
using (var ws = new ClientWebSocket())
{
ws.Options.SetRequestHeader("Origin", "https://xblstatus.com");
var cancellationTokenSource = new CancellationTokenSource(timeoutMs);
var buffer = new byte[8192]; // Buffer size
try
{
await ws.ConnectAsync(url, cancellationTokenSource.Token);
}
catch (WebSocketException ex)
{
result.Success = false;
result.ErrorMessage = $"Failed to connect to WebSocket: {ex.Message}";
return result; // Early return in case of connection failure
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = $"Unexpected error during WebSocket connection: {ex.Message}";
return result; // Early return in case of unexpected failure
}
var dataReceived = new TaskCompletionSource<bool>();
_ = Task.Run(async () =>
{
try
{
while (ws.State == WebSocketState.Open)
{
var segment = new ArraySegment<byte>(buffer);
var receiveResult = await ws.ReceiveAsync(segment, cancellationTokenSource.Token);
if (receiveResult.MessageType == WebSocketMessageType.Text)
{
var jsonContent = Encoding.UTF8.GetString(segment.Array, 0, receiveResult.Count);
var serializedContent = JsonSerializer.Deserialize<XboxLiveStatusResponse>(jsonContent);
if (serializedContent == null)
{
result.ErrorMessage = "Invalid data received from WebSocket.";
dataReceived.TrySetResult(false); // Signals that the data wasn't procesed
return;
}
if (serializedContent.Type != XboxLiveMessageType.Unknown &&
serializedContent.Services != null)
{
foreach (var service in serializedContent.Services)
{
var status = DetermineServiceStatus(service);
result.Services.Add(new XboxLiveService
{
Name = service.Name,
Description = service.Description,
IsOperational = service.IsOperational,
Status = status,
StatusText = GetStatusText(status)
});
}
result.Success = true;
dataReceived.TrySetResult(true);
}
else
{
result.Success = false;
result.ErrorMessage = "Invalid response format received.";
dataReceived.TrySetResult(false); // Signals a failure due to bad format
}
}
}
}
catch (WebSocketException ex)
{
result.Success = false;
result.ErrorMessage = $"WebSocket error while receiving data: {ex.Message}";
dataReceived.TrySetResult(false); // Signals a failure due toa WebSocket error
}
catch (TaskCanceledException)
{
result.Success = false;
result.ErrorMessage = "Operation timed out while receiving data.";
dataReceived.TrySetResult(false); // Signals a failure due to a timeout
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = $"Unexpected error while reading data: {ex.Message}";
dataReceived.TrySetResult(false); // Signals a failure due to an unexpected error
}
});
try
{
// Awaits TaskCompletion to signal cancellation or completion
await dataReceived.Task;
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = $"Error while waiting for WebSocket data: {ex.Message}";
}
try
{
if (ws.State == WebSocketState.Open)
{
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing connection",
CancellationToken.None);
}
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = $"Error closing WebSocket: {ex.Message}";
}
}
return result;
}
// Determines service status based on description & status, this can be improved further but for now it works
private ServiceStatus DetermineServiceStatus(XboxLiveServiceStatus service)
{
if (!service.IsOperational)
{
return ServiceStatus.Inoperational;
}
if (!string.IsNullOrEmpty(service.Description) && service.Description.Contains("Mostly"))
{
return ServiceStatus.Mostly;
}
return ServiceStatus.Fully;
}
// Gets the status text based on the service status
private string GetStatusText(ServiceStatus status)
{
switch (status)
{
case ServiceStatus.Fully:
return "Fully Operational";
case ServiceStatus.Mostly:
return "Mostly Operational";
case ServiceStatus.Inoperational:
return "Inoperational";
default:
return "Unknown";
}
}
public class XboxLiveServiceStatus
{
[JsonPropertyName("name")]
public string Name
{
get;
set;
}
[JsonPropertyName("description")]
public string Description
{
get;
set;
}
[JsonPropertyName("color")]
public string Color
{
get;
set;
}
public bool IsOperational => Color == "#0c0";
}
public sealed class XboxLiveStatusResponse
{
[JsonPropertyName("message_type")]
public string MessageTypeString
{
get;
set;
} = string.Empty;
[JsonIgnore]
public XboxLiveMessageType Type
{
get
{
if (Enum.TryParse<XboxLiveMessageType>(MessageTypeString, true, out var result))
{
return result;
}
if (MessageTypeString.Contains("status"))
{
return XboxLiveMessageType.XboxliveStatus;
}
return XboxLiveMessageType.Unknown;
}
}
[JsonPropertyName("services")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public XboxLiveServiceStatus[] Services
{
get;
set;
}
}
public class XboxLiveService
{
public string Name
{
get;
set;
}
public string Description
{
get;
set;
}
public bool IsOperational
{
get;
set;
}
public ServiceStatus Status
{
get;
set;
} = ServiceStatus.Unknown;
public string StatusText
{
get;
set;
} = "Unknown";
}
public class XboxLiveStatusResult
{
public List<XboxLiveService> Services
{
get;
set;
} = new List<XboxLiveService>();
public bool Success
{
get;
set;
}
public string ErrorMessage
{
get;
set;
}
public DateTime LastUpdated
{
get;
set;
}
}
}