-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwitchIRC.cs
202 lines (172 loc) · 6.53 KB
/
TwitchIRC.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
using NLog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TwitchTTS
{
enum TwitchIRCStatus
{
Offline,
Connecting,
WaitingForAck,
ConnectionFailed,
Timeout,
Online
}
class TwitchIRC
{
private static Logger logger;
public string oauth = "";
public string nickName = "";
public string channelName = "";
private string server = "irc.twitch.tv";
private int port = 6667;
private string buffer = string.Empty;
private ConcurrentQueue<string> commandQueue = new ConcurrentQueue<string>();
private ConcurrentQueue<string> receivedMsgs = new ConcurrentQueue<string>();
private Thread workerThread;
public Func<string,bool> MessageReceived = (m) => true;
public Func<bool> IsSpeakerBusy = () => false;
public event EventHandler<TwitchIRCStatus> ConnectionStatusChanged;
TcpClient networkSocket;
private TwitchIRCStatus currentStatus = TwitchIRCStatus.Offline;
private NetworkStream networkStream;
private StreamReader inputStream;
private StreamWriter outputStream;
private DateTime lastCommand = new DateTime();
private static TimeSpan commandThrottleTimeSpan = TimeSpan.FromMilliseconds(1750);
private CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
internal TwitchIRCStatus CurrentStatus
{
get => currentStatus; set
{
currentStatus = value;
ConnectionStatusChanged?.Invoke(this, value);
}
}
public TwitchIRC(string nickname, string channelname, string oauthtoken)
{
logger = Program.LogFactory.GetLogger("irc");
nickName = nickname;
channelName = channelname;
oauth = oauthtoken;
}
public void Start()
{
logger.Info("Connecting...");
CurrentStatus = TwitchIRCStatus.Connecting;
networkSocket = new System.Net.Sockets.TcpClient();
networkSocket.Connect(server, port);
if (!networkSocket.Connected)
{
logger.Fatal("Failed to connect!");
return;
}
logger.Info("Connected!");
CurrentStatus = TwitchIRCStatus.WaitingForAck;
networkStream = networkSocket.GetStream();
inputStream = new System.IO.StreamReader(networkStream);
outputStream = new System.IO.StreamWriter(networkStream);
workerThread = new Thread(BackgroundProcessingDoWork) { IsBackground = true, Name = "TwitchTTS Background" };
workerThread.Start(CancellationTokenSource.Token);
//Send PASS & NICK.
outputStream.WriteLine("PASS " + oauth);
outputStream.WriteLine("NICK " + nickName.ToLower());
outputStream.WriteLine("CAP REQ :twitch.tv/tags");
outputStream.Flush();
}
public void Stop()
{
if (workerThread != null && workerThread.IsAlive)
{
CancellationTokenSource.Cancel();
if (networkSocket.Connected)
{
networkSocket.Close();
}
workerThread.Join();
}
}
public void SendCommand(string cmd)
{
commandQueue.Enqueue(cmd);
}
public void SendMsg(string msg)
{
commandQueue.Enqueue("PRIVMSG #" + channelName + " :" + msg);
}
public void SendTaggedMsg(string tagWho, string msg)
{
commandQueue.Enqueue("PRIVMSG #" + channelName + " :@" + tagWho + " " + msg);
}
private DateTime LastPing = DateTime.Now;
public void BackgroundProcessingDoWork(object argument)
{
CancellationToken token = (CancellationToken)argument;
while (!token.IsCancellationRequested)
{
if (networkStream.DataAvailable)
{
buffer = inputStream.ReadLine();
logger.Debug(buffer);
//was message?
if (buffer.Contains("PRIVMSG #"))
{
//MessageReceived?.BeginInvoke(workerThread, buffer, null, null);
receivedMsgs.Enqueue(buffer);
}
//Send pong reply to any ping messages
if (buffer.StartsWith("PING "))
{
LastPing = DateTime.Now;
SendCommand(buffer.Replace("PING", "PONG"));
}
//After server sends 001 command, we can join a channel
if (buffer.Split(' ')[1] == "001")
{
SendCommand("JOIN #" + channelName);
CurrentStatus = TwitchIRCStatus.Online;
}
}
if (DateTime.Now - LastPing > TimeSpan.FromMinutes(8))
{
CurrentStatus = TwitchIRCStatus.Timeout;
break;
}
if (CurrentStatus == TwitchIRCStatus.WaitingForAck && DateTime.Now - LastPing > TimeSpan.FromSeconds(15))
{
CurrentStatus = TwitchIRCStatus.ConnectionFailed;
break;
}
if (!receivedMsgs.IsEmpty && !IsSpeakerBusy())
{
while (receivedMsgs.TryDequeue(out string msg))
{
if (!MessageReceived(msg))
{
receivedMsgs.Enqueue(msg);
break;
}
}
}
if (!commandQueue.IsEmpty && DateTime.Now - lastCommand > commandThrottleTimeSpan)
{
while (commandQueue.TryDequeue(out string command))
{
logger.Debug($"Sending '{command}'");
outputStream.WriteLine(command);
outputStream.Flush();
lastCommand = DateTime.Now;
}
}
Thread.Sleep(100);
}
}
}
}