refacto chathub

This commit is contained in:
Paul Schneider 2026-07-04 15:28:07 +01:00
commit 1d26cbdf3d
8 changed files with 107 additions and 113 deletions

View file

@ -14,11 +14,11 @@ namespace Yavsc.Abstract.Chat
public const string JustCreatedBy = "just created by "; public const string JustCreatedBy = "just created by ";
public const string LabYouNotOp = "you're no op."; public const string LabYouNotOp = "you're no op.";
public const string LabNoSuchUser = "No such user"; public const string LabNoSuchUser = "No such user";
public const string LabNoSuchChan = "No such chan"; public const string LabNoSuchChan = "No such chan";
public const string HopWontKickOp = "Half operator cannot kick any operator"; public const string HopWontKickOp = "Half operator cannot kick any operator";
public const string LabAuthChatUser = "Authenticated chat user"; public const string LabAuthChatUser = "Authenticated chat user";
public const string NoKickOnCop = "No, you won´t, you´ĺl never do kick a cop, it is the bad."; public const string NoKickOnCop = "No, you won´t, you´ĺl never do kick a cop, it is the bad.";
public const string LabnoJoinNoSend = "LabnoJoinNoSend"; public const string LabNoJoinNoSend = "LabnoJoinNoSend";
} }
} }

View file

@ -3,13 +3,13 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Attributes.Validation; using Yavsc.Attributes.Validation;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Messaging; using Yavsc.Models.Messaging;
using Yavsc.Services; using Yavsc.Services;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Yavsc.Server.Helpers; using Yavsc.Server.Helpers;
using static Yavsc.Blogs.Constants; using static Yavsc.Blogs.Constants;
using Yavsc.Server.Hubs;
namespace Yavsc.Blogs.Controllers namespace Yavsc.Blogs.Controllers
{ {
@ -46,7 +46,7 @@ namespace Yavsc.Blogs.Controllers
} }
logger.LogInformation("validated: api/stream/Put: "+filename); logger.LogInformation("validated: api/stream/Put: "+filename);
var userName = User.GetUserName(); var userName = User.GetUserName();
string url = string.Format( string url = string.Format(
"{0}/{1}/{2}", "{0}/{1}/{2}",
Config.UserFilesOptions.RequestPath.ToUriComponent(), Config.UserFilesOptions.RequestPath.ToUriComponent(),
@ -54,7 +54,7 @@ namespace Yavsc.Blogs.Controllers
filename filename
); );
string destDir = HttpContext.User.EnsureDestinationDirectory(filePath); string destDir = HttpContext.User.EnsureDestinationDirectory(filePath);
logger.LogInformation($"Saving flow to {destDir}"); logger.LogInformation($"Saving flow to {destDir}");
var userId = User.GetUserId(); var userId = User.GetUserId();
@ -65,7 +65,7 @@ namespace Yavsc.Blogs.Controllers
sender = userName, sender = userName,
url = url, url = url,
}, $"{userName} is starting a stream!"); }, $"{userName} is starting a stream!");
await liveProcessor.AcceptStream(HttpContext, user, destDir, shortFileName); await liveProcessor.AcceptStream(HttpContext, user, destDir, shortFileName);
return Ok(); return Ok();
} }

View file

@ -41,6 +41,7 @@ using Yavsc.Settings;
using Yavsc.ViewModels.Auth; using Yavsc.ViewModels.Auth;
using IdentityServer8.Models; using IdentityServer8.Models;
using IdentityServer8.EntityFramework.Mappers; using IdentityServer8.EntityFramework.Mappers;
using Yavsc.Server.Hubs;
namespace Yavsc.Extensions; namespace Yavsc.Extensions;

View file

