Spaces:
Running
Running
Commit ·
6276e23
1
Parent(s): cee8b77
feat(sync): implement in-memory signaling in BoardHub for direct UDP WebRTC P2P sync
Browse filesFiles changed (2)
- FlowAPI/Hubs/BoardHub.csAdded+186
- FlowAPI/Program.cs+20-2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.SignalR;using FlowAPI.Application.Interfaces;using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.Linq;using System.Security.Claims;using System.Threading.Tasks;
namespace FlowAPI.Hubs{ [Authorize] public class BoardHub : Hub { private readonly IGraphService _graphService;
// In-memory registry of active presence: BoardId -> (ConnectionId -> UserPresence) private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, UserPresence>> BoardPresences = new();
public BoardHub(IGraphService graphService) { _graphService = graphService; }
private Guid CurrentUserId { get { var userIdStr = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; return Guid.TryParse(userIdStr, out var userId) ? userId : Guid.Empty; } }
private string CurrentUserEmail => Context.User?.FindFirst(ClaimTypes.Email)?.Value ?? "unknown@user.com"; private string CurrentUserName => Context.User?.FindFirst("name")?.Value ?? Context.User?.FindFirst(ClaimTypes.Name)?.Value ?? "Collaborator";
public async Task JoinBoard(string boardId) { if (string.IsNullOrEmpty(boardId) || !Guid.TryParse(boardId, out var graphId)) { await Clients.Caller.SendAsync("Error", "Invalid Board ID"); return; }
var userId = CurrentUserId; if (userId == Guid.Empty) { await Clients.Caller.SendAsync("Error", "Unauthorized"); return; }
// Verify authorization var graph = await _graphService.GetByIdAsync(graphId, userId); if (graph == null) { await Clients.Caller.SendAsync("AccessDenied"); Context.Abort(); return; }
// Join SignalR Group await Groups.AddToGroupAsync(Context.ConnectionId, boardId);
// Register presence var presence = new UserPresence { ConnectionId = Context.ConnectionId, UserId = userId.ToString(), Email = CurrentUserEmail, Name = CurrentUserName, JoinedAt = DateTime.UtcNow };
var groupPresence = BoardPresences.GetOrAdd(boardId, _ => new ConcurrentDictionary<string, UserPresence>()); groupPresence[Context.ConnectionId] = presence;
// Broadcast presence to all other group members await BroadcastPresence(boardId); }
public async Task SendSignal(string boardId, string receiverUserId, string type, string data) { if (string.IsNullOrEmpty(boardId)) return; if (BoardPresences.TryGetValue(boardId, out var groupPresence)) { var receiverConns = groupPresence.Values .Where(p => p.UserId == receiverUserId) .Select(p => p.ConnectionId); foreach (var connId in receiverConns) { await Clients.Client(connId).SendAsync("ReceiveSignal", CurrentUserId.ToString(), type, data); } } }
public async Task SendCursor(string boardId, double x, double y) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("CursorMoved", Context.ConnectionId, CurrentUserId.ToString(), x, y); }
public async Task MoveNode(string boardId, string nodeId, double x, double y) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("NodeMoved", nodeId, x, y); }
public async Task UpdateNodeData(string boardId, string nodeId, string newDataJson) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("NodeDataUpdated", nodeId, newDataJson); }
public async Task AddNode(string boardId, string nodeJson) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("NodeAdded", nodeJson); }
public async Task DeleteNode(string boardId, string nodeId) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("NodeDeleted", nodeId); }
public async Task AddEdge(string boardId, string edgeJson) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("EdgeAdded", edgeJson); }
public async Task DeleteEdge(string boardId, string edgeId) { if (string.IsNullOrEmpty(boardId)) return; await Clients.OthersInGroup(boardId).SendAsync("EdgeDeleted", edgeId); }
public override async Task OnDisconnectedAsync(Exception exception) { // Clean up presence in all boards foreach (var boardId in BoardPresences.Keys) { if (BoardPresences.TryGetValue(boardId, out var groupPresence)) { if (groupPresence.TryRemove(Context.ConnectionId, out _)) { await BroadcastPresence(boardId); } } }
await base.OnDisconnectedAsync(exception); }
private async Task BroadcastPresence(string boardId) { if (BoardPresences.TryGetValue(boardId, out var groupPresence)) { // Unique by user ID (could be connected from multiple tabs, show as one presence or separate, we map by unique user ID) var uniquePresences = groupPresence.Values .GroupBy(p => p.UserId) .Select(g => g.First()) .Select(p => new { userId = p.UserId, email = p.Email, name = p.Name }) .ToList();
await Clients.Group(boardId).SendAsync("PresenceUpdated", uniquePresences); } } }
public class UserPresence { public string ConnectionId { get; set; } public string UserId { get; set; } public string Email { get; set; } public string Name { get; set; } public DateTime JoinedAt { get; set; } }}40 unmodified lines41424344454647484914 unmodified lines6465666768697071727374757677787980818210 unmodified lines93949580969782989910010110261 unmodified lines16416516616716816917040 unmodified lines // --- Singletons --- builder.Services.AddSingleton<IGeminiBridgeManager, GeminiBridgeManager>();
// --- SignalR --- builder.Services.AddSignalR();
// --- Authentication --- var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new Exception("JWT Key missing"); builder.Services.AddAuthentication(options =>14 unmodified lines ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) { context.Token = accessToken; } return Task.CompletedTask; } }; });
// --- Controllers & OpenAPI ---10 unmodified lines { options.AddPolicy("AllowAll", policy => { policy.AllowAnyOrigin() policy.SetIsOriginAllowed(origin => true) .AllowAnyMethod() .AllowAnyHeader(); .AllowAnyHeader() .AllowCredentials(); }); });
61 unmodified lines app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.MapHub<FlowAPI.Hubs.BoardHub>("/hubs/board");
app.Run(); }FlowAPI/Hubs/BoardHub.csAdded+186
FlowAPI/Program.cs+20-2