54 lines
1.6 KiB
C#
54 lines
1.6 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
|
|
{
|
|
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}");
|
|
}
|
|
}
|
|
}
|
|
}
|