@ -80,7 +80,7 @@ namespace Yavsc.Services
public void OnConnected(string cxId, bool isCop) public void OnConnected(string cxId, bool isCop)
{ {
var username = ChatUserNames[cxId]; var username = ChatUserNames[cxId];
if (!IsConnected(username)) if (!IsConnected(username))
ChatRoomPresence[username] = new List<string>(); ChatRoomPresence[username] = new List<string>();
_isCop[username] = isCop; _isCop[username] = isCop;
} }
@ -101,7 +101,7 @@ namespace Yavsc.Services
return _isCop[userName]; return _isCop[userName];
} }
public void OnDisctonnected(string connectionId) public void OnDisconnected(string connectionId)
{ {
string uname; string uname;
@ -136,7 +136,7 @@ namespace Yavsc.Services
return false; return false;
} }
// FIXME only remove cx, not username, // FIXME only remove cx, not username,
// as long as he might be connected // as long as he might be connected
// from another device, to the same room // from another device, to the same room
chanInfo.Users.Remove(cxId); chanInfo.Users.Remove(cxId);
if (chanInfo.Users.Count == 0) if (chanInfo.Users.Count == 0)
@ -183,7 +183,7 @@ namespace Yavsc.Services
} }
else{ else{
chanInfo.Users.Add(cxId); chanInfo.Users.Add(cxId);
} }
_logger.LogInformation($"existing room joint: {userName}=>{roomName}"); _logger.LogInformation($"existing room joint: {userName}=>{roomName}");
if (!ChatRoomPresence[userName].Contains(roomName)) if (!ChatRoomPresence[userName].Contains(roomName))
ChatRoomPresence[userName].Add(roomName); ChatRoomPresence[userName].Add(roomName);
@ -200,7 +200,7 @@ namespace Yavsc.Services
// room was closed. // room was closed.
var room = _dbContext.ChatRoom.FirstOrDefault(r => r.Name == roomName); var room = _dbContext.ChatRoom.FirstOrDefault(r => r.Name == roomName);
chanInfo = new ChatRoomInfo(); chanInfo = new ChatRoomInfo();
if (room != null) if (room != null)
{ {
@ -244,7 +244,7 @@ namespace Yavsc.Services
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public bool Dehop(string roomName, string userName) public bool DeHop(string roomName, string userName)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
@ -292,12 +292,12 @@ namespace Yavsc.Services
return false; return false;
} }
if (!Channels.TryGetValue(roomName, out chanInfo)) if (!Channels.TryGetValue(roomName, out chanInfo))
{ {
_errorHandler(roomName, _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString()); _errorHandler(roomName, _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString());
return false; return false;
} }
var kickerName = GetUserName(cxId); var kickerName = GetUserName(cxId);
if (!chanInfo.Ops.Contains(cxId)) if (!chanInfo.Ops.Contains(cxId))
if (!chanInfo.Hops.Contains(cxId)) if (!chanInfo.Hops.Contains(cxId))
@ -325,19 +325,19 @@ namespace Yavsc.Services
} }
// all good, time to kick :-) // all good, time to kick :-)
foreach (var ucx in ucxs) { foreach (var ucx in ucxs) {
if (chanInfo.Users.Contains(ucx)) if (chanInfo.Users.Contains(ucx))
chanInfo.Users.Remove(ucx); chanInfo.Users.Remove(ucx);
else if (chanInfo.Ops.Contains(ucx)) else if (chanInfo.Ops.Contains(ucx))
chanInfo.Ops.Remove(ucx); chanInfo.Ops.Remove(ucx);
else if (chanInfo.Hops.Contains(ucx)) else if (chanInfo.Hops.Contains(ucx))
chanInfo.Hops.Remove(ucx); chanInfo.Hops.Remove(ucx);
} }
return true; return true;
} }
} }
} }

View file

