-
Notifications
You must be signed in to change notification settings - Fork 0
/
NotificationHub.cs
93 lines (78 loc) · 2.9 KB
/
NotificationHub.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Data.Providers;
using Models.Domain;
using Models.Responses;
using Services;
using Services.Security;
namespace Web.App_Start
{
public class NotificationHub : Hub
{
readonly INotificationsService notificationsService;
public NotificationHub(INotificationsService notificationsService)
{
this.notificationsService = notificationsService;
}
static Dictionary<int, HashSet<string>> userIdToConnectionIds = new Dictionary<int, HashSet<string>>();
public override Task OnConnected()
{
int userId = Context.User.Identity.GetId().Value;
string connectionId = Context.ConnectionId;
string notifications = notificationsService.GetNotificationByUserId(userId);
Clients.Caller.addNotification(notifications);
lock (userIdToConnectionIds)
{
if (!userIdToConnectionIds.TryGetValue(userId, out HashSet<string> connections))
{
connections = new HashSet<string>();
userIdToConnectionIds.Add(userId, connections);
}
connections.Add(connectionId);
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
int userId = Context.User.Identity.GetId().Value;
string connectionId = Context.ConnectionId;
lock (userIdToConnectionIds)
{
HashSet<string> connections = userIdToConnectionIds[userId];
connections.Remove(connectionId);
if (connections.Count == 0)
{
userIdToConnectionIds.Remove(userId);
}
}
return base.OnDisconnected(stopCalled);
}
public static string[] GetConnections(int key)
{
HashSet<string> connections;
if (userIdToConnectionIds.TryGetValue(key, out connections))
{
return connections.ToArray();
}
return new string[0];
}
public static void SendNotification(int userId, string items)
{
var hub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
lock (userIdToConnectionIds)
{
string[] connections = GetConnections(userId);
foreach (var connectionId in connections)
{
hub.Clients.Client(connectionId).SendNotificationsToUser(items);
}
}
}
}
}