forked from Abev08/TwitchBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cs
More file actions
646 lines (574 loc) · 21.1 KB
/
Server.cs
File metadata and controls
646 lines (574 loc) · 21.1 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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
namespace AbevBot;
/// <summary> HTTP server with WebSocket connection to play notifications (instead of in the main window). </summary>
public static class Server
{
public static bool IsStarted { get; private set; }
/// <summary> HTTP server address. </summary>
public static IPAddress IP { get; private set; } = IPAddress.Parse("127.0.0.1");
/// <summary> HTTP server port. </summary>
public static ushort Port { get; private set; } = 40000;
/// <summary> Server thread. </summary>
private static readonly Thread ServerThread = new(Update) { IsBackground = true };
/// <summary> Is HTTP server required? </summary>
private static bool IsServerRestartRequired = true;
/// <summary> WebSocket message send queue. </summary>
private static readonly List<byte[]> WsSendQueue = new();
/// <summary> Current audio data that should be played. </summary>
public static byte[] CurrentAudio { get; set; }
/// <summary> Browser views video playing ended. </summary>
public static bool VideoEnded { get; set; } = true;
/// <summary> Amount of browser views on which the video playing has ended. </summary>
private static int VideoEndedCounter;
/// <summary> Browser views audio playing ended. </summary>
public static bool AudioEnded { get; set; } = true;
/// <summary> Amount of browser views on which the audio playing has ended. </summary>
private static int AudioEndedCounter;
/// <summary> Starts the HTTP server. </summary>
public static void Start()
{
if (IsStarted) { return; }
IsStarted = true;
// If everything is ok, start the server
ServerThread.Start();
Log.Information("HTTP server started at: {address}", $"http://{IP}:{Port}");
}
/// <summary> Updates IP address used by the HTTP server. </summary>
/// <param name="ip">IP address</param>
/// <param name="port">Port</param>
public static void UpdateIPAddress(string ip, ushort port)
{
// Try to parse provided IP address
if (!IPAddress.TryParse(ip, out var _ip) || ip is null)
{
Log.Error("HTTP server provided IP address is not recognized!");
return;
}
UpdateIPAddress(_ip, port);
}
/// <summary> Updates IP address used by the HTTP server. </summary>
/// <param name="ip">IP address</param>
/// <param name="port">Port</param>
public static void UpdateIPAddress(IPAddress ip, ushort port)
{
// Check if provided IP address is accessible
string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
bool ipOk = false;
foreach (var address in addr)
{
if (ip.Equals(address))
{
ipOk = true;
break;
}
}
if (!ipOk)
{
Log.Error("HTTP server provided IP address is not accessible!");
return;
}
IsServerRestartRequired = true;
}
/// <summary> Main update method used by the HTTP server thread. </summary>
private static void Update()
{
// Create and start the HTTP server
TcpListener httpServer = null;
var buffer = new byte[65535];
// Create and start WebSocket server
List<WebSocketConnection> wsConnections = new();
// string wsMsg = string.Empty;
byte[] wsSendBuffer = null;
bool wsSendTaskActive = false;
while (true)
{
if (MainWindow.CloseRequested) { return; }
if (IsServerRestartRequired || httpServer is null)
{
IsServerRestartRequired = false;
// Close all of the current ws connections
for (int i = wsConnections.Count - 1; i >= 0; i--)
{
wsConnections[i].Conn.CloseAsync(WebSocketCloseStatus.InternalServerError, null, CancellationToken.None);
wsConnections.RemoveAt(i);
}
// Restart the server
httpServer?.Stop();
httpServer = new(IP, Port);
httpServer.Start();
}
// Handle HTTP server
if (httpServer.Pending())
{
var conn = httpServer.AcceptTcpClient();
var stream = conn.GetStream();
var length = stream.Read(buffer, 0, buffer.Length);
var incomingMessage = Encoding.UTF8.GetString(buffer, 0, length).Split("\r\n");
var metadata = incomingMessage[0].Split(' ');
string secWebSocketKey = string.Empty;
if (metadata.Length != 3) { Log.Warning("HTTP server received bad request: {request}", incomingMessage[0]); }
else if (metadata[0] == "GET")
{
// Check connection type
for (int i = 1; i < incomingMessage.Length; i++)
{
if (incomingMessage[i].StartsWith("Connection:"))
{
var type = incomingMessage[i][12..];
if (type != "Upgrade") { break; }
}
if (incomingMessage[i].StartsWith("Upgrade:"))
{
var type = incomingMessage[i][9..];
if (type != "websocket") { break; }
}
if (incomingMessage[i].StartsWith("Sec-WebSocket-Key:"))
{
secWebSocketKey = incomingMessage[i][19..];
break;
}
}
if (secWebSocketKey.Length > 0)
{
// Upgrade tcp connection to websocket
Log.Information("HTTP server new request: {request}", "WebSocket upgrade");
var key = secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] keyHashed = SHA1.HashData(Encoding.UTF8.GetBytes(key));
string keyBase64 = Convert.ToBase64String(keyHashed);
byte[] response = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 101 Switching Protocols\r\n",
"Connection: Upgrade\r\n",
"Upgrade: websocket\r\n",
"Sec-WebSocket-Accept: ", keyBase64,
"\r\n\r\n"));
stream.Write(response);
var ws = new WebSocketConnection(
WebSocket.CreateFromStream(stream, true, null, TimeSpan.FromSeconds(1)));
switch (metadata[1])
{
case "/":
// Websocket connection to main notification view
wsConnections.Add(ws);
break;
case "/counter":
// Websocket connection to counter view
Counter.AddNewWebsocketConnection(ref ws);
break;
default:
// Unrecognized websocket connection? Just close it
stream.Close();
break;
}
}
else
{
Log.Information("HTTP server new request: {request}", metadata[1]);
byte[] response = null;
if (metadata[1] == "/")
{
var html = GetFileOrEmbedded("client.html");
response = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 200 OK\r\n",
"Content-Length: ", html.Length, "\r\n",
"Content-Type: text/html\r\n\r\n",
html,
"\r\n\r\n"));
}
else if (metadata[1] == "/client.js")
{
var js = GetFileOrEmbedded("client.js");
js = "let fromServer = true;\r\n" + js;
response = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 200 OK\r\n",
"Content-Length: ", js.Length, "\r\n",
"Content-Type: text/javascript\r\n\r\n",
js,
"\r\n\r\n"));
}
else if (metadata[1] == "/favicon.ico")
{
response = Encoding.UTF8.GetBytes("HTTP/1.1 404 Not Found\r\n\r\n");
}
else if (metadata[1] == "/audio")
{
if (CurrentAudio != null)
{
// Create repsonse header
var header = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 200 OK\r\n",
"Content-Length: ", CurrentAudio.Length, "\r\n",
$"Content-Type: audio/wav\r\n\r\n"));
response = new byte[header.Length + CurrentAudio.Length];
Array.Copy(header, response, header.Length);
Array.Copy(CurrentAudio, 0, response, header.Length, CurrentAudio.Length);
}
}
else if (metadata[1].StartsWith("/Resources"))
{
FileInfo file = new(Uri.UnescapeDataString(metadata[1][1..]));
bool error = !file.Exists;
// do {} while (false) loop for easy breaks
do
{
if (error) break;
// Check if requested file is in Resources direcotry
DirectoryInfo resources = new("Resources");
error = !resources.Exists;
if (error) break;
var parentDir = file.Directory;
while (!resources.FullName.Equals(parentDir.FullName))
{
parentDir = parentDir.Parent;
if (parentDir is null)
{
error = true;
break;
}
}
if (error) break;
// Get content type
string contentType;
if (Array.IndexOf(Notifications.SupportedVideoFormats, file.Extension) >= 0) { contentType = "video"; }
else if (Array.IndexOf(Notifications.SupportedAudioFormats, file.Extension) >= 0) { contentType = "audio"; }
else if (Array.IndexOf(Notifications.SupportedImageFormats, file.Extension) >= 0) { contentType = "image"; }
else
{
error = true;
break;
}
// Create repsonse header
var header = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 200 OK\r\n",
"Content-Length: ", file.Length, "\r\n",
$"Content-Type: {contentType}/{file.Extension[1..]}\r\n\r\n"));
response = new byte[header.Length + file.Length];
Array.Copy(header, response, header.Length);
// Append the file
using var s = file.OpenRead();
s.Read(response, header.Length, (int)file.Length);
} while (false);
if (error) { response = Encoding.UTF8.GetBytes("HTTP/1.1 404 Not Found\r\n\r\n"); }
}
else if (metadata[1] == "/counter")
{
var html = GetFileOrEmbedded("counter.html");
response = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 200 OK\r\n",
"Content-Length: ", html.Length, "\r\n",
"Content-Type: text/html\r\n\r\n",
html,
"\r\n\r\n"));
}
else if (metadata[1] == "/counter.js")
{
var js = GetFileOrEmbedded("counter.js");
js = "let fromServer = true;\r\n" + js;
response = Encoding.UTF8.GetBytes(string.Concat(
"HTTP/1.1 200 OK\r\n",
"Content-Length: ", js.Length, "\r\n",
"Content-Type: text/javascript\r\n\r\n",
js,
"\r\n\r\n"));
}
else { response = Encoding.UTF8.GetBytes("HTTP/1.1 404 Not Found\r\n\r\n"); }
if (response?.Length > 0) { stream.Write(response); }
stream.Close();
}
}
else
{
stream.Close();
Log.Error("HTTP server not handled request: {msg}", incomingMessage[0]);
}
}
// Check if there is a message to be send via websocket connection
lock (WsSendQueue)
{
if (!wsSendTaskActive && WsSendQueue.Count > 0)
{
wsSendBuffer = WsSendQueue[0];
WsSendQueue.RemoveAt(0);
}
}
wsSendTaskActive = false;
// Handle WebSocket server
for (int i = wsConnections.Count - 1; i >= 0; i--)
{
var ws = wsConnections[i];
if (ws.Conn.State != WebSocketState.Open)
{
ws.Conn.Dispose();
wsConnections.RemoveAt(i);
continue;
}
// Receive
if (ws.ReceiveTask is null) { ws.ReceiveTask = ws.Conn.ReceiveAsync(ws.ReceiveBuffer, CancellationToken.None); }
if (ws.ReceiveTask != null && ws.ReceiveTask.IsCompleted)
{
if (ws.ReceiveTask.Status == TaskStatus.RanToCompletion && ws.ReceiveTask.Result.Count > 0)
{
// Do something with received data
string msg = Encoding.UTF8.GetString(ws.ReceiveBuffer, 0, ws.ReceiveTask.Result.Count);
if (msg == "message_parsed")
{
if (ws.SendTask != null && ws.SendTask.IsCompleted) { ws.SendTask = null; }
}
else if (msg == "video_end") { VideoEndedCounter += 1; }
else if (msg == "audio_end") { AudioEndedCounter += 1; }
}
ws.ReceiveTask = null;
}
// Send
if (ws.SendTask != null) { wsSendTaskActive = true; }
else if (wsSendBuffer?.Length > 0)
{
// Fill the send buffer
ws.SendBuffer = new byte[wsSendBuffer.Length];
Array.Copy(wsSendBuffer, ws.SendBuffer, wsSendBuffer.Length);
// Send the message
ws.SendTask = ws.Conn.SendAsync(ws.SendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
wsSendBuffer = null;
VideoEnded = VideoEndedCounter >= wsConnections.Count;
AudioEnded = AudioEndedCounter >= wsConnections.Count;
Thread.Sleep(10);
}
}
/// <summary> Sends "clear" command to every connected HTTP client. </summary>
public static void ClearAll()
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "clear_all" },
}.ToJsonString());
VideoEndedCounter = int.MaxValue;
AudioEndedCounter = int.MaxValue;
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "clear_video" command to every connected HTTP client. </summary>
public static void ClearVideo()
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "clear_video" },
}.ToJsonString());
VideoEndedCounter = int.MaxValue;
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "clear_audio" command to every connected HTTP client. </summary>
public static void ClearAudio()
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "clear_audio" },
}.ToJsonString());
AudioEndedCounter = int.MaxValue;
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "clear_text" command to every connected HTTP client. </summary>
public static void ClearText()
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "clear_text" },
}.ToJsonString());
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "display text" command to every connected HTTP client. </summary>
/// <param name="text">Text to be displayed</param>
/// <param name="position">Text position</param>
/// <param name="size">Text size</param>
public static void DisplayText(string text, Notifications.TextPosition position, double size = -1)
{
if (text is null || text.Length == 0) return;
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "new_notification" },
{ "text", text },
{ "text_position", position.ToString() },
{ "text_size", size }
}.ToJsonString());
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "play video" command to every connected HTTP client. </summary>
/// <param name="videoPath">Path to the video file</param>
/// <param name="left">Video player position from left edge of the screen</param>
/// <param name="top">Video player position from top of the screen</param>
/// <param name="width">Video player width</param>
/// <param name="height">Video player height</param>
/// <param name="volume">Volume of video player</param>
public static void PlayVideo(string videoPath, float left, float top, float width, float height, float volume)
{
if (videoPath is null || videoPath.Length == 0) return;
if (!videoPath.StartsWith("http"))
{
FileInfo videoFile = new(videoPath);
if (!videoFile.Exists)
{
Log.Warning("Video file not found: {file}", videoFile.FullName);
return;
}
}
VideoEndedCounter = 0;
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "new_notification" },
{ "video", videoPath },
{ "video_position", new JsonArray(left, top) },
{ "video_size", new JsonArray(width, height) },
{ "video_volume", volume }
}.ToJsonString());
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "play audio" command to every connected HTTP client. </summary>
/// <param name="audioPath">Path to audio file</param>
/// <param name="volume">Volume</param>
public static void PlayAudio(string audioPath, float volume)
{
if (audioPath is null || audioPath.Length == 0) return;
FileInfo audioFile = new(audioPath);
if (!audioFile.Exists)
{
Log.Warning("Audio file not found: {file}", audioFile.FullName);
return;
}
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "new_notification" },
{ "audio", audioPath },
{ "audio_volume", volume }
}.ToJsonString());
AudioEndedCounter = 0;
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "play video" command to every connected HTTP client. Uses audio set by current notification. </summary>
/// <param name="volume">Volume</param>
public static void PlayAudio(float volume)
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "new_notification" },
{ "audio", "audio" },
{ "audio_volume", volume }
}.ToJsonString());
AudioEndedCounter = 0;
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "pause" command to every connected HTTP client. </summary>
public static void Pause()
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "pause" },
}.ToJsonString());
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "resume" command to every connected HTTP client. </summary>
public static void Resume()
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "resume" },
}.ToJsonString());
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
/// <summary> Sends "gamba animation" command to every connected HTTP client. </summary>
/// <param name="animationFilePath">Relative path to a file with animation that should be played</param>
/// <param name="name">Name of a chatter that does the gamba</param>
/// <param name="value">Amount of gambled points</param>
public static void GambaAnimation(string animationFilePath, string name, int points_rolled, int points_received)
{
var msg = Encoding.UTF8.GetBytes(new JsonObject()
{
{ "type", "gamba_animation" },
{ "gamba", animationFilePath },
{ "gamba_name", name },
{ "gamba_points_rolled", points_rolled },
{ "gamba_points_received", points_received },
}.ToJsonString());
lock (WsSendQueue)
{
WsSendQueue.Add(msg);
}
}
public static string GetFileOrEmbedded(string name)
{
string data = string.Empty;
var file = new FileInfo($"server/{name}");
// If the file exists return it's content, otherwise get embedded data
if (file.Exists) { data = File.ReadAllText(file.FullName); }
else
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"AbevBot.server.{name}");
if (stream is null) { Log.Error("File {file} not found!", file.FullName); }
else
{
using var reader = new StreamReader(stream);
data = reader.ReadToEnd();
}
}
return data;
}
}
/// <summary> HTTP server WebSocket "wrapper". </summary>
public class WebSocketConnection
{
/// <summary> The connection. </summary>
public WebSocket Conn { get; init; }
/// <summary> Connection receive async task. </summary>
public Task<WebSocketReceiveResult> ReceiveTask { get; set; }
/// <summary> Receive buffer. </summary>
public byte[] ReceiveBuffer { get; set; } = new byte[65535];
/// <summary> Connection send async task. </summary>
public Task SendTask { get; set; }
/// <summary> Send buffer. </summary>
public byte[] SendBuffer { get; set; }
/// <summary> Creates new HTTP server WebSocket "wrapper". </summary>
/// <param name="ws">WebSocket connection</param>
public WebSocketConnection(WebSocket ws) { Conn = ws; }
}