Notes/NoteHub.cs

56 lines
1.7 KiB
C#
Raw Normal View History

2023-01-25 08:48:50 -05:00
using BinaryDad.Notes.Services;
2023-10-30 10:07:35 -04:00
using Microsoft.AspNetCore.Authorization;
2023-01-25 08:48:50 -05:00
using Microsoft.AspNetCore.SignalR;
namespace BinaryDad.Notes
{
2023-10-30 10:07:35 -04:00
[Authorize]
2023-01-25 08:48:50 -05:00
public class NoteHub : Hub
{
private readonly INoteService noteService;
2024-12-16 15:36:47 -05:00
private readonly ILogger<NoteHub> logger;
2023-01-25 08:48:50 -05:00
2024-12-16 15:36:47 -05:00
public NoteHub(INoteService noteService, ILogger<NoteHub> logger)
2023-01-25 08:48:50 -05:00
{
this.noteService = noteService;
2024-12-16 15:36:47 -05:00
this.logger = logger;
2023-01-25 08:48:50 -05:00
}
2023-03-09 22:06:21 -05:00
public override Task OnConnectedAsync()
2023-01-25 08:48:50 -05:00
{
2023-03-09 22:06:21 -05:00
var noteName = Context.GetHttpContext().Request.Query["noteName"];
2023-01-25 08:48:50 -05:00
2023-03-09 22:06:21 -05:00
NoteContext.ClientNotes[Context.ConnectionId] = noteName;
return base.OnConnectedAsync();
}
2024-01-25 20:11:39 -05:00
public async Task SaveNote(string content, string noteName)
2023-01-25 08:48:50 -05:00
{
2024-12-16 16:10:17 -05:00
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}");
}
2023-01-25 08:48:50 -05:00
}
}
}