-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOnlineUserHandler.cs
78 lines (67 loc) · 2.43 KB
/
OnlineUserHandler.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SignalRChat
{
public class OnlineUserHandler
{
private Dictionary<string, List<User>> onlineUsersOfGroups = new Dictionary<string, List<User>>();
private HashSet<User> allUsers = new HashSet<User>();
public void RemoveUserFromRoom(string connectionId, string roomName) {
List<User> userList;
if (!onlineUsersOfGroups.TryGetValue(roomName, out userList))
{
userList = new List<User>();
}
var itemToRemove = allUsers.FirstOrDefault(r => r.ConnectionID == connectionId);
userList.Remove(itemToRemove);
}
public void AddUserToRoom(string connectionId, string roomName, string userName)
{
User user = allUsers.FirstOrDefault(u => u.ConnectionID == connectionId);
if (user == null) {
user = new User(userName, connectionId);
allUsers.Add(user);
}
List<User> onlines;
if (!onlineUsersOfGroups.TryGetValue(roomName, out onlines))
{
onlines = new List<User>();
}
onlines.Add(user);
onlineUsersOfGroups.Remove(roomName);
onlineUsersOfGroups.Add(roomName, onlines);
}
public List<User> getOnlineList(string groupName)
{
List<User> onlines;
if (onlineUsersOfGroups.TryGetValue(groupName, out onlines))
{
return onlines;
}
return null;
}
public void RemoveUser(string connectionId)
{
allUsers.RemoveWhere(u => u.ConnectionID == connectionId);
foreach (var item in onlineUsersOfGroups)
{
item.Value.RemoveAll(x => x.ConnectionID == connectionId);
}
}
public string getUserName(string connectionId) {
return allUsers.FirstOrDefault(x => x.ConnectionID == connectionId).Name;
}
public List<string> getRoomsOfUser(string connectionId) {
List<string> rooms = new List<string>();
foreach (var item in onlineUsersOfGroups)
{
if (item.Value.Any(x => x.ConnectionID == connectionId)) {
rooms.Add(item.Key);
}
}
return rooms;
}
}
}