forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerEventsFeature.cs
More file actions
808 lines (672 loc) · 27.5 KB
/
Copy pathServerEventsFeature.cs
File metadata and controls
808 lines (672 loc) · 27.5 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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using ServiceStack.Auth;
using ServiceStack.Host.Handlers;
using ServiceStack.Logging;
using ServiceStack.Web;
namespace ServiceStack
{
public class ServerEventsFeature : IPlugin
{
public string StreamPath { get; set; }
public string HeartbeatPath { get; set; }
public string SubscribersPath { get; set; }
public string UnRegisterPath { get; set; }
public TimeSpan IdleTimeout { get; set; }
public TimeSpan HeartbeatInterval { get; set; }
public Action<IRequest> OnInit { get; set; }
public Action<IRequest> OnHeartbeatInit { get; set; }
public Action<IEventSubscription, IRequest> OnCreated { get; set; }
public Action<IEventSubscription, Dictionary<string, string>> OnConnect { get; set; }
public Action<IEventSubscription> OnSubscribe { get; set; }
public Action<IEventSubscription> OnUnsubscribe { get; set; }
public Action<IResponse, string> OnPublish { get; set; }
public bool NotifyChannelOfSubscriptions { get; set; }
public bool LimitToAuthenticatedUsers { get; set; }
public ServerEventsFeature()
{
StreamPath = "/event-stream";
HeartbeatPath = "/event-heartbeat";
UnRegisterPath = "/event-unregister";
SubscribersPath = "/event-subscribers";
IdleTimeout = TimeSpan.FromSeconds(30);
HeartbeatInterval = TimeSpan.FromSeconds(10);
NotifyChannelOfSubscriptions = true;
}
public void Register(IAppHost appHost)
{
var broker = new MemoryServerEvents
{
IdleTimeout = IdleTimeout,
OnSubscribe = OnSubscribe,
OnUnsubscribe = OnUnsubscribe,
NotifyChannelOfSubscriptions = NotifyChannelOfSubscriptions,
};
var container = appHost.GetContainer();
if (container.TryResolve<IServerEvents>() == null)
container.Register<IServerEvents>(broker);
appHost.RawHttpHandlers.Add(httpReq =>
httpReq.PathInfo.EndsWith(StreamPath)
? (IHttpHandler)new ServerEventsHandler()
: httpReq.PathInfo.EndsWith(HeartbeatPath)
? new ServerEventsHeartbeatHandler()
: null);
if (UnRegisterPath != null)
{
appHost.RegisterService(typeof(ServerEventsUnRegisterService), UnRegisterPath);
}
if (SubscribersPath != null)
{
appHost.RegisterService(typeof(ServerEventsSubscribersService), SubscribersPath);
}
}
}
public class ServerEventsHandler : HttpAsyncTaskHandler
{
public override bool RunAsAsync()
{
return true;
}
public override Task ProcessRequestAsync(IRequest req, IResponse res, string operationName)
{
var feature = HostContext.GetPlugin<ServerEventsFeature>();
var session = req.GetSession();
if (feature.LimitToAuthenticatedUsers && !session.IsAuthenticated)
{
session.ReturnFailedAuthentication(req);
return EmptyTask;
}
res.ContentType = MimeTypes.ServerSentEvents;
res.AddHeader(HttpHeaders.CacheControl, "no-cache");
res.ApplyGlobalResponseHeaders();
res.UseBufferedStream = false;
res.KeepAlive = true;
if (feature.OnInit != null)
feature.OnInit(req);
res.Flush();
var serverEvents = req.TryResolve<IServerEvents>();
var userAuthId = session != null ? session.UserAuthId : null;
var anonUserId = serverEvents.GetNextSequence("anonUser");
var userId = userAuthId ?? ("-" + anonUserId);
var displayName = session.GetSafeDisplayName()
?? "user" + anonUserId;
var now = DateTime.UtcNow;
var subscriptionId = SessionExtensions.CreateRandomSessionId();
var subscription = new EventSubscription(res)
{
CreatedAt = now,
LastPulseAt = now,
Channel = req.QueryString["channel"] ?? EventSubscription.UnknownChannel,
SubscriptionId = subscriptionId,
UserId = userId,
UserName = session != null ? session.UserName : null,
DisplayName = displayName,
SessionId = req.GetPermanentSessionId(),
IsAuthenticated = session != null && session.IsAuthenticated,
OnPublish = feature.OnPublish,
Meta = {
{ "userId", userId },
{ "displayName", displayName },
{ AuthMetadataProvider.ProfileUrlKey, session.GetProfileUrl() ?? AuthMetadataProvider.DefaultNoProfileImgUrl },
}
};
if (feature.OnCreated != null)
feature.OnCreated(subscription, req);
var heartbeatUrl = req.ResolveAbsoluteUrl("~/".CombineWith(feature.HeartbeatPath))
.AddQueryParam("id", subscriptionId);
var unRegisterUrl = req.ResolveAbsoluteUrl("~/".CombineWith(feature.UnRegisterPath))
.AddQueryParam("id", subscriptionId);
var privateArgs = new Dictionary<string, string>(subscription.Meta) {
{"id", subscriptionId },
{"unRegisterUrl", unRegisterUrl},
{"heartbeatUrl", heartbeatUrl},
{"heartbeatIntervalMs", ((long)feature.HeartbeatInterval.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) },
{"idleTimeoutMs", ((long)feature.IdleTimeout.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)}
};
if (feature.OnConnect != null)
feature.OnConnect(subscription, privateArgs);
serverEvents.Register(subscription, privateArgs);
var tcs = new TaskCompletionSource<bool>();
subscription.OnDispose = _ =>
{
try
{
res.EndHttpHandlerRequest(skipHeaders: true);
}
catch { }
tcs.SetResult(true);
};
return tcs.Task;
}
}
public class ServerEventsHeartbeatHandler : HttpAsyncTaskHandler
{
public override bool RunAsAsync() { return true; }
public override Task ProcessRequestAsync(IRequest req, IResponse res, string operationName)
{
res.ApplyGlobalResponseHeaders();
var feature = HostContext.GetPlugin<ServerEventsFeature>();
if (feature.OnHeartbeatInit != null)
feature.OnHeartbeatInit(req);
var subscriptionId = req.QueryString["id"];
if (!req.TryResolve<IServerEvents>().Pulse(subscriptionId))
{
res.StatusCode = 404;
res.StatusDescription = "Subscription {0} does not exist".Fmt(subscriptionId);
}
res.EndHttpHandlerRequest(skipHeaders:true);
return EmptyTask;
}
}
public class GetEventSubscribers : IReturn<List<Dictionary<string, string>>>
{
public string Channel { get; set; }
}
[DefaultRequest(typeof(GetEventSubscribers))]
[Restrict(VisibilityTo = RequestAttributes.None)]
public class ServerEventsSubscribersService : Service
{
public IServerEvents ServerEvents { get; set; }
public object Any(GetEventSubscribers request)
{
return ServerEvents.GetSubscriptionsDetails(request.Channel);
}
}
public class UnRegisterEventSubscriber : IReturn<Dictionary<string, string>>
{
public string Id { get; set; }
}
[DefaultRequest(typeof(UnRegisterEventSubscriber))]
[Restrict(VisibilityTo = RequestAttributes.None)]
public class ServerEventsUnRegisterService : Service
{
public IServerEvents ServerEvents { get; set; }
public object Any(UnRegisterEventSubscriber request)
{
var subscription = ServerEvents.GetSubscriptionInfo(request.Id);
if (subscription == null)
throw HttpError.NotFound(ErrorMessages.SubscriptionNotExistsFmt.Fmt(request.Id));
ServerEvents.UnRegister(subscription.SubscriptionId);
return subscription.Meta;
}
}
/*
# Commands
cmd.announce This is your captain speaking ...
cmd.toggle$#channels
# CSS
css.background #eceff1
css.background$#top #673ab7
css.background$#right #fffde7
css.background$#bottom #0091ea
css.color$#me #ff0
css.display$img none
css.display$img inline
# Receivers
document.title New Window Title
window.location http://google.com
cmd.removeReceiver window
cmd.addReceiver window
tv.watch http://youtu.be/518XP8prwZo
tv.watch https://servicestack.net/img/logo-220.png
tv.off
# Triggers
trigger.customEvent arg
*/
public class EventSubscription : SubscriptionInfo, IEventSubscription
{
private static ILog Log = LogManager.GetLogger(typeof(EventSubscription));
public static string UnknownChannel = "*";
public DateTime LastPulseAt { get; set; }
private readonly IResponse response;
private long msgId;
public EventSubscription(IResponse response)
{
this.response = response;
this.Meta = new Dictionary<string, string>();
}
public Action<IEventSubscription> OnUnsubscribe { get; set; }
public Action<IEventSubscription> OnDispose { get; set; }
public Action<IResponse, string> OnPublish { get; set; }
public void Publish(string selector)
{
Publish(selector, null);
}
public void Publish(string selector, string message)
{
try
{
var msg = message ?? "";
var frame = "id: " + Interlocked.Increment(ref msgId) + "\n"
+ "data: " + selector + " " + msg + "\n\n";
lock (response)
{
response.OutputStream.Write(frame);
response.Flush();
if (OnPublish != null)
OnPublish(response, frame);
}
}
catch (Exception ex)
{
Log.Error("Error publishing notification to: " + selector, ex);
Unsubscribe();
}
}
public void Pulse()
{
LastPulseAt = DateTime.UtcNow;
}
public void Unsubscribe()
{
if (OnUnsubscribe != null)
OnUnsubscribe(this);
}
public void Dispose()
{
OnUnsubscribe = null;
try
{
lock (response)
{
response.EndHttpHandlerRequest(skipHeaders: true);
}
}
catch (Exception ex)
{
Log.Error("Error ending subscription response", ex);
}
if (OnDispose != null)
OnDispose(this);
}
}
public interface IEventSubscription : IMeta, IDisposable
{
DateTime CreatedAt { get; set; }
DateTime LastPulseAt { get; set; }
string Channel { get; }
string UserId { get; }
string UserName { get; }
string DisplayName { get; }
string SessionId { get; }
string SubscriptionId { get; }
bool IsAuthenticated { get; set; }
Action<IEventSubscription> OnUnsubscribe { get; set; }
void Unsubscribe();
void Publish(string selector, string message);
void Pulse();
}
public class SubscriptionInfo
{
public DateTime CreatedAt { get; set; }
public string Channel { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string DisplayName { get; set; }
public string SessionId { get; set; }
public string SubscriptionId { get; set; }
public bool IsAuthenticated { get; set; }
public Dictionary<string, string> Meta { get; set; }
}
public class MemoryServerEvents : IServerEvents
{
private static ILog Log = LogManager.GetLogger(typeof(MemoryServerEvents));
public static int DefaultArraySize = 2;
public static int ReSizeMultiplier = 2;
public static int ReSizeBuffer = 20;
public TimeSpan IdleTimeout { get; set; }
public Action<IEventSubscription> OnSubscribe { get; set; }
public Action<IEventSubscription> OnUnsubscribe { get; set; }
public Action<IEventSubscription> NotifyJoin { get; set; }
public Action<IEventSubscription> NotifyLeave { get; set; }
public Action<IEventSubscription> NotifyHeartbeat { get; set; }
public Func<object,string> Serialize { get; set; }
public bool NotifyChannelOfSubscriptions { get; set; }
public ConcurrentDictionary<string, IEventSubscription[]> Subcriptions;
public ConcurrentDictionary<string, IEventSubscription[]> ChannelSubcriptions;
public ConcurrentDictionary<string, IEventSubscription[]> UserIdSubcriptions;
public ConcurrentDictionary<string, IEventSubscription[]> UserNameSubcriptions;
public ConcurrentDictionary<string, IEventSubscription[]> SessionSubcriptions;
public MemoryServerEvents()
{
Reset();
NotifyJoin = s => NotifyChannel(s.Channel, "cmd.onJoin", s.Meta);
NotifyLeave = s => NotifyChannel(s.Channel, "cmd.onLeave", s.Meta);
NotifyHeartbeat = s => NotifyChannel(s.Channel, "cmd.onHeartbeat", s.Meta);
Serialize = o => o != null ? o.ToJson() : null;
}
public void Reset()
{
Subcriptions = new ConcurrentDictionary<string, IEventSubscription[]>();
ChannelSubcriptions = new ConcurrentDictionary<string, IEventSubscription[]>();
UserIdSubcriptions = new ConcurrentDictionary<string, IEventSubscription[]>();
UserNameSubcriptions = new ConcurrentDictionary<string, IEventSubscription[]>();
SessionSubcriptions = new ConcurrentDictionary<string, IEventSubscription[]>();
}
public void Start()
{
}
public void Stop()
{
Reset();
}
public void NotifyAll(string selector, object message)
{
foreach (var entry in Subcriptions)
{
foreach (var sub in entry.Value)
{
if (sub != null)
sub.Publish(selector, Serialize(message));
}
}
}
public void NotifySubscription(string subscriptionId, string selector, object message, string channel = null)
{
Notify(Subcriptions, subscriptionId, selector, message, channel);
}
public void NotifyChannel(string channel, string selector, object message)
{
Notify(ChannelSubcriptions, channel, selector, message, channel);
}
public void NotifyUserId(string userId, string selector, object message, string channel = null)
{
Notify(UserIdSubcriptions, userId, selector, message, channel);
}
public void NotifyUserName(string userName, string selector, object message, string channel = null)
{
Notify(UserNameSubcriptions, userName, selector, message, channel);
}
public void NotifySession(string sspid, string selector, object message, string channel = null)
{
Notify(SessionSubcriptions, sspid, selector, message, channel);
}
protected void Notify(ConcurrentDictionary<string, IEventSubscription[]> map, string key,
string selector, object message, string channel = null)
{
IEventSubscription[] subs;
if (!map.TryGetValue(key, out subs)) return;
var expired = new List<IEventSubscription>();
var now = DateTime.UtcNow;
foreach (var subscription in subs)
{
if (subscription != null && (channel == null || subscription.Channel == channel))
{
if (now - subscription.LastPulseAt > IdleTimeout)
{
expired.Add(subscription);
}
subscription.Publish(selector, Serialize(message));
}
}
foreach (var sub in expired)
{
sub.Unsubscribe();
}
}
public bool Pulse(string id)
{
var sub = GetSubscription(id);
if (sub == null)
return false;
sub.Pulse();
if (NotifyHeartbeat != null)
NotifyHeartbeat(sub);
return true;
}
public IEventSubscription GetSubscription(string id)
{
if (id == null) return null;
foreach (var subs in Subcriptions.Values)
{
foreach (var sub in subs)
{
if (sub != null && sub.SubscriptionId == id)
return sub;
}
}
return null;
}
public SubscriptionInfo GetSubscriptionInfo(string id)
{
return GetSubscription(id).GetInfo();
}
public List<SubscriptionInfo> GetSubscriptionInfosByUserId(string userId)
{
var userSubs = new List<SubscriptionInfo>();
if (userId == null) return userSubs;
foreach (var subs in Subcriptions.Values)
{
foreach (var sub in subs)
{
var info = sub.GetInfo();
if (info != null && info.UserId == userId)
userSubs.Add(info);
}
}
return userSubs;
}
ConcurrentDictionary<string, long> SequenceCounters = new ConcurrentDictionary<string, long>();
public long GetNextSequence(string sequenceId)
{
return SequenceCounters.AddOrUpdate(sequenceId, 1, (id, count) => count + 1);
}
public List<Dictionary<string, string>> GetSubscriptionsDetails(string channel = null)
{
var ret = new List<Dictionary<string, string>>();
foreach (var subs in Subcriptions.Values)
{
foreach (var sub in subs)
{
if (sub != null && (channel == null || sub.Channel == channel))
ret.Add(sub.Meta);
}
}
return ret;
}
public void Register(IEventSubscription subscription, Dictionary<string, string> connectArgs = null)
{
try
{
lock (subscription)
{
if (connectArgs != null)
subscription.Publish("cmd.onConnect", connectArgs.ToJson());
subscription.OnUnsubscribe = HandleUnsubscription;
RegisterSubscription(subscription, subscription.Channel ?? EventSubscription.UnknownChannel, ChannelSubcriptions);
RegisterSubscription(subscription, subscription.SubscriptionId, Subcriptions);
RegisterSubscription(subscription, subscription.UserId, UserIdSubcriptions);
RegisterSubscription(subscription, subscription.UserName, UserNameSubcriptions);
RegisterSubscription(subscription, subscription.SessionId, SessionSubcriptions);
if (OnSubscribe != null)
OnSubscribe(subscription);
}
if (NotifyChannelOfSubscriptions && subscription.Channel != null && NotifyJoin != null)
NotifyJoin(subscription);
}
catch (Exception ex)
{
Log.Error("Register: " + ex.Message, ex);
throw;
}
}
void RegisterSubscription(IEventSubscription subscription, string key,
ConcurrentDictionary<string, IEventSubscription[]> map)
{
if (key == null)
return;
IEventSubscription[] subs;
if (!map.TryGetValue(key, out subs))
{
subs = new IEventSubscription[DefaultArraySize];
subs[0] = subscription;
if (map.TryAdd(key, subs))
return;
}
while (!map.TryGetValue(key, out subs)) ;
if (!TryAdd(subs, subscription))
{
IEventSubscription[] snapshot, newArray;
do
{
while (!map.TryGetValue(key, out snapshot)) ;
newArray = new IEventSubscription[subs.Length * ReSizeMultiplier + ReSizeBuffer];
Array.Copy(snapshot, 0, newArray, 0, snapshot.Length);
if (!TryAdd(newArray, subscription, startIndex: snapshot.Length))
snapshot = null;
} while (!map.TryUpdate(key, newArray, snapshot));
}
}
private static bool TryAdd(IEventSubscription[] subs, IEventSubscription subscription, int startIndex = 0)
{
for (int i = startIndex; i < subs.Length; i++)
{
if (subs[i] != null) continue;
lock (subs)
{
if (subs[i] != null) continue;
subs[i] = subscription;
return true;
}
}
return false;
}
public void UnRegister(string subscriptionId)
{
var subscription = GetSubscription(subscriptionId);
if (subscription == null)
return;
HandleUnsubscription(subscription);
}
void UnRegisterSubscription(IEventSubscription subscription, string key,
ConcurrentDictionary<string, IEventSubscription[]> map)
{
if (key == null)
return;
try
{
IEventSubscription[] subs;
if (!map.TryGetValue(key, out subs)) return;
for (int i = 0; i < subs.Length; i++)
{
if (subs[i] != subscription) continue;
lock (subs)
{
if (subs[i] == subscription)
{
subs[i] = null;
}
}
}
}
catch (Exception ex)
{
Log.Error("UnRegister: " + ex.Message, ex);
throw;
}
}
void HandleUnsubscription(IEventSubscription subscription)
{
lock (subscription)
{
UnRegisterSubscription(subscription, subscription.Channel ?? EventSubscription.UnknownChannel, ChannelSubcriptions);
UnRegisterSubscription(subscription, subscription.SubscriptionId, Subcriptions);
UnRegisterSubscription(subscription, subscription.UserId, UserIdSubcriptions);
UnRegisterSubscription(subscription, subscription.UserName, UserNameSubcriptions);
UnRegisterSubscription(subscription, subscription.SessionId, SessionSubcriptions);
if (OnUnsubscribe != null)
OnUnsubscribe(subscription);
subscription.Dispose();
}
if (NotifyChannelOfSubscriptions && subscription.Channel != null && NotifyLeave != null)
NotifyLeave(subscription);
}
public void Dispose()
{
Reset();
}
}
public interface IServerEvents : IDisposable
{
// External API's
void NotifyAll(string selector, object message);
void NotifyChannel(string channel, string selector, object message);
void NotifySubscription(string subscriptionId, string selector, object message, string channel = null);
void NotifyUserId(string userId, string selector, object message, string channel = null);
void NotifyUserName(string userName, string selector, object message, string channel = null);
void NotifySession(string sspid, string selector, object message, string channel = null);
SubscriptionInfo GetSubscriptionInfo(string id);
List<SubscriptionInfo> GetSubscriptionInfosByUserId(string userId);
// Admin API's
void Register(IEventSubscription subscription, Dictionary<string, string> connectArgs = null);
void UnRegister(string subscriptionId);
long GetNextSequence(string sequenceId);
// Client API's
List<Dictionary<string, string>> GetSubscriptionsDetails(string channel = null);
bool Pulse(string subscriptionId);
// Clear all Registrations
void Reset();
void Start();
void Stop();
}
public static class Selector
{
public static string Id(Type type)
{
return "cmd." + type.Name;
}
public static string Id<T>()
{
return "cmd." + typeof(T).Name;
}
}
public static class ServerEventExtensions
{
public static SubscriptionInfo GetInfo(this IEventSubscription sub)
{
if (sub == null)
return null;
return new SubscriptionInfo
{
CreatedAt = sub.CreatedAt,
Channel = sub.Channel,
UserId = sub.UserId,
UserName = sub.UserName,
DisplayName = sub.DisplayName,
SessionId = sub.SessionId,
SubscriptionId = sub.SubscriptionId,
IsAuthenticated = sub.IsAuthenticated,
Meta = sub.Meta,
};
}
public static void NotifyAll(this IServerEvents server, object message)
{
server.NotifyAll(Selector.Id(message.GetType()), message);
}
public static void NotifyChannel(this IServerEvents server, string channel, object message)
{
server.NotifyChannel(channel, Selector.Id(message.GetType()), message);
}
public static void NotifySubscription(this IServerEvents server, string subscriptionId, object message, string channel = null)
{
server.NotifySubscription(subscriptionId, Selector.Id(message.GetType()), message, channel);
}
public static void NotifyUserId(this IServerEvents server, string userId, object message, string channel = null)
{
server.NotifyUserId(userId, Selector.Id(message.GetType()), message, channel);
}
public static void NotifyUserName(this IServerEvents server, string userName, object message, string channel = null)
{
server.NotifyUserName(userName, Selector.Id(message.GetType()), message, channel);
}
public static void NotifySession(this IServerEvents server, string sspid, object message, string channel = null)
{
server.NotifySession(sspid, Selector.Id(message.GetType()), message, channel);
}
}
}