blob: c5e520f4f18207d0ac746825ba43e57ef0b4f33c (
plain) (
blame)
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
|
using Microsoft.AspNetCore.SignalR;
using PUSG.Web.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PUSG.Web.Hubs
{
public class HomeHub : Hub
{
private const string ServerMessageUser = "PUSG";
private ISessionService sessionService;
public HomeHub(ISessionService sessionService)
{
this.sessionService = sessionService;
}
private async Task BroadcastToLoggedIn(string message, params object[] contents)
{
List<string> excludedConnections = this.sessionService
.LiveConnections
.Where(liveConnection => !this.sessionService.IsLogged(liveConnection))
.ToList();
await this.Clients.AllExcept(excludedConnections).SendAsync(message, contents);
}
public async Task SendMessage(string username, string messageContent)
{
if (this.sessionService.IsLogged(username) || username == "PUSG")
{
await this.BroadcastToLoggedIn("ReceiveMessage", username, messageContent);
}
}
public async Task Login(string username)
{
if(!this.sessionService.IsLogged(username))
{
await this.BroadcastToLoggedIn("OnLoggedIn", username);
this.sessionService.AddUser(this.Context.ConnectionId, username);
await this.Clients.Caller.SendAsync("OnLoggedIn", this.sessionService.Users.Values);
}
}
public override async Task OnConnectedAsync()
{
this.sessionService.LiveConnections.Add(this.Context.ConnectionId);
await this.BroadcastToLoggedIn("OnConnected", "A new user has connected!");
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
if (this.sessionService.IsLogged(this.Context.ConnectionId))
{
string username = this.sessionService.Users[this.Context.ConnectionId];
this.sessionService.LiveConnections.Remove(this.Context.ConnectionId);
this.sessionService.RemoveUser(this.Context.ConnectionId);
await this.BroadcastToLoggedIn("OnLoggedOut", username);
}
await base.OnDisconnectedAsync(exception);
}
}
}
|