forked from Inumedia/SlackAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlackSocket.cs
338 lines (308 loc) · 13.6 KB
/
SlackSocket.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
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
using System.IO;
using Newtonsoft.Json;
using SlackAPI.Utilities;
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace SlackAPI
{
public class SlackSocket
{
LockFreeQueue<string> sendingQueue;
int currentlySending;
int closedEmitted;
CancellationTokenSource cts;
Dictionary<int, Action<string>> callbacks;
internal ClientWebSocket socket;
int currentId;
Dictionary<string, Dictionary<string, Delegate>> routes;
public bool Connected { get { return socket != null && socket.State == WebSocketState.Open; } }
public event Action<WebSocketException> ErrorSending;
public event Action<WebSocketException> ErrorReceiving;
public event Action<Exception> ErrorReceivingDesiralization;
public event Action<Exception> ErrorHandlingMessage;
public event Action ConnectionClosed;
//This would be done for hinting but I don't think we really need this.
static Dictionary<string, Dictionary<string, Type>> routing;
static SlackSocket()
{
routing = new Dictionary<string, Dictionary<string, Type>>();
foreach (Assembly assy in AppDomain.CurrentDomain.GetAssemblies())
{
if (!assy.GlobalAssemblyCache)
foreach (Type t in assy.GetTypes())
foreach (SlackSocketRouting route in t.GetCustomAttributes<SlackSocketRouting>())
{
if (!routing.ContainsKey(route.Type))
routing.Add(route.Type, new Dictionary<string, Type>()
{
{route.SubType ?? "null", t}
});
else
if (!routing[route.Type].ContainsKey(route.SubType ?? "null"))
routing[route.Type].Add(route.SubType ?? "null", t);
else
throw new InvalidProgramException("Cannot have two socket message types with the same type and subtype!");
}
}
}
public SlackSocket(LoginResponse loginDetails, object routingTo, Action onConnected = null)
{
BuildRoutes(routingTo);
socket = new ClientWebSocket();
callbacks = new Dictionary<int, Action<string>>();
sendingQueue = new LockFreeQueue<string>();
currentId = 1;
cts = new CancellationTokenSource();
socket.ConnectAsync(new Uri(string.Format("{0}?svn_rev={1}&login_with_boot_data-0-{2}&on_login-0-{2}&connect-1-{2}", loginDetails.url, loginDetails.svn_rev, DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds)), cts.Token).Wait();
if(onConnected != null)
onConnected();
SetupReceiving();
}
void BuildRoutes(object routingTo)
{
routes = new Dictionary<string, Dictionary<string, Delegate>>();
Type routingToType = routingTo.GetType();
Type slackMessage = typeof(SlackSocketMessage);
foreach (MethodInfo m in routingTo.GetType().GetMethods(BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public))
{
ParameterInfo[] parameters = m.GetParameters();
if (parameters.Length != 1) continue;
if (parameters[0].ParameterType.IsSubclassOf(slackMessage))
{
Type t = parameters[0].ParameterType;
foreach (SlackSocketRouting route in t.GetCustomAttributes<SlackSocketRouting>())
{
Type genericAction = typeof(Action<>).MakeGenericType(parameters[0].ParameterType);
Delegate d = Delegate.CreateDelegate(genericAction, routingTo, m, false);
if (d == null)
{
System.Diagnostics.Debug.WriteLine(string.Format("Couldn't create delegate for {0}.{1}", routingToType.FullName, m.Name));
continue;
}
if (!routes.ContainsKey(route.Type))
routes.Add(route.Type, new Dictionary<string, Delegate>());
if (!routes[route.Type].ContainsKey(route.SubType ?? "null"))
routes[route.Type].Add(route.SubType ?? "null", d);
else
routes[route.Type][route.SubType ?? "null"] = Delegate.Combine(routes[route.Type][route.SubType ?? "null"], d);
}
}
}
}
public void Send<K>(SlackSocketMessage message, Action<K> callback)
where K : SlackSocketMessage
{
int sendingId = Interlocked.Increment(ref currentId);
message.id = sendingId;
callbacks.Add(sendingId, (c) =>
{
K obj = c.Deserialize<K>();
callback(obj);
});
Send(message);
}
public void Send(SlackSocketMessage message)
{
if (message.id == 0)
message.id = Interlocked.Increment(ref currentId);
//socket.Send(JsonConvert.SerializeObject(message));
if (string.IsNullOrEmpty(message.type)){
IEnumerable<SlackSocketRouting> routes = message.GetType().GetCustomAttributes<SlackSocketRouting>();
SlackSocketRouting route = null;
foreach (SlackSocketRouting r in routes)
{
route = r;
}
if (route == null) throw new InvalidProgramException("Cannot send without a proper route!");
else
{
message.type = route.Type;
message.subtype = route.SubType;
}
}
sendingQueue.Push(JsonConvert.SerializeObject(message, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
if (Interlocked.CompareExchange(ref currentlySending, 1, 0) == 0)
ThreadPool.QueueUserWorkItem(HandleSending);
}
public void BindCallback<K>(Action<K> callback)
{
Type t = typeof(K);
foreach (SlackSocketRouting route in t.GetCustomAttributes<SlackSocketRouting>())
{
if (!routes.ContainsKey(route.Type))
routes.Add(route.Type, new Dictionary<string, Delegate>());
if (!routes[route.Type].ContainsKey(route.SubType ?? "null"))
routes[route.Type].Add(route.SubType ?? "null", callback);
else
routes[route.Type][route.SubType ?? "null"] = Delegate.Combine(routes[route.Type][route.SubType ?? "null"], callback);
}
}
public void UnbindCallback<K>(Action<K> callback)
{
Type t = typeof(K);
foreach (SlackSocketRouting route in t.GetCustomAttributes<SlackSocketRouting>())
{
Delegate d = routes.ContainsKey(route.Type) ? (routes.ContainsKey(route.SubType ?? "null") ? routes[route.Type][route.SubType ?? "null"] : null) : null;
if (d != null)
{
Delegate newd = Delegate.Remove(d, callback);
routes[route.Type][route.SubType ?? "null"] = newd;
}
}
}
void SetupReceiving()
{
Task.Factory.StartNew(
async () =>
{
List<byte[]> buffers = new List<byte[]>();
byte[] bytes = new byte[1024];
buffers.Add(bytes);
ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);
while (socket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = null;
try
{
result = await socket.ReceiveAsync(buffer, cts.Token);
}
catch (WebSocketException wex)
{
if (ErrorReceiving != null)
ErrorReceiving(wex);
Close();
break;
}
if (!result.EndOfMessage && buffer.Count == buffer.Array.Length)
{
bytes = new byte[1024];
buffers.Add(bytes);
buffer = new ArraySegment<byte>(bytes);
continue;
}
string data = string.Join("", buffers.Select((c) => Encoding.UTF8.GetString(c).TrimEnd('\0')));
//Console.WriteLine("SlackSocket data = " + data);
SlackSocketMessage message = null;
try
{
message = data.Deserialize<SlackSocketMessage>();
}
catch (JsonException jsonExcep)
{
if (ErrorReceivingDesiralization != null)
ErrorReceivingDesiralization(jsonExcep);
continue;
}
if (message == null)
continue;
else
{
HandleMessage(message, data);
buffers = new List<byte[]>();
bytes = new byte[1024];
buffers.Add(bytes);
buffer = new ArraySegment<byte>(bytes);
}
}
}, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
void HandleMessage(SlackSocketMessage message, string data)
{
if (callbacks.ContainsKey(message.reply_to))
callbacks[message.reply_to](data);
else if (routes.ContainsKey(message.type) && routes[message.type].ContainsKey(message.subtype ?? "null"))
{
try
{
object o = null;
if (routing.ContainsKey(message.type) &&
routing[message.type].ContainsKey(message.subtype ?? "null"))
o = data.Deserialize(routing[message.type][message.subtype ?? "null"]);
else
{
//I believe this method is slower than the former. If I'm wrong we can just use this instead. :D
Type t = routes[message.type][message.subtype ?? "null"].Method.GetParameters()[0].ParameterType;
o = data.Deserialize(t);
}
routes[message.type][message.subtype ?? "null"].DynamicInvoke(o);
}
catch (Exception e)
{
if (ErrorHandlingMessage != null)
ErrorHandlingMessage(e);
throw e;
}
}
else
{
System.Diagnostics.Debug.WriteLine(string.Format("No valid route for {0} - {1}", message.type, message.subtype ?? "null"));
if (ErrorHandlingMessage != null)
ErrorHandlingMessage(new InvalidDataException(string.Format("No valid route for {0} - {1}", message.type, message.subtype ?? "null")));
}
}
void HandleSending(object stateful)
{
string message;
while (sendingQueue.Pop(out message) && socket.State == WebSocketState.Open && !cts.Token.IsCancellationRequested)
{
byte[] sending = Encoding.UTF8.GetBytes(message);
ArraySegment<byte> buffer = new ArraySegment<byte>(sending);
try
{
socket.SendAsync(buffer, WebSocketMessageType.Text, true, cts.Token).Wait();
}
catch (WebSocketException wex)
{
if (ErrorSending != null)
ErrorSending(wex);
Close();
break;
}
}
currentlySending = 0;
}
public void Close()
{
try
{
this.socket.Abort();
}
catch (Exception ex)
{
}
if (Interlocked.CompareExchange(ref closedEmitted, 1, 0) == 0 && ConnectionClosed != null)
ConnectionClosed();
}
}
public class SlackSocketMessage
{
public int id;
public int reply_to;
public string type;
public string subtype;
public bool ok = true;
public Error error;
}
public class Error
{
public int code;
public string msg;
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class SlackSocketRouting : Attribute
{
public string Type;
public string SubType;
public SlackSocketRouting(string type, string subtype = null)
{
this.Type = type;
this.SubType = subtype;
}
}
}