Notes/NoteHub.cs

43 lines
1.2 KiB
C#
Raw Normal View History

2023-01-25 13:48:50 +00:00
using BinaryDad.Notes.Services;
2023-10-30 14:07:35 +00:00
using Microsoft.AspNetCore.Authorization;
2023-01-25 13:48:50 +00:00
using Microsoft.AspNetCore.SignalR;
namespace BinaryDad.Notes
{
2023-10-30 14:07:35 +00:00
[Authorize]
2023-01-25 13:48:50 +00:00
public class NoteHub : Hub
{
private readonly INoteService noteService;
public NoteHub(INoteService noteService)
{
this.noteService = noteService;
}
2023-03-10 03:06:21 +00:00
public override Task OnConnectedAsync()
2023-01-25 13:48:50 +00:00
{
2023-03-10 03:06:21 +00:00
var noteName = Context.GetHttpContext().Request.Query["noteName"];
2023-01-25 13:48:50 +00:00
2023-03-10 03:06:21 +00:00
NoteContext.ClientNotes[Context.ConnectionId] = noteName;
return base.OnConnectedAsync();
}
public async Task SaveNote(string content, string? noteName)
2023-01-25 13:48:50 +00:00
{
2023-05-12 16:38:13 +00:00
noteService.SaveText(content, noteName);
2023-01-25 13:48:50 +00:00
2023-03-10 03:14:28 +00:00
// find all other connections except for the current one
2023-03-10 03:06:21 +00:00
var clientConnections = NoteContext.ClientNotes
.Where(c => c.Value == noteName && c.Key != Context.ConnectionId)
.Select(c => c.Key)
.ToList();
2023-03-10 03:14:28 +00:00
// update note for all other clients
2023-03-10 03:06:21 +00:00
await Clients
.Clients(clientConnections)
.SendAsync("updateNote", content);
2023-01-25 13:48:50 +00:00
}
}
}