56 lines
2.2 KiB
C#
56 lines
2.2 KiB
C#
using SharpChat.Packet;
|
|
using System.Linq;
|
|
|
|
namespace SharpChat.Commands {
|
|
public class NickCommand : IChatCommand {
|
|
public bool IsMatch(ChatCommandContext ctx) {
|
|
return ctx.NameEquals("nick");
|
|
}
|
|
|
|
public void Dispatch(ChatCommandContext ctx) {
|
|
bool setOthersNick = ctx.User.Can(ChatUserPermissions.SetOthersNickname);
|
|
|
|
if(!setOthersNick && !ctx.User.Can(ChatUserPermissions.SetOwnNickname)) {
|
|
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{ctx.Name}"));
|
|
return;
|
|
}
|
|
ChatUser targetUser = null;
|
|
int offset = 0;
|
|
|
|
if(setOthersNick && long.TryParse(ctx.Args.FirstOrDefault(), out long targetUserId) && targetUserId > 0) {
|
|
lock(ctx.Chat.UsersAccess)
|
|
targetUser = ctx.Chat.Users.FirstOrDefault(u => u.UserId == targetUserId);
|
|
++offset;
|
|
}
|
|
|
|
targetUser ??= ctx.User;
|
|
|
|
if(ctx.Args.Length < offset) {
|
|
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR));
|
|
return;
|
|
}
|
|
|
|
string nickStr = string.Join('_', ctx.Args.Skip(offset))
|
|
.Replace("\n", string.Empty).Replace("\r", string.Empty)
|
|
.Replace("\f", string.Empty).Replace("\t", string.Empty)
|
|
.Replace(' ', '_').Trim();
|
|
|
|
if(nickStr == targetUser.Username)
|
|
nickStr = null;
|
|
else if(nickStr.Length > 15)
|
|
nickStr = nickStr[..15];
|
|
else if(string.IsNullOrEmpty(nickStr))
|
|
nickStr = null;
|
|
|
|
lock(ctx.Chat.UsersAccess)
|
|
if(!string.IsNullOrWhiteSpace(nickStr) && ctx.Chat.Users.Any(u => u.NameEquals(nickStr))) {
|
|
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.NAME_IN_USE, true, nickStr));
|
|
return;
|
|
}
|
|
|
|
string previousName = targetUser == ctx.User ? (targetUser.Nickname ?? targetUser.Username) : null;
|
|
targetUser.Nickname = nickStr;
|
|
ctx.Chat.SendTo(ctx.Channel, new UserUpdatePacket(targetUser, previousName));
|
|
}
|
|
}
|
|
}
|