| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Threading.Tasks; |
| | | 5 | | using Microsoft.AspNetCore.Authorization; |
| | | 6 | | using Microsoft.AspNetCore.SignalR; |
| | | 7 | | using Microsoft.Extensions.Logging; |
| | | 8 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 9 | | |
| | | 10 | | namespace SVETA.Api.Hubs |
| | | 11 | | { |
| | | 12 | | [Authorize] |
| | | 13 | | public class NotificationHub : Hub |
| | | 14 | | { |
| | | 15 | | private readonly INotificationService _notificationService; |
| | | 16 | | private readonly ILogger<NotificationHub> _logger; |
| | | 17 | | |
| | | 18 | | public NotificationHub(INotificationService notificationService, ILogger<NotificationHub> logger) |
| | | 19 | | { |
| | | 20 | | _notificationService = notificationService; |
| | | 21 | | _logger = logger; |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | public async Task Send() |
| | | 25 | | { |
| | | 26 | | await Clients.All.SendAsync("notificationReceived", Context.UserIdentifier); |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | public async Task NewMessage(long userName, string message) |
| | | 30 | | { |
| | | 31 | | await Clients.All.SendAsync("messageReceived", userName, message); |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | public override Task OnConnectedAsync() |
| | | 35 | | { |
| | | 36 | | _logger.LogError($"Подключаем пользователя " + |
| | | 37 | | $"{Context.User.Identities.SelectMany(d => d.Claims).FirstOrDefault(s => s.Type.Contains("u |
| | | 38 | | var tid = Context.User.Identities.SelectMany(d => d.Claims).FirstOrDefault(s => s.Type.Contains("user_TID")) |
| | | 39 | | .Value.ToString(); |
| | | 40 | | string actual = default; |
| | | 41 | | UserHandler.ConnectedIds.TryGetValue(tid, out actual); |
| | | 42 | | if (actual != default) |
| | | 43 | | { |
| | | 44 | | OnDisconnectedAsync(new ArgumentException("User already have connection")); |
| | | 45 | | } |
| | | 46 | | UserHandler.ConnectedIds.Add(tid, Context.ConnectionId); |
| | | 47 | | return base.OnConnectedAsync(); |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | public override Task OnDisconnectedAsync(Exception exception) |
| | | 51 | | { |
| | | 52 | | _logger.LogError($"Удаляем подключение пользователя " + |
| | | 53 | | $"{Context.User.Identities.SelectMany(d => d.Claims).FirstOrDefault(s => s.Type.Contains("u |
| | | 54 | | var tid = Context.User.Identities.SelectMany(d => d.Claims).FirstOrDefault(s => s.Type.Contains("user_TID")) |
| | | 55 | | .Value.ToString(); |
| | | 56 | | UserHandler.ConnectedIds.Remove(tid); |
| | | 57 | | return base.OnDisconnectedAsync(exception); |
| | | 58 | | } |
| | | 59 | | } |
| | | 60 | | public static class UserHandler |
| | | 61 | | { |
| | 0 | 62 | | public static Dictionary<string, string> ConnectedIds = new Dictionary<string, string>(); |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | |
| | | 66 | | } |