Notes/NoteHub.cs
2024-05-07 21:43:09 -04:00

43 lines
1.2 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;
public NoteHub(INoteService noteService)
{
this.noteService = noteService;
}
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)
{
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);
}
}
}