Coding/BinaryDad.Coding/Hubs/CodeHub.cs
2024-01-17 21:49:23 -05:00

88 lines
2.8 KiB
C#

using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Threading.Tasks;
namespace BinaryDad.Coding.Hubs
{
public class CodeHub : Hub
{
private readonly IDistributedCache _cache;
public CodeHub(IDistributedCache cache)
{
_cache = cache;
}
public async Task UpdateCode(string user, int index, string code, bool isTeacher)
{
Console.WriteLine($"Received code from {user} with index {index}");
if (index == 0)
{
await _cache.SetStringAsync($"html-{Context.ConnectionId}", code);
//if (Users.Sessions.TryGetValue(Context.ConnectionId, out User value))
//{
// value.Html = code;
//}
}
else if (index == 1)
{
await _cache.SetStringAsync($"css-{Context.ConnectionId}", code);
//if (Users.Sessions.TryGetValue(Context.ConnectionId, out User value))
//{
// value.Css = code;
//}
}
// only send to all if it's a teacher
if (isTeacher)
{
Console.WriteLine($"Sending code from {user}");
await Clients.Others.SendAsync("ReceiveCode", user, index, code);
}
}
public async Task SaveName(string name, string color)
{
await _cache.SetStringAsync($"name-{Context.ConnectionId}", name);
await _cache.SetStringAsync($"color-{Context.ConnectionId}", string.IsNullOrWhiteSpace(color) ? "white" : color);
//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;
//}
await Clients.Others.SendAsync("UsersList", Users.Sessions);
}
public override async Task OnConnectedAsync()
{
Users.Sessions[Context.ConnectionId] = new User
{
Name = string.Empty
};
await Clients.Others.SendAsync("UsersList", Users.Sessions);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
if (Users.Sessions.ContainsKey(Context.ConnectionId))
{
Users.Sessions.Remove(Context.ConnectionId);
}
await Clients.Others.SendAsync("UsersList", Users.Sessions);
await base.OnDisconnectedAsync(exception);
}
}
}