forked from JustDerb/Tiltify-Client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTiltifyWebSocket.cs
More file actions
404 lines (370 loc) · 15.1 KB
/
TiltifyWebSocket.cs
File metadata and controls
404 lines (370 loc) · 15.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
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Timers;
using Tiltify.Events;
using Tiltify.Models;
using Timer = System.Timers.Timer;
namespace Tiltify
{
public class TiltifyWebSocket
{
/// <summary>
/// The socket
/// </summary>
private readonly WebSocketClient _socket;
public bool IsConnected => _socket.IsConnected;
/// <summary>
/// The previous requests
/// </summary>
private readonly List<PreviousRequest> _previousRequests = new List<PreviousRequest>();
/// <summary>
/// The previous requests semaphore
/// </summary>
private readonly Semaphore _previousRequestsSemaphore = new Semaphore(1, 1);
/// <summary>
/// The logger
/// </summary>
private readonly ILogger<TiltifyWebSocket> _logger;
/// <summary>
/// The ping timer
/// </summary>
private readonly Timer _pingTimer = new Timer();
/// <summary>
/// The pong timer
/// </summary>
private readonly Timer _pongTimer = new Timer();
/// <summary>
/// The pong received
/// </summary>
private bool _pongReceived = false;
/// <summary>
/// The topic list
/// </summary>
private readonly List<string> _topicList = new List<string>();
private readonly Dictionary<string, string> _topicToChannelId = new Dictionary<string, string>();
private int websocketMessageId = 16;
#region Events
/// <summary>
/// Fires when this client receives any data from Tiltify
/// </summary>
public event EventHandler<OnLogArgs> OnLog;
/// <inheritdoc />
/// <summary>
/// Fires when Tiltify Service is connected.
/// </summary>
public event EventHandler OnTiltifyServiceConnected;
/// <inheritdoc />
/// <summary>
/// Fires when Tiltify Service is closed.
/// </summary>
public event EventHandler OnTiltifyServiceClosed;
/// <summary>
/// Occurs when [on pub sub service error].
/// </summary>
event EventHandler<OnTiltifyServiceErrorArgs> OnTiltifyServiceError;
/// <inheritdoc />
/// <summary>
/// Fires when Tiltify receives any response.
/// </summary>
public event EventHandler<OnListenResponseArgs> OnListenResponse;
public event EventHandler<OnCampaignDonationArgs> OnCampaignDonation;
#endregion
/// <summary>
/// Constructor for a client that interface's with Tiltify's websocket.
/// </summary>
public TiltifyWebSocket(ILogger<TiltifyWebSocket> logger = null, WebSocketClientOptions options = null)
{
_logger = logger;
_socket = new WebSocketClient(options);
_socket.OnConnected += Socket_OnConnected;
_socket.OnError += OnError;
_socket.OnMessage += OnMessage;
_socket.OnDisconnected += Socket_OnDisconnected;
_pongTimer.Interval = 10000;
_pongTimer.Elapsed += PongTimerTick;
}
/// <summary>
/// Handles the <see cref="E:OnError" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="OnErrorEventArgs"/> instance containing the event data.</param>
private void OnError(object sender, OnErrorEventArgs e)
{
_logger?.LogError($"OnError in Tiltify Websocket connection occured! Exception: {e.Exception}");
OnTiltifyServiceError?.Invoke(this, new OnTiltifyServiceErrorArgs { Exception = e.Exception });
}
/// <summary>
/// Handles the <see cref="E:OnMessage" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="OnMessageEventArgs"/> instance containing the event data.</param>
private void OnMessage(object sender, OnMessageEventArgs e)
{
_logger?.LogDebug($"Received Websocket OnMessage: {e.Message}");
OnLog?.Invoke(this, new OnLogArgs { Data = e.Message });
ParseMessage(e.Message);
}
/// <summary>
/// Handles the OnDisconnected event of the Socket control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void Socket_OnDisconnected(object sender, EventArgs e)
{
_logger?.LogWarning("Tiltify Websocket connection closed");
_pingTimer.Stop();
_pongTimer.Stop();
OnTiltifyServiceClosed?.Invoke(this, null);
}
/// <summary>
/// Handles the OnConnected event of the Socket control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void Socket_OnConnected(object sender, EventArgs e)
{
_logger?.LogInformation("Tiltify Websocket connection established");
_pingTimer.Interval = 30000;
_pingTimer.Elapsed += PingTimerTick;
_pingTimer.Start();
OnTiltifyServiceConnected?.Invoke(this, null);
}
/// <summary>
/// Pings the timer tick.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ElapsedEventArgs"/> instance containing the event data.</param>
private void PingTimerTick(object sender, ElapsedEventArgs e)
{
//Reset pong state.
_pongReceived = false;
var messageId = GenerateMessageId();
//Send ping.
var data = new JArray(
null,
messageId,
"phoenix",
"heartbeat",
new JObject()
);
_socket.Send(data.ToString());
//Start pong timer.
_pongTimer.Start();
}
/// <summary>
/// Pongs the timer tick.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ElapsedEventArgs"/> instance containing the event data.</param>
private void PongTimerTick(object sender, ElapsedEventArgs e)
{
//Stop the pong timer.
_pongTimer.Stop();
if (_pongReceived)
{
//If we received a pong we're good.
_pongReceived = false;
}
else
{
//Otherwise we're disconnected so close the socket.
_socket.Close();
}
}
/*
* Heartbeat required every 30 seconds
* JOIN: ["27","27","fact.165613.donation","phx_join",{}]
* JOIN REPLY: ["27","27","fact.165613.donation","phx_reply",{"response":{},"status":"ok"}]
* HEARTBEAT: [null,"32","phoenix","heartbeat",{}]
* HEARTBEAT REPLY: [null,"32","phoenix","phx_reply",{"response":{},"status":"ok"}]
* LEAVE: ["27","28","fact.165613.donation","phx_leave",{}]
* LEAVE REPLY: ["27","28","fact.165613.donation","phx_reply",{"response":{},"status":"ok"}]
* CLOSE REPLY: ["27","27","fact.165613.donation","phx_close",{}]
* DONATION: [null,null,"fact.165613.donation","donation",{"amount":37.0,"challenge_id":31290,"comment":"Muensterous cheese puns! I may not be that sharp, but this is no gouda! Swiss entire idea is full of holes! Cheddar get out of here before I make a pun myself...\n((And of course, as ever and always, Trans Rights!!!))","completedAt":1649552307000,"event_id":165613,"id":5827276,"name":"N0nb1naryCode","poll_option_id":39030,"reward_id":null,"updatedAt":1649552307000}]
* DONATION: [null,null,"fact.165613.donation","donation",{"amount":12.0,"challenge_id":31290,"comment":"Let's gooooooo! Animals in balls? Running crazy races? We need this!","completedAt":1649553051000,"event_id":165613,"id":5827305,"name":"TrainerAnade","poll_option_id":39031,"reward_id":null,"updatedAt":1649553051000}]
* DONATION: [null,null,"fact.165613.donation","donation",{"amount":21.0,"challenge_id":31290,"comment":"Things and stuff! Trans Rights! I don't have anything clever to add!!","completedAt":1649553226000,"event_id":165613,"id":5827315,"name":"N0nb1naryCode","poll_option_id":39030,"reward_id":null,"updatedAt":1649553226000}]
*/
/// <summary>
/// Parses the message.
/// </summary>
/// <param name="message">The message.</param>
private void ParseMessage(string message)
{
var resp = new WebSocketResponse(message);
if (resp.Topic == null)
{
return;
}
if (int.TryParse(resp.JoinId, out int joinId)) {
int highestId = Math.Max(websocketMessageId, joinId);
Interlocked.Exchange(ref websocketMessageId, highestId);
}
var topicParts = resp.Topic.Split('.');
switch (resp.Event?.ToLower())
{
case "phx_close":
_socket.Close();
return;
case "phx_reply":
if ("phoenix".Equals(resp.Topic))
{
// Heartbeat
_pongReceived = true;
return;
}
if (_previousRequests.Count != 0)
{
bool handled = false;
_previousRequestsSemaphore.WaitOne();
try
{
for (int i = 0; i < _previousRequests.Count;)
{
var request = _previousRequests[i];
if (string.Equals(request.MessageId, resp.MessageId, StringComparison.CurrentCulture))
{
//Remove the request.
_previousRequests.RemoveAt(i);
_topicToChannelId.TryGetValue(request.Topic, out var requestChannelId);
OnListenResponse?.Invoke(this, new OnListenResponseArgs { Response = resp, Topic = request.Topic, Successful = true, ChannelId = requestChannelId });
handled = true;
}
else
{
i++;
}
}
}
finally
{
_previousRequestsSemaphore.Release();
}
if (handled) return;
}
break;
case "donation":
if (topicParts.Length < 3)
{
break;
}
if ("fact".Equals(topicParts[0]) && "donation".Equals(topicParts[2]))
{
var donation = resp.Data.ToObject<WebSocketDonationInformation>();
OnCampaignDonation?.Invoke(this, new OnCampaignDonationArgs { Donation = donation });
return;
}
break;
case "reconnect": _socket.Close(); break;
}
UnaccountedFor(message);
}
/// <summary>
/// The random
/// </summary>
private static readonly Random Random = new Random();
/// <summary>
/// Generates the nonce.
/// </summary>
/// <returns>System.String.</returns>
private string GenerateMessageId()
{
return Interlocked.Increment(ref websocketMessageId).ToString();
}
/// <summary>
/// Listens to topic.
/// </summary>
/// <param name="topic">The topic.</param>
private void ListenToTopic(string topic)
{
_topicList.Add(topic);
}
/// <summary>
/// Listen to multiple topics.
/// </summary>
/// <param name="topics">The topics</param>
private void ListenToTopics(params string[] topics)
{
foreach (var topic in topics)
{
_topicList.Add(topic);
}
}
/// <inheritdoc />
/// <summary>
/// Sends the topics.
/// </summary>
/// <param name="unlisten">if set to <c>true</c> [unlisten].</param>
public void SendTopics(bool unlisten = false)
{
var messageId = GenerateMessageId();
var topics = new List<string>();
_previousRequestsSemaphore.WaitOne();
try
{
foreach (var val in _topicList)
{
_previousRequests.Add(new PreviousRequest(messageId, val));
topics.Add(val);
}
}
finally
{
_previousRequestsSemaphore.Release();
}
foreach (var topic in topics)
{
var jsonData = new JArray(
messageId,
messageId,
topic,
!unlisten ? "phx_join" : "phx_leave",
new JObject()
);
_socket.Send(jsonData.ToString());
}
_topicList.Clear();
}
/// <summary>
/// Unaccounted for.
/// </summary>
/// <param name="message">The message.</param>
private void UnaccountedFor(string message)
{
_logger?.LogInformation($"[Tiltify] [Unaccounted] {message}");
}
#region Listeners
/// <inheritdoc />
/// <summary>
/// Sends a request to listenOn follows coming into a specified channel.
/// </summary>
/// <param name="campaignId">The campaign identifier.</param>
public void ListenToCampaignDonations(string campaignId)
{
// fact.165613.donation
var topic = $"fact.{campaignId}.donation";
_topicToChannelId[topic] = campaignId;
ListenToTopic(topic);
}
#endregion
/// <inheritdoc />
/// <summary>
/// Method to connect to Tiltify's service. You MUST listen toOnConnected event and listen to a Topic within 15 seconds of connecting (or be disconnected)
/// </summary>
public void Connect()
{
_socket.Open();
}
/// <inheritdoc />
/// <summary>
/// What do you think it does? :)
/// </summary>
public void Disconnect()
{
_socket.Close();
}
}
}