Now with multi connections
This commit is contained in:
parent
fd79027b37
commit
2f537a7535
@ -1,16 +1,62 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Todo.Api.Hubs.Models;
|
||||
using Todo.Core.Interfaces.Persistence;
|
||||
|
||||
namespace Todo.Api.Hubs
|
||||
namespace Todo.Api.Hubs;
|
||||
|
||||
[Authorize]
|
||||
public class TodoHub : Hub
|
||||
{
|
||||
[Authorize]
|
||||
public class TodoHub : Hub
|
||||
{
|
||||
private readonly ITodoRepository _todoRepository;
|
||||
|
||||
private static readonly ConcurrentDictionary<string, List<string>> ConnectedUsers = new();
|
||||
|
||||
public override Task OnConnectedAsync()
|
||||
{
|
||||
var userId = Context.User.FindFirstValue("sub");
|
||||
|
||||
// Try to get a List of existing user connections from the cache
|
||||
ConnectedUsers.TryGetValue(userId, out var existingUserConnectionIds);
|
||||
|
||||
// happens on the very first connection from the user
|
||||
existingUserConnectionIds ??= new List<string>();
|
||||
|
||||
// First add to a List of existing user connections (i.e. multiple web browser tabs)
|
||||
existingUserConnectionIds.Add(Context.ConnectionId);
|
||||
|
||||
|
||||
// Add to the global dictionary of connected users
|
||||
ConnectedUsers.TryAdd(userId, existingUserConnectionIds);
|
||||
|
||||
return base.OnConnectedAsync();
|
||||
}
|
||||
|
||||
public override Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
var userId = Context.User.FindFirstValue("sub");
|
||||
|
||||
ConnectedUsers.TryGetValue(userId, out var existingUserConnectionIds);
|
||||
|
||||
// remove the connection id from the List
|
||||
existingUserConnectionIds?.Remove(Context.ConnectionId);
|
||||
|
||||
// If there are no connection ids in the List, delete the user from the global cache (ConnectedUsers).
|
||||
if (existingUserConnectionIds?.Count == 0)
|
||||
{
|
||||
// if there are no connections for the user,
|
||||
// just delete the userName key from the ConnectedUsers concurent dictionary
|
||||
ConnectedUsers.TryRemove(userId, out _);
|
||||
}
|
||||
|
||||
return base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
|
||||
|
||||
public TodoHub(ITodoRepository todoRepository)
|
||||
{
|
||||
_todoRepository = todoRepository;
|
||||
@ -28,9 +74,11 @@ namespace Todo.Api.Hubs
|
||||
.Select(t => new TodoResponse { Id = t.Id, Title = t.Title, Project = t.Project })
|
||||
.ToList());
|
||||
|
||||
await Clients.Caller.SendAsync("getInboxTodos", serializedTodos);
|
||||
await RunOnUserConnections(async (connections) =>
|
||||
await Clients.Clients(connections).SendAsync("getInboxTodos", serializedTodos));
|
||||
}
|
||||
|
||||
|
||||
public async Task UpdateTodo(string todoId, bool todoStatus)
|
||||
{
|
||||
await _todoRepository.UpdateTodoStatus(todoId, todoStatus);
|
||||
@ -42,7 +90,8 @@ namespace Todo.Api.Hubs
|
||||
{ Id = t.Id, Title = t.Title, Status = t.Status, Project = t.Project })
|
||||
.ToList());
|
||||
|
||||
await Clients.Caller.SendAsync("getInboxTodos", serializedTodos);
|
||||
await RunOnUserConnections(async (connections) =>
|
||||
await Clients.Clients(connections).SendAsync("getInboxTodos", serializedTodos));
|
||||
}
|
||||
|
||||
public async Task GetTodos()
|
||||
@ -52,7 +101,8 @@ namespace Todo.Api.Hubs
|
||||
.Select(t => new TodoResponse { Id = t.Id, Title = t.Title, Status = t.Status, Project = t.Project })
|
||||
.ToList());
|
||||
|
||||
await Clients.Caller.SendAsync("todos", serializedTodos);
|
||||
await RunOnUserConnections(async (connections) =>
|
||||
await Clients.Clients(connections).SendAsync("todos", serializedTodos));
|
||||
}
|
||||
|
||||
public async Task GetInboxTodos()
|
||||
@ -62,7 +112,8 @@ namespace Todo.Api.Hubs
|
||||
.Select(t => new TodoResponse { Id = t.Id, Title = t.Title, Status = t.Status, Project = t.Project })
|
||||
.ToList());
|
||||
|
||||
await Clients.Caller.SendAsync("getInboxTodos", serializedTodos);
|
||||
await RunOnUserConnections(async (connections) =>
|
||||
await Clients.Clients(connections).SendAsync("getInboxTodos", serializedTodos));
|
||||
}
|
||||
|
||||
public async Task GetTodo(string todoId)
|
||||
@ -76,7 +127,8 @@ namespace Todo.Api.Hubs
|
||||
Title = todo.Title,
|
||||
});
|
||||
|
||||
await Clients.Caller.SendAsync("getTodo", serializedTodo);
|
||||
await RunOnUserConnections(async (connections) =>
|
||||
await Clients.Clients(connections).SendAsync("getTodo", serializedTodo));
|
||||
}
|
||||
|
||||
public async Task ReplaceTodo(string updateTodoRequest)
|
||||
@ -101,7 +153,21 @@ namespace Todo.Api.Hubs
|
||||
Title = updatedTodo.Title,
|
||||
});
|
||||
|
||||
await Clients.Caller.SendAsync("getTodo", serializedTodo);
|
||||
await RunOnUserConnections(async (connections) =>
|
||||
await Clients.Clients(connections).SendAsync("getTodo", serializedTodo));
|
||||
}
|
||||
|
||||
private Task RunOnUserConnections(Func<IEnumerable<string>, Task> action)
|
||||
{
|
||||
var userId = Context.User.FindFirstValue("sub");
|
||||
if (userId is null)
|
||||
throw new InvalidOperationException("User id was invalid. Something has gone terribly wrong");
|
||||
|
||||
ConnectedUsers.TryGetValue(userId, out var connections);
|
||||
|
||||
if (connections is not null)
|
||||
action(connections);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
@ -27,6 +27,7 @@ namespace Todo.Api
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddControllers();
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddCors(options =>
|
||||
{
|
||||
options.AddDefaultPolicy(builder =>
|
||||
|
@ -3,6 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -40,7 +40,9 @@ export const SocketProvider: FC = (props) => {
|
||||
process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:5000";
|
||||
|
||||
const connection = new HubConnectionBuilder()
|
||||
.withUrl(`${serverUrl}/hubs/todo`)
|
||||
.withUrl(`${serverUrl}/hubs/todo`, {
|
||||
withCredentials: true
|
||||
})
|
||||
.withAutomaticReconnect()
|
||||
.configureLogging(LogLevel.Information)
|
||||
.build();
|
||||
|
Loading…
Reference in New Issue
Block a user