Notes/NoteHub.cs
2024-12-16 16:10:17 -05:00

56 lines
1.7 KiB
C#

using BinaryDad.Notes.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace BinaryDad.Notes
{
[Authorize]
public class NoteHub : Hub
{
private readonly INoteService noteService;
private readonly ILogger<NoteHub> logger;
public NoteHub(INoteService noteService, ILogger<NoteHub> logger)
{
this.noteService = noteService;
this.logger = logger;
}
public override Task OnConnectedAsync()
{
var noteName = Context.GetHttpContext().Request.Query["noteName"];
NoteContext.ClientNotes[Context.ConnectionId] = noteName;
return base.OnConnectedAsync();
}
public async Task SaveNote(string content, string noteName)
{
try
{
logger.LogInformation($"Saving note \"{noteName}\"");
noteService.SaveNote(content, noteName);
// find all other connections except for the current one
var clientConnections = NoteContext.ClientNotes
.Where(c => c.Value == noteName && c.Key != Context.ConnectionId)
.Select(c => c.Key)
.ToList();
// update note for all other clients
await Clients
.Clients(clientConnections)
.SendAsync("updateNote", content);
logger.LogInformation($"NOTE \"{noteName}\" SAVED! Updated {clientConnections.Count} other client(s).");
}
catch (Exception ex)
{
logger.LogError($"Unable to save note \"{noteName}\" => {ex}");
}
}
}
}