@ -1,5 +1,4 @@
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
using Yavsc.Interface; using Yavsc.Interface;
@ -8,6 +7,7 @@ using Yavsc.Models;
using Yavsc.Models.Google.Messaging; using Yavsc.Models.Google.Messaging;
using Yavsc.Models.Haircut; using Yavsc.Models.Haircut;
using Yavsc.Models.Messaging; using Yavsc.Models.Messaging;
using Yavsc.Server.Hubs;
namespace Yavsc.Services namespace Yavsc.Services
{ {
@ -92,25 +92,25 @@ namespace Yavsc.Services
_logger.LogDebug($"Sending to {user.UserName} <{user.Email}> : {body}"); _logger.LogDebug($"Sending to {user.UserName} <{user.Email}> : {body}");
result.message_id = await _emailSender.SendEmailAsync(user.UserName, user.Email, result.message_id = await _emailSender.SendEmailAsync(user.UserName, user.Email,
$"{ev.Sender} (un client) vous demande un rendez-vous", $"{ev.Sender} (un client) vous demande un rendez-vous",
body + Environment.NewLine); body + Environment.NewLine);
response.success++; response.success++;
var cxids = _cxManager.GetConnexionIds(user.UserName); var cxIds = _cxManager.GetConnexionIds(user.UserName);
if (cxids == null) if (cxIds == null)
{ {
_logger.LogDebug($"no cx to {user.UserName} <{user.Email}> "); _logger.LogDebug($"no cx to {user.UserName} <{user.Email}> ");
} }
else else
{ {
_logger.LogDebug($"Sending signal to {string.Join(" ", cxids)} : " + JsonConvert.SerializeObject(ev)); _logger.LogDebug($"Sending signal to {string.Join(" ", cxIds)} : " + JsonConvert.SerializeObject(ev));
foreach (var cxid in cxids) foreach (var cxId in cxIds)
{ {
// from usr asp.net Id : var hubClient = hubContext.Clients.User(userId); // from usr asp.net Id : var hubClient = hubContext.Clients.User(userId);
var hubClient = hubContext.Clients.Client(cxid); var hubClient = hubContext.Clients.Client(cxId);
var data = new Dictionary<string, object> var data = new Dictionary<string, object>
{ {
["event"] = JsonConvert.SerializeObject(ev) ["event"] = JsonConvert.SerializeObject(ev)
@ -152,22 +152,9 @@ namespace Yavsc.Services
return await NotifyEvent<HairCutQueryEvent>(userIds, ev); return await NotifyEvent<HairCutQueryEvent>(userIds, ev);
} }
public async Task<MessageWithPayloadResponse> NotifyAsync(IEnumerable<string> userIds, IEvent yaev) public async Task<MessageWithPayloadResponse> NotifyAsync(IEnumerable<string> userIds, IEvent yavscEvent)
{ {
return await NotifyEvent<IEvent>(userIds, yaev); return await NotifyEvent<IEvent>(userIds, yavscEvent);
} }
/* SMS with Twilio:
public Task SendSmsAsync(TwilioSettings twilioSettigns, string number, string message)
{
var Twilio = new TwilioRestClient(twilioSettigns.AccountSID, twilioSettigns.Token);
var result = Twilio.SendMessage( twilioSettigns.SMSAccountFrom, number, message);
// Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
Trace.TraceInformation(result.Status);
// Twilio doesn't currently have an async API, so return success.
return Task.FromResult(result.Status != "Failed");
} */
} }
} }

View file

@ -19,23 +19,19 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
#pragma warning disable CS4014 // Dans la mesure où cet appel n'est pas attendu, l'exécution de la méthode actuelle continue avant la fin de l'appel
namespace Yavsc namespace Yavsc.Server.Hubs
{ {
using System.Diagnostics; using System.Diagnostics;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Models;
using Models.Chat;
using Yavsc.Abstract.Chat; using Yavsc.Abstract.Chat;
using Yavsc.Helpers; using Yavsc.Models;
using Yavsc.Models.Chat;
using Yavsc.Server.Helpers; using Yavsc.Server.Helpers;
using Yavsc.Services; using Yavsc.Services;
public partial class ChatHub : Hub, IDisposable public partial class ChatHub : Hub, IDisposable
@ -47,21 +43,23 @@ namespace Yavsc
public HubInputValidator InputValidator { get; } public HubInputValidator InputValidator { get; }
public ChatHub(ApplicationDbContext dbContext, public ChatHub(ApplicationDbContext dbContext,
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
IStringLocalizerFactory stringLocalizerFactory, IStringLocalizerFactory stringLocalizerFactory,
IConnexionManager connexionManager) IConnexionManager connexionManager)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_localizer = stringLocalizerFactory.Create(typeof(ChatHub)); _localizer = stringLocalizerFactory.Create(typeof(ChatHub));
_cxManager = connexionManager; _cxManager = connexionManager;
_cxManager.SetErrorHandler ((context, error) => _cxManager.SetErrorHandler ((context, error) =>
{ {
NotifyUser(NotificationTypes.Error, context, error); NotifyUser(NotificationTypes.Error, context, error);
}); });
_logger = loggerFactory.CreateLogger<ChatHub>(); _logger = loggerFactory.CreateLogger<ChatHub>();
InputValidator = new HubInputValidator { NotifyUser = async (type, target, msg) => await this.NotifyUser(type, target, msg) }; InputValidator = new HubInputValidator(_localizer) {
NotifyUser = async (type, target, msg) => await this.NotifyUser(type, target, msg) };
} }
void SetUserName(string cxId, string userName) void SetUserName(string cxId, string userName)
@ -114,14 +112,14 @@ namespace Yavsc
return Context.User.Identity.Name; return Context.User.Identity.Name;
} }
anonymousSequence++; anonymousSequence++;
var aname = $"{ChatHubConstants.AnonymousUserNamePrefix}{queryUname}{anonymousSequence}"; var anonymousName = $"{ChatHubConstants.AnonymousUserNamePrefix}{queryUname}{anonymousSequence}";
SetUserName(Context.ConnectionId, aname); SetUserName(Context.ConnectionId, anonymousName);
return aname; return anonymousName;
} }
static long anonymousSequence = 0; static long anonymousSequence = 0;
public override async Task OnDisconnectedAsync(Exception ?ex) public override async Task OnDisconnectedAsync(Exception ex)
{ {
string userName = Context.User?.Identity.Name; string userName = Context.User?.Identity.Name;
if (userName != null) if (userName != null)
@ -130,12 +128,12 @@ namespace Yavsc
var userId = user.Id; var userId = user.Id;
await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.DisConnected, userName, null); await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.DisConnected, userName, null);
_cxManager.OnDisctonnected(Context.ConnectionId); _cxManager.OnDisconnected(Context.ConnectionId);
} }
await base.OnDisconnectedAsync(ex); await base.OnDisconnectedAsync(ex);
} }
public async Task Nick(string nickName) public async Task Nick(string nickName)
{ {
if (!InputValidator.ValidateUserName(nickName)) return; if (!InputValidator.ValidateUserName(nickName)) return;
@ -156,33 +154,33 @@ namespace Yavsc
public async Task<ChatRoomInfo> Join(string roomName) public async Task<ChatRoomInfo> Join(string roomName)
{ {
_logger.LogInformation($"Join:{roomName}"); _logger.LogInformation($"Join:{roomName}");
if (!InputValidator.ValidateRoomName(roomName)) if (!InputValidator.ValidateRoomName(roomName))
{ {
_logger.LogError("!InputValidator.ValidateRoomName(roomName)"); _logger.LogError("!InputValidator.ValidateRoomName(roomName)");
return null; return null;
} }
var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName; var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName;
var user = _cxManager.GetUserName(Context.ConnectionId); var user = _cxManager.GetUserName(Context.ConnectionId);
await Groups.AddToGroupAsync(Context.ConnectionId, roomGroupName); await Groups.AddToGroupAsync(Context.ConnectionId, roomGroupName);
ChatRoomInfo chanInfo; ChatRoomInfo channelInfo;
if (!_cxManager.IsPresent(roomName, user)) if (!_cxManager.IsPresent(roomName, user))
{ {
_logger.LogInformation($"Joining"); _logger.LogInformation($"Joining");
chanInfo = _cxManager.Join(roomName, Context.ConnectionId); channelInfo = _cxManager.Join(roomName, Context.ConnectionId);
await Clients.Group(roomGroupName).SendAsync("notifyRoom", NotificationTypes.UserJoin, roomName, user); await Clients.Group(roomGroupName).SendAsync("notifyRoom", NotificationTypes.UserJoin, roomName, user);
} else { } else {
_logger.LogInformation($"already present"); _logger.LogInformation($"already present");
// in case in an additional connection, // in case in an additional connection,
// one only send info on room without // one only send info on room without
// warning any other user. // warning any other user.
_cxManager.TryGetChanInfo(roomName, out chanInfo); _cxManager.TryGetChanInfo(roomName, out channelInfo);
} }
_logger.LogInformation($"returning chan info"); _logger.LogInformation($"returning channel info");
await Clients.Caller.SendAsync("joint", chanInfo); await Clients.Caller.SendAsync("joint", channelInfo);
return chanInfo; return channelInfo;
} }
[Authorize] [Authorize]
@ -192,23 +190,23 @@ namespace Yavsc
var existent = _dbContext.ChatRoom.Any(r => r.Name == room); var existent = _dbContext.ChatRoom.Any(r => r.Name == room);
if (existent) if (existent)
{ {
NotifyUserInRoom(NotificationTypes.Error, room, "already registered."); NotifyUserInRoom(NotificationTypes.Error, room, "already registered.");
return; return;
} }
Debug.Assert(Context.User != null); Debug.Assert(Context.User != null);
string userName = Context.User.GetUserName(); string userName = Context.User.GetUserName();
var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName); var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
var newroom = new ChatRoom { Name = room, OwnerId = Context.User.GetUserId() }; var newRoom = new ChatRoom { Name = room, OwnerId = Context.User.GetUserId() };
ChatRoomInfo chanInfo; ChatRoomInfo channelInfo;
if (_cxManager.TryGetChanInfo(room, out chanInfo)) if (_cxManager.TryGetChanInfo(room, out channelInfo))
{ {
// TODO get and require some admin status for current user on this chan // TODO get and require some admin status for current user on this channel
newroom.Topic = chanInfo.Topic; newRoom.Topic = channelInfo.Topic;
} }
newroom.LatestJoinPart = DateTime.Now; newRoom.LatestJoinPart = DateTime.Now;
_dbContext.ChatRoom.Add(newroom); _dbContext.ChatRoom.Add(newRoom);
_dbContext.SaveChanges(user.Id); _dbContext.SaveChanges(user.Id);
} }
@ -228,22 +226,22 @@ namespace Yavsc
if (!InputValidator.ValidateRoomName(roomName)) return ; if (!InputValidator.ValidateRoomName(roomName)) return ;
if (!InputValidator.ValidateUserName(userName)) return ; if (!InputValidator.ValidateUserName(userName)) return ;
if (!InputValidator.ValidateReason(reason)) return; if (!InputValidator.ValidateReason(reason)) return;
ChatRoomInfo chanInfo; ChatRoomInfo channelInfo;
var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName; var roomGroupName = ChatHubConstants.HubGroupRomsPrefix + roomName;
if (_cxManager.TryGetChanInfo(roomName, out chanInfo)) if (_cxManager.TryGetChanInfo(roomName, out channelInfo))
{ {
if (!_cxManager.IsPresent(roomName,userName)) if (!_cxManager.IsPresent(roomName,userName))
{ {
NotifyErrorToCallerInRoom(roomName, $"{userName} was not found in {roomName}."); NotifyErrorToCallerInRoom(roomName, $"{userName} was not found in {roomName}.");
return; return;
} }
// in case of Kick returned false, being not allowed to, or for what ever other else failure, // 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. // the error handler will send an error message while handling the error.
if (!_cxManager.Kick(Context.ConnectionId, userName, roomName, reason)) return; if (!_cxManager.Kick(Context.ConnectionId, userName, roomName, reason)) return;
} }
var ukeys = _cxManager.GetConnexionIds(userName); var cxIds = _cxManager.GetConnexionIds(userName);
if (ukeys!=null) foreach(var ukey in ukeys) if (cxIds!=null) foreach(var cx in cxIds)
await Groups.RemoveFromGroupAsync(ukey, roomGroupName); await Groups.RemoveFromGroupAsync(cx, roomGroupName);
await Clients.Group(roomGroupName).SendAsync("notifyRoom", NotificationTypes.Kick, roomName, $"{userName}: {reason}"); await Clients.Group(roomGroupName).SendAsync("notifyRoom", NotificationTypes.Kick, roomName, $"{userName}: {reason}");
} }
@ -258,13 +256,13 @@ namespace Yavsc
} }
[Authorize] [Authorize]
public void Gline(string userName, string reason) public void GLine(string userName, string reason)
{ {
if (!InputValidator.ValidateUserName(userName)) return ; if (!InputValidator.ValidateUserName(userName)) return ;
if (!InputValidator.ValidateReason(reason)) return; if (!InputValidator.ValidateReason(reason)) return;
throw new NotImplementedException(); throw new NotImplementedException();
} }
public void Part(string roomName, string reason) public void Part(string roomName, string reason)
{ {
if (!InputValidator.ValidateRoomName(roomName)) return ; if (!InputValidator.ValidateRoomName(roomName)) return ;
@ -299,9 +297,9 @@ namespace Yavsc
_logger.LogError($"Invalid message : {message}"); _logger.LogError($"Invalid message : {message}");
return ; return ;
} }
var groupname = ChatHubConstants.HubGroupRomsPrefix + roomName; var groupName = ChatHubConstants.HubGroupRomsPrefix + roomName;
ChatRoomInfo chanInfo ; ChatRoomInfo channelInfo ;
if (!_cxManager.TryGetChanInfo(roomName, out chanInfo)) if (!_cxManager.TryGetChanInfo(roomName, out channelInfo))
{ {
_logger.LogError($"No such room : {roomName}"); _logger.LogError($"No such room : {roomName}");
var noChanMsg = _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString(); var noChanMsg = _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString();
@ -312,11 +310,11 @@ namespace Yavsc
if (!_cxManager.IsPresent(roomName, userName)) if (!_cxManager.IsPresent(roomName, userName))
{ {
_logger.LogError($"{userName} Not present in room : {roomName}"); _logger.LogError($"{userName} Not present in room : {roomName}");
var notSentMsg = _localizer.GetString(ChatHubConstants.LabnoJoinNoSend).ToString(); var notSentMsg = _localizer.GetString(ChatHubConstants.LabNoJoinNoSend).ToString();
NotifyUserInRoom(NotificationTypes.Error, roomName, notSentMsg); NotifyUserInRoom(NotificationTypes.Error, roomName, notSentMsg);
return; return;
} }
var group = Clients.Group(groupname); var group = Clients.Group(groupName);
var msg = new { Name = userName, Room = roomName, Message = message}; var msg = new { Name = userName, Room = roomName, Message = message};
await group.SendAsync("ReceiveMessage", msg); await group.SendAsync("ReceiveMessage", msg);
} }
@ -339,12 +337,12 @@ namespace Yavsc
Debug.Assert(Context.User != null); Debug.Assert(Context.User != null);
_logger.LogInformation($"Sending pv to {userName}"); _logger.LogInformation($"Sending pv to {userName}");
if (!InputValidator.ValidateUserName(userName)) if (!InputValidator.ValidateUserName(userName))
{ {
_logger.LogError($"Invalid username : {userName}"); _logger.LogError($"Invalid username : {userName}");
return ; return ;
} }
if (!InputValidator.ValidateMessage(message)) if (!InputValidator.ValidateMessage(message))
{ {
_logger.LogError($"Invalid message : {message}"); _logger.LogError($"Invalid message : {message}");
return ; return ;
@ -399,3 +397,4 @@ namespace Yavsc
} }
} }
#pragma warning restore CS4014 // Dans la mesure où cet appel n'est pas attendu, l'exécution de la méthode actuelle continue avant la fin de l'appel

