danylokhodus commited on
Commit
6276e23
·
1 Parent(s): cee8b77

feat(sync): implement in-memory signaling in BoardHub for direct UDP WebRTC P2P sync

Browse files
Files changed (2) hide show
  1. FlowAPI/Hubs/BoardHub.cs +186 -0
  2. FlowAPI/Program.cs +20 -2
FlowAPI/Hubs/BoardHub.cs ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Microsoft.AspNetCore.Authorization;
2
+ using Microsoft.AspNetCore.SignalR;
3
+ using FlowAPI.Application.Interfaces;
4
+ using System;
5
+ using System.Collections.Concurrent;
6
+ using System.Collections.Generic;
7
+ using System.Linq;
8
+ using System.Security.Claims;
9
+ using System.Threading.Tasks;
10
+
11
+ namespace FlowAPI.Hubs
12
+ {
13
+ [Authorize]
14
+ public class BoardHub : Hub
15
+ {
16
+ private readonly IGraphService _graphService;
17
+
18
+ // In-memory registry of active presence: BoardId -> (ConnectionId -> UserPresence)
19
+ private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, UserPresence>> BoardPresences = new();
20
+
21
+ public BoardHub(IGraphService graphService)
22
+ {
23
+ _graphService = graphService;
24
+ }
25
+
26
+ private Guid CurrentUserId
27
+ {
28
+ get
29
+ {
30
+ var userIdStr = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
31
+ return Guid.TryParse(userIdStr, out var userId) ? userId : Guid.Empty;
32
+ }
33
+ }
34
+
35
+ private string CurrentUserEmail => Context.User?.FindFirst(ClaimTypes.Email)?.Value ?? "unknown@user.com";
36
+
37
+ private string CurrentUserName => Context.User?.FindFirst("name")?.Value ?? Context.User?.FindFirst(ClaimTypes.Name)?.Value ?? "Collaborator";
38
+
39
+ public async Task JoinBoard(string boardId)
40
+ {
41
+ if (string.IsNullOrEmpty(boardId) || !Guid.TryParse(boardId, out var graphId))
42
+ {
43
+ await Clients.Caller.SendAsync("Error", "Invalid Board ID");
44
+ return;
45
+ }
46
+
47
+ var userId = CurrentUserId;
48
+ if (userId == Guid.Empty)
49
+ {
50
+ await Clients.Caller.SendAsync("Error", "Unauthorized");
51
+ return;
52
+ }
53
+
54
+ // Verify authorization
55
+ var graph = await _graphService.GetByIdAsync(graphId, userId);
56
+ if (graph == null)
57
+ {
58
+ await Clients.Caller.SendAsync("AccessDenied");
59
+ Context.Abort();
60
+ return;
61
+ }
62
+
63
+ // Join SignalR Group
64
+ await Groups.AddToGroupAsync(Context.ConnectionId, boardId);
65
+
66
+ // Register presence
67
+ var presence = new UserPresence
68
+ {
69
+ ConnectionId = Context.ConnectionId,
70
+ UserId = userId.ToString(),
71
+ Email = CurrentUserEmail,
72
+ Name = CurrentUserName,
73
+ JoinedAt = DateTime.UtcNow
74
+ };
75
+
76
+ var groupPresence = BoardPresences.GetOrAdd(boardId, _ => new ConcurrentDictionary<string, UserPresence>());
77
+ groupPresence[Context.ConnectionId] = presence;
78
+
79
+ // Broadcast presence to all other group members
80
+ await BroadcastPresence(boardId);
81
+ }
82
+
83
+ public async Task SendSignal(string boardId, string receiverUserId, string type, string data)
84
+ {
85
+ if (string.IsNullOrEmpty(boardId)) return;
86
+ if (BoardPresences.TryGetValue(boardId, out var groupPresence))
87
+ {
88
+ var receiverConns = groupPresence.Values
89
+ .Where(p => p.UserId == receiverUserId)
90
+ .Select(p => p.ConnectionId);
91
+ foreach (var connId in receiverConns)
92
+ {
93
+ await Clients.Client(connId).SendAsync("ReceiveSignal", CurrentUserId.ToString(), type, data);
94
+ }
95
+ }
96
+ }
97
+
98
+ public async Task SendCursor(string boardId, double x, double y)
99
+ {
100
+ if (string.IsNullOrEmpty(boardId)) return;
101
+ await Clients.OthersInGroup(boardId).SendAsync("CursorMoved", Context.ConnectionId, CurrentUserId.ToString(), x, y);
102
+ }
103
+
104
+ public async Task MoveNode(string boardId, string nodeId, double x, double y)
105
+ {
106
+ if (string.IsNullOrEmpty(boardId)) return;
107
+ await Clients.OthersInGroup(boardId).SendAsync("NodeMoved", nodeId, x, y);
108
+ }
109
+
110
+ public async Task UpdateNodeData(string boardId, string nodeId, string newDataJson)
111
+ {
112
+ if (string.IsNullOrEmpty(boardId)) return;
113
+ await Clients.OthersInGroup(boardId).SendAsync("NodeDataUpdated", nodeId, newDataJson);
114
+ }
115
+
116
+ public async Task AddNode(string boardId, string nodeJson)
117
+ {
118
+ if (string.IsNullOrEmpty(boardId)) return;
119
+ await Clients.OthersInGroup(boardId).SendAsync("NodeAdded", nodeJson);
120
+ }
121
+
122
+ public async Task DeleteNode(string boardId, string nodeId)
123
+ {
124
+ if (string.IsNullOrEmpty(boardId)) return;
125
+ await Clients.OthersInGroup(boardId).SendAsync("NodeDeleted", nodeId);
126
+ }
127
+
128
+ public async Task AddEdge(string boardId, string edgeJson)
129
+ {
130
+ if (string.IsNullOrEmpty(boardId)) return;
131
+ await Clients.OthersInGroup(boardId).SendAsync("EdgeAdded", edgeJson);
132
+ }
133
+
134
+ public async Task DeleteEdge(string boardId, string edgeId)
135
+ {
136
+ if (string.IsNullOrEmpty(boardId)) return;
137
+ await Clients.OthersInGroup(boardId).SendAsync("EdgeDeleted", edgeId);
138
+ }
139
+
140
+ public override async Task OnDisconnectedAsync(Exception exception)
141
+ {
142
+ // Clean up presence in all boards
143
+ foreach (var boardId in BoardPresences.Keys)
144
+ {
145
+ if (BoardPresences.TryGetValue(boardId, out var groupPresence))
146
+ {
147
+ if (groupPresence.TryRemove(Context.ConnectionId, out _))
148
+ {
149
+ await BroadcastPresence(boardId);
150
+ }
151
+ }
152
+ }
153
+
154
+ await base.OnDisconnectedAsync(exception);
155
+ }
156
+
157
+ private async Task BroadcastPresence(string boardId)
158
+ {
159
+ if (BoardPresences.TryGetValue(boardId, out var groupPresence))
160
+ {
161
+ // Unique by user ID (could be connected from multiple tabs, show as one presence or separate, we map by unique user ID)
162
+ var uniquePresences = groupPresence.Values
163
+ .GroupBy(p => p.UserId)
164
+ .Select(g => g.First())
165
+ .Select(p => new
166
+ {
167
+ userId = p.UserId,
168
+ email = p.Email,
169
+ name = p.Name
170
+ })
171
+ .ToList();
172
+
173
+ await Clients.Group(boardId).SendAsync("PresenceUpdated", uniquePresences);
174
+ }
175
+ }
176
+ }
177
+
178
+ public class UserPresence
179
+ {
180
+ public string ConnectionId { get; set; }
181
+ public string UserId { get; set; }
182
+ public string Email { get; set; }
183
+ public string Name { get; set; }
184
+ public DateTime JoinedAt { get; set; }
185
+ }
186
+ }
FlowAPI/Program.cs CHANGED
@@ -41,6 +41,9 @@ namespace FlowAPI
41
  // --- Singletons ---
