Skip to content
Snippets Groups Projects

Feature/chat signalr

Merged Enzo Santangelo Dodera requested to merge feature/chat-signalr into develop
1 file
+ 0
1
Compare changes
  • Side-by-side
  • Inline
+ 146
0
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Tsi1.BusinessLayer.Dtos;
using Tsi1.BusinessLayer.Interfaces;
using Tsi1.DataLayer;
using Tsi1.DataLayer.Entities;
namespace Tsi1.Api.SignalR
{
[Authorize]
public class ChatHub : Hub
{
private readonly IMapper _mapper;
private readonly IHubContext<PresenceHub> _presenceHub;
private readonly PresenceTracker _tracker;
private readonly IMessageService _messageService;
private readonly IChatService _chatService;
public ChatHub(IMapper mapper, IHubContext<PresenceHub> presenceHub,
PresenceTracker tracker, IMessageService messageService, IChatService chatService)
{
_tracker = tracker;
_presenceHub = presenceHub;
_mapper = mapper;
_messageService = messageService;
_chatService = chatService;
}
public override async Task OnConnectedAsync()
{
var httpContext = Context.GetHttpContext();
var otherUserId = int.Parse(httpContext.Request.Query["id"].ToString());
var userId = int.Parse(Context.User.Claims.FirstOrDefault(x => x.Type == "Id").Value);
var tenantId = int.Parse(Context.User.Claims.FirstOrDefault(x => x.Type == "TenantId").Value);
var groupName = GetGroupName(userId, otherUserId);
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await AddToGroup(groupName);
var messages = await _messageService.GetMessages(userId, otherUserId, tenantId);
await Clients.Caller.SendAsync("ReceiveMessages", messages);
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await RemoveFromGroup();
await base.OnDisconnectedAsync(exception);
}
public async Task SendMessage(MessageCreateDto newMessage)
{
var userId = int.Parse(Context.User.Claims.FirstOrDefault(x => x.Type == "Id").Value);
var tenantId = int.Parse(Context.User.Claims.FirstOrDefault(x => x.Type == "TenantId").Value);
if (userId == newMessage.ReceiverId)
throw new HubException("You cannot send messages to yourself");
var groupName = GetGroupName(userId, newMessage.ReceiverId);
var group = await _chatService.GetGroupByName(groupName);
if (group == null)
{
throw new HubException($"No existe el grupo {groupName}");
}
if (!group.Connections.Any(x => x.UserId == newMessage.ReceiverId))
{
var connections = await _tracker.GetConnectionsForUser(newMessage.ReceiverId);
if (connections != null)
{
await _presenceHub.Clients.Clients(connections).SendAsync("NewMessageReceived", userId);
}
}
newMessage.SenderId = userId;
var messageDto = await _messageService.Send(newMessage);
await Clients.Group(groupName).SendAsync("NewMessage", messageDto);
}
private async Task<Group> AddToGroup(string groupName)
{
var group = await _chatService.GetGroupByName(groupName);
if (group == null)
{
throw new HubException($"No existe el grupo {groupName}");
}
var userId = int.Parse(Context.User.Claims.FirstOrDefault(x => x.Type == "Id").Value);
var connection = new Connection
{
ConnectionId = Context.ConnectionId,
UserId = userId,
};
if (group == null)
{
group = new Group
{
Name = groupName,
};
}
group.Connections.Add(connection);
var result = await _chatService.CreateGroup(group);
if (result.HasError)
{
throw new HubException($"Error al crear el grupo {group}");
}
return group;
}
private async Task<bool> RemoveFromGroup()
{
await _chatService.RemoveConnectionFromGroup(Context.ConnectionId);
return true;
}
private string GetGroupName(int callerId, int otherId)
{
var compare = callerId < otherId;
return compare ? $"{callerId}-{otherId}" : $"{otherId}-{callerId}";
}
}
}
Loading