yavsc/src/Yavsc.Server/Hubs/ChatHub.cs

401 lines
16 KiB
C#
Raw Normal View History

2016-05-17 18:22:18 +02:00
//
2019-05-22 17:27:44 +01:00
// ChatHub.cs
2016-05-17 18:22:18 +02:00
//
// Author:
// Paul Schneider <paul@pschneider.fr>
//
2019-05-22 17:27:44 +01:00
// Copyright (c) 2016-2019 GNU GPL
2016-05-17 18:22:18 +02:00
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2019-05-24 20:15:48 +01:00
2019-05-11 02:50:19 +01:00
using System;
2023-03-19 17:57:55 +00:00
using Microsoft.AspNetCore.SignalR;
2019-05-11 02:50:19 +01:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2019-06-05 01:36:50 +01:00
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
2016-05-17 18:22:18 +02:00
namespace Yavsc
{
2025-07-07 07:49:18 +01:00
using System.Diagnostics;
2023-03-19 17:57:55 +00:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
2016-11-03 14:52:17 +01:00
using Models;
using Models.Chat;
2019-06-14 10:03:51 +01:00
using Yavsc.Abstract.Chat;
2025-07-07 07:49:18 +01:00
using Yavsc.Helpers;
using Yavsc.Server.Helpers;
2019-06-14 10:03:51 +01:00
using Yavsc.Services;
2019-06-05 11:44:33 +01:00
public partial class ChatHub : Hub, IDisposable
2016-05-17 18:22:18 +02:00
{
2021-03-10 01:41:31 +00:00
private readonly ApplicationDbContext _dbContext;
private readonly IConnexionManager _cxManager;
private readonly IStringLocalizer _localizer;
private readonly ILogger _logger;
2019-01-26 14:23:53 +00:00
public HubInputValidator InputValidator { get; }
2019-06-18 14:01:33 +01:00
2024-02-25 18:05:10 +00:00
public ChatHub(ApplicationDbContext dbContext,
ILoggerFactory loggerFactory,
IStringLocalizerFactory stringLocalizerFactory,
IConnexionManager connexionManager)
2019-05-13 14:44:28 +01:00
{
2024-02-25 18:05:10 +00:00
_dbContext = dbContext;
_localizer = stringLocalizerFactory.Create(typeof(ChatHub));
2019-06-14 10:03:51 +01:00
2024-02-25 18:05:10 +00:00
_cxManager = connexionManager;
2019-06-14 10:03:51 +01:00
_cxManager.SetErrorHandler ((context, error) =>
{
2019-06-17 20:52:51 +01:00
NotifyUser(NotificationTypes.Error, context, error);
2019-06-14 10:03:51 +01:00
});
2019-01-26 14:23:53 +00:00
_logger = loggerFactory.CreateLogger<ChatHub>();
2023-03-19 17:57:55 +00:00
InputValidator = new HubInputValidator { NotifyUser = async (type, target, msg) => await this.NotifyUser(type, target, msg) };
2019-01-26 14:23:53 +00:00
}
2016-11-02 11:27:12 +01:00
2019-06-14 10:03:51 +01:00
void SetUserName(string cxId, string userName)
{
_cxManager.SetUserName(cxId, userName);
2019-06-14 10:03:51 +01:00
}
2023-03-19 17:57:55 +00:00
public override async Task OnConnectedAsync()
2016-11-01 23:22:46 +01:00
{
2024-03-04 01:02:19 +00:00
bool isAuth = Context.User?.Identity?.IsAuthenticated ?? false;
2019-06-14 10:03:51 +01:00
bool isCop = false;
2019-05-10 09:58:09 +01:00
string userName = setUserName();
if (isAuth)
2016-11-01 23:22:46 +01:00
{
2019-05-13 14:44:28 +01:00
2016-11-01 23:22:46 +01:00
var group = isAuth ?
2019-06-14 10:03:51 +01:00
ChatHubConstants.HubGroupAuthenticated : ChatHubConstants.HubGroupAnonymous;
2016-11-01 23:22:46 +01:00
// Log ("Cx: " + group);
2023-03-19 17:57:55 +00:00
await Groups.AddToGroupAsync(Context.ConnectionId, group);
_logger.LogInformation(_localizer.GetString(ChatHubConstants.LabAuthChatUser));
2019-05-13 14:44:28 +01:00
2024-03-04 01:02:19 +00:00
var userId = _dbContext.Users.First(u => u.UserName == Context.User.Identity.Name).Id;
2019-05-13 14:44:28 +01:00
2023-03-19 17:57:55 +00:00
await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.Connected, userName, null);
isCop = Context.User.IsInRole(Constants.AdminGroupName) ;
if (isCop)
{
2023-03-19 17:57:55 +00:00
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.HubGroupCops);
2016-11-02 11:27:12 +01:00
}
foreach (var uid in _dbContext.CircleMembers.Select(m => m.MemberId))
2019-05-10 09:58:09 +01:00
{
2023-03-19 17:57:55 +00:00
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.HubGroupFollowingPrefix + uid);
2019-05-10 09:58:09 +01:00
}
}
2019-05-13 14:44:28 +01:00
else
{
2023-03-19 17:57:55 +00:00
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.HubGroupAnonymous);
2016-11-01 23:22:46 +01:00
}
_cxManager.OnConnected(Context.ConnectionId, isCop);
2023-03-19 17:57:55 +00:00
await base.OnConnectedAsync();
2016-11-01 23:22:46 +01:00
}
2023-03-19 17:57:55 +00:00
string setUserName(string queryUname = "anon")
2019-05-10 09:58:09 +01:00
{
2019-05-13 14:44:28 +01:00
if (Context.User != null)
2019-05-10 09:58:09 +01:00
if (Context.User.Identity.IsAuthenticated)
{
2019-06-14 10:03:51 +01:00
SetUserName(Context.ConnectionId, Context.User.Identity.Name);
2019-05-10 09:58:09 +01:00
return Context.User.Identity.Name;
}
anonymousSequence++;
2019-06-14 10:03:51 +01:00
var aname = $"{ChatHubConstants.AnonymousUserNamePrefix}{queryUname}{anonymousSequence}";
SetUserName(Context.ConnectionId, aname);
2019-05-13 14:44:28 +01:00
return aname;
2019-05-10 09:58:09 +01:00
}
2019-05-13 14:44:28 +01:00
static long anonymousSequence = 0;
2016-11-02 11:27:12 +01:00
2023-03-19 17:57:55 +00:00
public override async Task OnDisconnectedAsync(Exception ?ex)
2016-11-01 23:22:46 +01:00
{
2016-11-02 11:27:12 +01:00
string userName = Context.User?.Identity.Name;
2019-06-12 11:17:07 +01:00
if (userName != null)
{
2019-06-08 21:51:39 +01:00
var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
var userId = user.Id;
2023-03-19 17:57:55 +00:00
await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.DisConnected, userName, null);
2019-06-08 21:51:39 +01:00
_cxManager.OnDisctonnected(Context.ConnectionId);
2019-06-12 11:17:07 +01:00
}
2023-03-19 17:57:55 +00:00
await base.OnDisconnectedAsync(ex);
2019-05-10 09:58:09 +01:00
}
2016-11-03 14:52:17 +01:00
2023-03-19 17:57:55 +00:00
public async Task Nick(string nickName)
2019-05-20 18:48:03 +01:00
{
if (!InputValidator.ValidateUserName(nickName)) return;
2019-06-17 20:52:51 +01:00
2019-05-24 20:15:48 +01:00
var candidate = "?" + nickName;
2019-06-14 10:03:51 +01:00
if (_cxManager.IsConnected(candidate))
2019-05-20 18:48:03 +01:00
{
2023-03-19 17:57:55 +00:00
await NotifyUser(NotificationTypes.ExistingUserName, nickName, "aborting");
2019-05-24 20:15:48 +01:00
return;
2019-05-20 18:48:03 +01:00
}
2019-06-14 10:03:51 +01:00
_cxManager.SetUserName( Context.ConnectionId, candidate);
2019-05-20 18:48:03 +01:00
}
2019-06-14 10:03:51 +01:00
bool IsPresent(string roomName, string userName)
{
return _cxManager.IsPresent(roomName, userName);
}
2019-05-18 09:42:50 +01:00
2023-03-19 17:57:55 +00:00
public async Task<ChatRoomInfo> Join(string roomName)
2019-05-10 09:58:09 +01:00
{
_logger.LogInformation($"Join:{roomName}");
if (!InputValidator.ValidateRoomName(roomName))
{
_logger.LogError("!InputValidator.ValidateRoomName(roomName)");
return null;
}
2019-06-17 20:52:51 +01:00
2019-06-14 10:03:51 +01:00
var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName;
var user = _cxManager.GetUserName(Context.ConnectionId);
2023-03-19 17:57:55 +00:00
await Groups.AddToGroupAsync(Context.ConnectionId, roomGroupName);
2019-05-10 09:58:09 +01:00
ChatRoomInfo chanInfo;
2019-06-14 10:03:51 +01:00
if (!_cxManager.IsPresent(roomName, user))
2019-05-10 09:58:09 +01:00
{
_logger.LogInformation($"Joining");
chanInfo = _cxManager.Join(roomName, Context.ConnectionId);
2023-03-19 17:57:55 +00:00
await Clients.Group(roomGroupName).SendAsync("notifyRoom", NotificationTypes.UserJoin, roomName, user);
2019-09-14 14:54:39 +01:00
} else {
_logger.LogInformation($"already present");
2019-06-14 10:03:51 +01:00
// in case in an additional connection,
// one only send info on room without
// warning any other user.
_cxManager.TryGetChanInfo(roomName, out chanInfo);
}
_logger.LogInformation($"returning chan info");
2024-03-04 01:02:19 +00:00
await Clients.Caller.SendAsync("joint", chanInfo);
2019-06-14 10:03:51 +01:00
return chanInfo;
2016-11-01 23:22:46 +01:00
}
2016-05-17 18:22:18 +02:00
2019-05-10 09:58:09 +01:00
[Authorize]
2019-06-18 00:24:22 +01:00
public void Register(string room)
2016-11-01 23:22:46 +01:00
{
if (!InputValidator.ValidateRoomName(room)) return ;
2019-05-10 09:58:09 +01:00
var existent = _dbContext.ChatRoom.Any(r => r.Name == room);
2019-05-13 14:44:28 +01:00
if (existent)
{
2019-06-17 20:52:51 +01:00
NotifyUserInRoom(NotificationTypes.Error, room, "already registered.");
2019-05-10 09:58:09 +01:00
return;
}
2025-07-07 07:49:18 +01:00
Debug.Assert(Context.User != null);
string userName = Context.User.GetUserName();
2019-05-13 14:44:28 +01:00
var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
2019-06-14 10:03:51 +01:00
2025-07-07 07:49:18 +01:00
var newroom = new ChatRoom { Name = room, OwnerId = Context.User.GetUserId() };
2019-05-10 09:58:09 +01:00
ChatRoomInfo chanInfo;
2019-06-14 10:03:51 +01:00
if (_cxManager.TryGetChanInfo(room, out chanInfo))
2019-05-10 09:58:09 +01:00
{
// TODO get and require some admin status for current user on this chan
newroom.Topic = chanInfo.Topic;
}
newroom.LatestJoinPart = DateTime.Now;
_dbContext.ChatRoom.Add(newroom);
_dbContext.SaveChanges(user.Id);
2016-11-01 23:22:46 +01:00
}
2019-06-18 14:01:33 +01:00
[Authorize]
2019-06-18 00:24:22 +01:00
public void KickBan(string roomName, string userName, string reason)
2019-06-14 10:03:51 +01:00
{
if (!InputValidator.ValidateRoomName(roomName)) return ;
if (!InputValidator.ValidateUserName(userName)) return ;
if (!InputValidator.ValidateReason(reason)) return;
2019-06-14 10:03:51 +01:00
Kick(roomName, userName, reason);
Ban(roomName, userName, reason);
}
2019-06-18 14:01:33 +01:00
[Authorize]
2023-03-19 17:57:55 +00:00
public async Task Kick(string roomName, string userName, string reason)
2019-05-10 09:58:09 +01:00
{
if (!InputValidator.ValidateRoomName(roomName)) return ;
if (!InputValidator.ValidateUserName(userName)) return ;
if (!InputValidator.ValidateReason(reason)) return;
2019-05-10 09:58:09 +01:00
ChatRoomInfo chanInfo;
2019-06-14 10:03:51 +01:00
var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName;
if (_cxManager.TryGetChanInfo(roomName, out chanInfo))
2019-05-10 09:58:09 +01:00
{
2019-06-14 10:03:51 +01:00
if (!_cxManager.IsPresent(roomName,userName))
2019-05-29 21:41:19 +01:00
{
2019-06-14 10:03:51 +01:00
NotifyErrorToCallerInRoom(roomName, $"{userName} was not found in {roomName}.");
2019-05-29 21:41:19 +01:00
return;
}
2019-06-14 10:03:51 +01:00
// in case of Kick returned false, being not allowed to, or for what ever other else failure,
// the error handler will send an error message while handling the error.
if (!_cxManager.Kick(Context.ConnectionId, userName, roomName, reason)) return;
2019-05-10 09:58:09 +01:00
}
2019-06-14 10:03:51 +01:00
var ukeys = _cxManager.GetConnexionIds(userName);
2019-09-01 01:31:55 +01:00
if (ukeys!=null) foreach(var ukey in ukeys)
2023-03-19 17:57:55 +00:00
await Groups.RemoveFromGroupAsync(ukey, roomGroupName);
await Clients.Group(roomGroupName).SendAsync("notifyRoom", NotificationTypes.Kick, roomName, $"{userName}: {reason}");
2019-05-10 09:58:09 +01:00
}
2019-06-18 14:01:33 +01:00
[Authorize]
2019-06-18 00:24:22 +01:00
public void Ban(string roomName, string userName, string reason)
2019-05-22 17:27:44 +01:00
{
if (!InputValidator.ValidateRoomName(roomName)) return ;
if (!InputValidator.ValidateUserName(userName)) return ;
if (!InputValidator.ValidateReason(reason)) return;
2019-06-14 10:03:51 +01:00
var cxIds = _cxManager.GetConnexionIds(userName);
throw new NotImplementedException();
}
2019-06-18 14:01:33 +01:00
[Authorize]
2019-06-18 00:24:22 +01:00
public void Gline(string userName, string reason)
2019-06-14 10:03:51 +01:00
{
if (!InputValidator.ValidateUserName(userName)) return ;
if (!InputValidator.ValidateReason(reason)) return;
2019-06-14 10:03:51 +01:00
throw new NotImplementedException();
2019-05-22 17:27:44 +01:00
}
2019-06-14 10:03:51 +01:00
2019-06-18 00:24:22 +01:00
public void Part(string roomName, string reason)
2019-06-14 10:03:51 +01:00
{
if (!InputValidator.ValidateRoomName(roomName)) return ;
if (!InputValidator.ValidateReason(reason)) return;
2019-06-14 10:03:51 +01:00
if (_cxManager.Part(Context.ConnectionId, roomName, reason))
{
var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName;
var group = Clients.Group(roomGroupName);
var userName = _cxManager.GetUserName(Context.ConnectionId);
2023-03-19 17:57:55 +00:00
group.SendAsync("notifyRoom", NotificationTypes.UserPart, roomName, $"{userName}: {reason}");
Groups.RemoveFromGroupAsync(Context.ConnectionId, roomGroupName);
2019-06-14 10:03:51 +01:00
}
else {
_logger.LogError("Could not part");
}
}
2019-05-10 09:58:09 +01:00
2019-06-14 10:03:51 +01:00
void NotifyErrorToCallerInRoom(string room, string reason)
2019-05-10 09:58:09 +01:00
{
2019-06-17 20:52:51 +01:00
NotifyUserInRoom(NotificationTypes.Error, room, reason);
2019-06-14 12:34:15 +01:00
_logger.LogError($"NotifyErrorToCallerInRoom: {room}, {reason}");
2019-06-14 10:03:51 +01:00
}
2023-03-19 17:57:55 +00:00
public async Task Send(string roomName, string message)
2019-06-14 10:03:51 +01:00
{
_logger.LogInformation($"Send {roomName} {message}");
if (!InputValidator.ValidateRoomName(roomName)) {
_logger.LogError($"Invalid roomName : {roomName}");
return ;
}
if (!InputValidator.ValidateMessage(message)) {
_logger.LogError($"Invalid message : {message}");
return ;
}
2019-06-14 10:03:51 +01:00
var groupname = ChatHubConstants.HubGroupRomsPrefix + roomName;
ChatRoomInfo chanInfo ;
if (!_cxManager.TryGetChanInfo(roomName, out chanInfo))
2019-05-10 09:58:09 +01:00
{
_logger.LogError($"No such room : {roomName}");
2019-06-15 17:00:00 +01:00
var noChanMsg = _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString();
2019-06-17 20:52:51 +01:00
NotifyUserInRoom(NotificationTypes.Error, roomName, noChanMsg);
2019-06-14 10:03:51 +01:00
return;
2019-05-10 09:58:09 +01:00
}
2019-06-14 10:03:51 +01:00
var userName = _cxManager.GetUserName(Context.ConnectionId);
2019-06-14 13:02:16 +01:00
if (!_cxManager.IsPresent(roomName, userName))
2019-05-10 09:58:09 +01:00
{
_logger.LogError($"{userName} Not present in room : {roomName}");
2019-06-15 17:00:00 +01:00
var notSentMsg = _localizer.GetString(ChatHubConstants.LabnoJoinNoSend).ToString();
2019-06-17 20:52:51 +01:00
NotifyUserInRoom(NotificationTypes.Error, roomName, notSentMsg);
2019-05-10 09:58:09 +01:00
return;
}
2024-03-04 01:02:19 +00:00
var group = Clients.Group(groupname);
var msg = new { Name = userName, Room = roomName, Message = message};
await group.SendAsync("ReceiveMessage", msg);
2019-05-10 09:58:09 +01:00
}
2023-03-19 17:57:55 +00:00
async Task NotifyUser(string type, string targetId, string message)
2019-06-17 20:52:51 +01:00
{
2025-07-07 07:49:18 +01:00
_logger.LogInformation($"notifying user {type} {targetId} : {message}");
2023-03-19 17:57:55 +00:00
await Clients.Caller.SendAsync("notifyUser", type, targetId, message);
2019-06-17 20:52:51 +01:00
}
2023-03-19 17:57:55 +00:00
async Task NotifyUserInRoom(string type, string room, string message)
2019-06-17 20:52:51 +01:00
{
2023-03-19 17:57:55 +00:00
await Clients.Caller.SendAsync("notifyUserInRoom", type, room, message);
2019-06-17 20:52:51 +01:00
}
2019-05-10 09:58:09 +01:00
2016-11-01 23:22:46 +01:00
[Authorize]
2023-03-19 17:57:55 +00:00
public async Task SendPV(string userName, string message)
2016-11-01 23:22:46 +01:00
{
2025-07-07 07:49:18 +01:00
// Authorized code
Debug.Assert(Context.User != null);
_logger.LogInformation($"Sending pv to {userName}");
2019-09-14 14:54:39 +01:00
if (!InputValidator.ValidateUserName(userName))
{
_logger.LogError($"Invalid username : {userName}");
return ;
}
2019-09-14 14:54:39 +01:00
if (!InputValidator.ValidateMessage(message))
{
_logger.LogError($"Invalid message : {message}");
return ;
}
_logger.LogInformation($"Message form is validated.");
2025-07-07 07:49:18 +01:00
var identityUserName = Context.User.GetUserName();
2019-05-24 20:15:48 +01:00
2025-07-07 07:49:18 +01:00
if (userName[0] != '?' && Context.User!=null)
2019-05-24 20:15:48 +01:00
if (!Context.User.IsInRole(Constants.AdminGroupName))
{
2025-07-07 07:49:18 +01:00
2019-05-24 20:15:48 +01:00
var bl = _dbContext.BlackListed
2019-09-14 14:54:39 +01:00
.Include(r => r.User)
.Include(r => r.Owner)
2025-07-07 07:49:18 +01:00
.Where(r => r.User.UserName == identityUserName && r.Owner.UserName == userName)
2019-09-14 14:54:39 +01:00
.Select(r => r.OwnerId);
2019-05-24 20:15:48 +01:00
if (bl.Count() > 0)
{
2025-07-07 07:49:18 +01:00
_logger.LogError($"Black listed : {identityUserName}");
2023-03-19 17:57:55 +00:00
await NotifyUser(NotificationTypes.PrivateMessageDenied, userName, "you are black listed.");
2019-05-24 20:15:48 +01:00
return;
}
_logger.LogInformation("Sender is no black listed");
2019-05-24 20:15:48 +01:00
}
_logger.LogInformation("getting cx id´s");
2019-06-14 10:03:51 +01:00
var cxIds = _cxManager.GetConnexionIds(userName);
if (cxIds==null || cxIds.Count()==0)
_logger.LogError($"No such connected user : {userName}");
else foreach (var connectionId in cxIds)
2019-05-24 20:15:48 +01:00
{
_logger.LogInformation($"cx: {connectionId}");
2019-05-24 20:15:48 +01:00
var cli = Clients.Client(connectionId);
_logger.LogInformation($"cli: {cli.ToString()}");
2025-07-07 07:49:18 +01:00
await cli.SendAsync("addPV", identityUserName, message);
_logger.LogInformation($"Sent pv to cx {connectionId}");
2019-05-24 20:15:48 +01:00
}
2016-11-01 23:22:46 +01:00
}
2019-01-26 14:23:53 +00:00
2019-05-10 09:58:09 +01:00
[Authorize]
2023-03-19 17:57:55 +00:00
public async Task SendStream(string connectionId, long streamId, string message)
2019-01-26 14:23:53 +00:00
{
2025-07-07 07:49:18 +01:00
// Authorized code
Debug.Assert(Context.User != null);
Debug.Assert(Context.User.Identity != null);
if (!InputValidator.ValidateMessage(message)) return;
2019-01-26 14:23:53 +00:00
var sender = Context.User.Identity.Name;
var cli = Clients.Client(connectionId);
2023-03-19 17:57:55 +00:00
await cli.SendAsync("addStreamInfo", sender, streamId, message);
2019-01-26 14:23:53 +00:00
}
2016-11-01 23:22:46 +01:00
}
2016-05-17 18:22:18 +02:00
}