42
  builder.Services.AddSingleton<IGeminiBridgeManager, GeminiBridgeManager>();
43
 
 
 
 
44
  // --- Authentication ---
45
  var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new Exception("JWT Key missing");
46
  builder.Services.AddAuthentication(options =>
@@ -61,6 +64,19 @@ namespace FlowAPI
61
  ValidateLifetime = true,
62
  ClockSkew = TimeSpan.Zero
63
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  });
65
 
66
  // --- Controllers & OpenAPI ---
@@ -77,9 +93,10 @@ namespace FlowAPI
77
  {
78
  options.AddPolicy("AllowAll", policy =>
79
  {
80
- policy.AllowAnyOrigin()
81
  .AllowAnyMethod()
82
- .AllowAnyHeader();
 
83
  });
84
  });
85
 
@@ -147,6 +164,7 @@ namespace FlowAPI
147
  app.UseAuthentication();
148
  app.UseAuthorization();
149
  app.MapControllers();
 
150
 
151
  app.Run();
152
  }
 
41
  // --- Singletons ---
42
  builder.Services.AddSingleton<IGeminiBridgeManager, GeminiBridgeManager>();
43
 
44
+ // --- SignalR ---
45
+ builder.Services.AddSignalR();
46
+
47
  // --- Authentication ---
48
  var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new Exception("JWT Key missing");
49
  builder.Services.AddAuthentication(options =>
 
64
  ValidateLifetime = true,
65
  ClockSkew = TimeSpan.Zero
66
  };
67
+ options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
68
+ {
69
+ OnMessageReceived = context =>
70
+ {
71
+ var accessToken = context.Request.Query["access_token"];
72
+ var path = context.HttpContext.Request.Path;
73
+ if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
74
+ {
75
+ context.Token = accessToken;
76
+ }
77
+ return Task.CompletedTask;
78
+ }
79
+ };
80
  });
81
 
82
  // --- Controllers & OpenAPI ---
 
93
  {
94
  options.AddPolicy("AllowAll", policy =>
95
  {
96
+ policy.SetIsOriginAllowed(origin => true)
97
  .AllowAnyMethod()
98
+ .AllowAnyHeader()
99
+ .AllowCredentials();
100
  });
101
  });
102
 
 
164
  app.UseAuthentication();
165
  app.UseAuthorization();
166
  app.MapControllers();
167
+ app.MapHub<FlowAPI.Hubs.BoardHub>("/hubs/board");
168
 
169
  app.Run();
170
  }