View file

@ -19,40 +19,47 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
using System; using Microsoft.Extensions.Localization;
using System.Linq;
using Yavsc;
namespace Yavsc namespace Yavsc.Server.Hubs
{ {
public class HubInputValidator { public class HubInputValidator {
public IStringLocalizer _locator;
public HubInputValidator(IStringLocalizer locator) {
_locator = locator;
}
public Action<string,string,string> NotifyUser {get;set;} public Action<string,string,string> NotifyUser {get;set;}
public bool ValidateRoomName (string roomName) public bool ValidateRoomName (string roomName)
{ {
bool valid = ValidateStringLength(roomName,1,25); bool valid = ValidateStringLength(roomName,1,25);
if (valid) valid = IsLetterOrDigit(roomName); if (valid) valid = IsLetterOrDigit(roomName);
if (!valid) NotifyUser(NotificationTypes.Error, "roomName", ChatHubLabels.InvalidRoomName); if (!valid) NotifyUser(NotificationTypes.Error, "roomName", _locator.GetString(ChatHubLabels.InvalidRoomName));
return valid; return valid;
} }
public bool ValidateUserName (string userName) public bool ValidateUserName (string userName)
{ {
bool valid = true; bool valid = true;
if (userName.Length<1 || userName[0] == '?' && userName.Length<2) valid = false; if (userName.Length<1 || userName[0] == '?' && userName.Length<2) valid = false;
if (valid) { if (valid) {
string suname = (userName[0] == '?') ? userName.Substring(1) : userName; string suname = (userName[0] == '?') ? userName.Substring(1) : userName;
if (valid) valid = ValidateStringLength(suname, 1,12); if (valid) valid = ValidateStringLength(suname, 1,12);
if (valid) valid = IsLetterOrDigit(userName); if (valid) valid = IsLetterOrDigit(userName);
} }
if (!valid) NotifyUser(NotificationTypes.Error, "userName" , ChatHubLabels.InvalidUserName); if (!valid)
NotifyUser(
NotificationTypes.Error,
"userName",
_locator.GetString(ChatHubLabels.InvalidUserName));
return valid; return valid;
} }
public bool ValidateMessage (string message) public bool ValidateMessage (string message)
{ {
if (!ValidateStringLength(message, 1, 10240)) if (!ValidateStringLength(message, 1, 10240))
{ {
NotifyUser(NotificationTypes.Error, "message", ChatHubLabels.InvalidMessage); NotifyUser(NotificationTypes.Error, "message", _locator.GetString(ChatHubLabels.InvalidMessage));
return false; return false;
} }
return true; return true;

View file

@ -11,9 +11,9 @@ namespace Yavsc.Services
void OnConnected(string cxId, bool isCop); void OnConnected(string cxId, bool isCop);
bool IsConnected(string candidate); bool IsConnected(string candidate);
void OnDisctonnected (string cxId); void OnDisconnected (string cxId);
bool IsPresent(string roomName, string userName); bool IsPresent(string roomName, string userName);
ChatRoomInfo Join(string roomName, string cxId); ChatRoomInfo Join(string roomName, string cxId);
bool Part(string cxId, string roomName, string reason); bool Part(string cxId, string roomName, string reason);
@ -23,13 +23,13 @@ namespace Yavsc.Services
bool Op(string roomName, string userName); bool Op(string roomName, string userName);
bool Deop(string roomName, string userName); bool Deop(string roomName, string userName);
bool Hop(string roomName, string userName); bool Hop(string roomName, string userName);
bool Dehop(string roomName, string userName); bool DeHop(string roomName, string userName);
bool TryGetChanInfo(string room, out ChatRoomInfo chanInfo); bool TryGetChanInfo(string room, out ChatRoomInfo channelInfo);
IEnumerable<string> GetConnexionIds(string userName); IEnumerable<string> GetConnexionIds(string userName);
void SetErrorHandler(Action<string,string> errorHandler); void SetErrorHandler(Action<string,string> errorHandler);
IEnumerable<ChannelShortInfo> ListChannels(string pattern); IEnumerable<ChannelShortInfo> ListChannels(string pattern);
} }
} }