-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKickChatClient.cs
More file actions
148 lines (119 loc) · 4.55 KB
/
KickChatClient.cs
File metadata and controls
148 lines (119 loc) · 4.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
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using KickChatSpy.Models;
namespace KickChatSpy;
public class KickChatClient
{
private static readonly Uri WebSocketUri = new("wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679");
private ClientWebSocket _ws;
private CancellationTokenSource _cts;
private readonly ChatroomLookupService _lookupService = new();
public bool IsConnected => _ws != null && _ws.State == WebSocketState.Open;
public event Action<ChatMessage> OnMessageReceived;
public async Task ConnectToChatroomAsync(string channelname)
{
if (string.IsNullOrWhiteSpace(channelname))
throw new ArgumentException("Channel name is required.", nameof(channelname));
var chatroomId = await _lookupService.GetChatroomIdAsync(channelname);
if (!chatroomId.HasValue)
throw new InvalidOperationException($"Chatroom '{channelname}' not found.");
Console.WriteLine($"Found chatroom ID: {chatroomId.Value} for channel '{channelname}'");
await ConnectToChatroomAsync(chatroomId.Value);
}
public async Task ConnectToChatroomAsync(long chatroomNumber)
{
if (IsConnected)
throw new InvalidOperationException("Already connected.");
_ws = new ClientWebSocket();
_cts = new CancellationTokenSource();
await _ws.ConnectAsync(WebSocketUri, _cts.Token);
//Console.WriteLine($"Connected to chatroom: {chatroomNumber}");
await SubscribeToChannelsAsync(chatroomNumber);
_ = Task.Run(() => StartReceivingMessagesAsync(_cts.Token));
}
public async Task DisconnectAsync()
{
if (!IsConnected) return;
_cts?.Cancel();
try
{
await _ws!.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client disconnecting", CancellationToken.None);
}
catch
{
Console.WriteLine("Error while closing WebSocket connection.");
}
_ws?.Dispose();
_ws = null;
_cts?.Dispose();
_cts = null;
Console.WriteLine("Disconnected from chatroom.");
}
private async Task SubscribeToChannelsAsync(long chatroomNumber)
{
string[] channels =
[
$"chatroom_{chatroomNumber}",
$"chatrooms.{chatroomNumber}.v2"
];
foreach (var channel in channels)
{
var payload = new
{
@event = "pusher:subscribe",
data = new
{
auth = "",
channel = channel
}
};
string json = JsonSerializer.Serialize(payload);
var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(json));
await _ws.SendAsync(buffer, WebSocketMessageType.Text, true, _cts!.Token);
//Console.WriteLine($"Subscribed to: {channel}");
}
}
private async Task StartReceivingMessagesAsync(CancellationToken cancellationToken)
{
var buffer = new byte[8192];
var sb = new StringBuilder();
while (!cancellationToken.IsCancellationRequested && _ws?.State == WebSocketState.Open)
{
try
{
sb.Clear();
WebSocketReceiveResult result;
do
{
result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
if (result.MessageType == WebSocketMessageType.Close)
break;
sb.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
}
while (!result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Close)
break;
var json = sb.ToString();
var pusherMsg = JsonSerializer.Deserialize<PusherMessage>(json);
if (pusherMsg?.Event?.Contains("ChatMessageEvent") == true)
{
var chatMsg = JsonSerializer.Deserialize<ChatMessage>(pusherMsg.Data);
if (chatMsg != null)
{
OnMessageReceived?.Invoke(chatMsg);
}
}
}
catch (JsonException)
{
//Console.WriteLine($"[JSON] {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"[ReceiveError] {ex.Message}");
}
}
Console.WriteLine("Stopped receiving messages.");
}
}