98 lines
3.4 KiB
C#
98 lines
3.4 KiB
C#
using SharpChat.Commands;
|
|
using SharpChat.Config;
|
|
using SharpChat.Events;
|
|
using SharpChat.EventStorage;
|
|
using SharpChat.Packet;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace SharpChat.PacketHandlers
|
|
{
|
|
public class SendMessageHandler : IChatPacketHandler {
|
|
private readonly CachedValue<int> MaxMessageLength;
|
|
|
|
private List<IChatCommand> Commands { get; } = new();
|
|
|
|
public SendMessageHandler(CachedValue<int> maxMsgLength) {
|
|
MaxMessageLength = maxMsgLength ?? throw new ArgumentNullException(nameof(maxMsgLength));
|
|
}
|
|
|
|
public void AddCommand(IChatCommand command) {
|
|
Commands.Add(command ?? throw new ArgumentNullException(nameof(command)));
|
|
}
|
|
|
|
public void AddCommands(IEnumerable<IChatCommand> commands) {
|
|
Commands.AddRange(commands ?? throw new ArgumentNullException(nameof(commands)));
|
|
}
|
|
|
|
public bool IsMatch(ChatPacketHandlerContext ctx) {
|
|
return ctx.CheckPacketId("2");
|
|
}
|
|
|
|
public void Handle(ChatPacketHandlerContext ctx) {
|
|
string[] args = ctx.SplitText(3);
|
|
|
|
ChatUser user = ctx.Connection.User;
|
|
|
|
// No longer concats everything after index 1 with \t, no previous implementation did that either
|
|
string messageText = args.ElementAtOrDefault(2);
|
|
|
|
if(user == null || !user.Can(ChatUserPermissions.SendMessage) || string.IsNullOrWhiteSpace(messageText))
|
|
return;
|
|
|
|
// Extra validation step, not necessary at all but enforces proper formatting in SCv1.
|
|
if(!long.TryParse(args[1], out long mUserId) || user.UserId != mUserId)
|
|
return;
|
|
|
|
ctx.Chat.ContextAccess.Wait();
|
|
try {
|
|
if(!ctx.Chat.UserLastChannel.TryGetValue(user.UserId, out ChatChannel channel)
|
|
&& !ctx.Chat.IsInChannel(user, channel)
|
|
/*|| (user.IsSilenced && !user.Can(ChatUserPermissions.SilenceUser))*/)
|
|
return;
|
|
|
|
if(user.Status != ChatUserStatus.Online)
|
|
ctx.Chat.UpdateUser(user, status: ChatUserStatus.Online);
|
|
|
|
int maxMsgLength = MaxMessageLength;
|
|
if(messageText.Length > maxMsgLength)
|
|
messageText = messageText[..maxMsgLength];
|
|
|
|
messageText = messageText.Trim();
|
|
|
|
#if DEBUG
|
|
Logger.Write($"<{ctx.Connection.Id} {user.UserName}> {messageText}");
|
|
#endif
|
|
|
|
if(messageText.StartsWith("/")) {
|
|
ChatCommandContext context = new(messageText, ctx.Chat, user, ctx.Connection, channel);
|
|
|
|
IChatCommand command = null;
|
|
|
|
foreach(IChatCommand cmd in Commands)
|
|
if(cmd.IsMatch(context)) {
|
|
command = cmd;
|
|
break;
|
|
}
|
|
|
|
if(command != null) {
|
|
command.Dispatch(context);
|
|
return;
|
|
}
|
|
}
|
|
|
|
ctx.Chat.DispatchEvent(new MessageCreateEvent(
|
|
SharpId.Next(),
|
|
channel,
|
|
user,
|
|
DateTimeOffset.Now,
|
|
messageText,
|
|
false, false, false
|
|
));
|
|
} finally {
|
|
ctx.Chat.ContextAccess.Release();
|
|
}
|
|
}
|
|
}
|
|
}
|