Coding/BinaryDad.Coding/Hubs/CodeHub.cs

77 lines
2.2 KiB
C#
Raw Normal View History

2021-07-19 01:15:57 +00:00
using Microsoft.AspNetCore.SignalR;
2021-07-21 01:53:39 +00:00
using System;
2021-07-19 01:15:57 +00:00
using System.Threading.Tasks;
namespace BinaryDad.Coding.Hubs
{
public class CodeHub : Hub
{
2021-07-23 00:41:12 +00:00
public Task UpdateCode(string user, int index, string code, bool isTeacher)
2021-07-19 01:15:57 +00:00
{
2024-01-18 01:21:35 +00:00
Console.WriteLine($"Received code from {user} with index {index}");
2021-07-23 00:41:12 +00:00
if (index == 0)
{
2024-01-18 00:27:07 +00:00
if (Users.Sessions.TryGetValue(Context.ConnectionId, out User value))
{
value.Html = code;
}
2021-07-23 00:41:12 +00:00
}
else if (index == 1)
{
2024-01-18 00:27:07 +00:00
if (Users.Sessions.TryGetValue(Context.ConnectionId, out User value))
{
value.Css = code;
}
2021-07-23 00:41:12 +00:00
}
2021-07-23 02:51:14 +00:00
// only send to all if it's a teacher
2021-07-23 00:41:12 +00:00
if (isTeacher)
{
2024-01-18 01:21:35 +00:00
Console.WriteLine($"Sending code from {user}");
2021-07-23 00:41:12 +00:00
return Clients.All.SendAsync("ReceiveCode", user, index, code);
}
2024-01-18 01:21:35 +00:00
2024-01-18 01:16:31 +00:00
return Task.CompletedTask;
2021-07-19 01:15:57 +00:00
}
2021-07-21 01:53:39 +00:00
public async Task SaveName(string name, string color)
{
2024-01-18 00:27:07 +00:00
if (!Users.Sessions.ContainsKey(Context.ConnectionId))
{
Users.Sessions[Context.ConnectionId].Id = Context.ConnectionId;
Users.Sessions[Context.ConnectionId].Name = name;
Users.Sessions[Context.ConnectionId].Color = string.IsNullOrWhiteSpace(color) ? "white" : color;
}
2021-07-21 01:53:39 +00:00
2021-07-23 00:41:12 +00:00
await Clients.All.SendAsync("UsersList", Users.Sessions);
2021-07-21 01:53:39 +00:00
}
public override async Task OnConnectedAsync()
{
2021-07-23 00:41:12 +00:00
Users.Sessions[Context.ConnectionId] = new User
2021-07-21 01:53:39 +00:00
{
2021-07-23 02:51:14 +00:00
Name = string.Empty
2021-07-21 01:53:39 +00:00
};
2021-07-23 00:41:12 +00:00
await Clients.All.SendAsync("UsersList", Users.Sessions);
2021-07-21 01:53:39 +00:00
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
2024-01-18 00:27:07 +00:00
if (Users.Sessions.ContainsKey(Context.ConnectionId))
{
Users.Sessions.Remove(Context.ConnectionId);
}
2021-07-21 01:53:39 +00:00
2021-07-23 00:41:12 +00:00
await Clients.All.SendAsync("UsersList", Users.Sessions);
2021-07-21 01:53:39 +00:00
await base.OnDisconnectedAsync(exception);
}
2021-07-19 01:15:57 +00:00
}
2021-07-21 01:53:39 +00:00
}