54 lines
2.1 KiB
C#
54 lines
2.1 KiB
C#
using SharpChat.PacketsS2C;
|
|
using System.Linq;
|
|
|
|
namespace SharpChat.Commands {
|
|
public class UserNickCommand : ISockChatClientCommand {
|
|
public bool IsMatch(SockChatClientCommandContext ctx) {
|
|
return ctx.NameEquals("nick");
|
|
}
|
|
|
|
public void Dispatch(SockChatClientCommandContext ctx) {
|
|
bool setOthersNick = ctx.User.Permissions.HasFlag(UserPermissions.SetOthersNickname);
|
|
|
|
if(!setOthersNick && !ctx.User.Permissions.HasFlag(UserPermissions.SetOwnNickname)) {
|
|
ctx.Chat.SendTo(ctx.User, new CommandNotAllowedErrorS2CPacket(ctx.Name));
|
|
return;
|
|
}
|
|
|
|
UserInfo? targetUser = null;
|
|
int offset = 0;
|
|
|
|
if(setOthersNick && long.TryParse(ctx.Args.FirstOrDefault(), out long targetUserId) && targetUserId > 0) {
|
|
targetUser = ctx.Chat.Users.Get(targetUserId);
|
|
++offset;
|
|
}
|
|
|
|
targetUser ??= ctx.User;
|
|
|
|
if(ctx.Args.Length < offset) {
|
|
ctx.Chat.SendTo(ctx.User, new CommandFormatErrorS2CPacket());
|
|
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 = string.Empty;
|
|
else if(nickStr.Length > 15)
|
|
nickStr = nickStr[..15];
|
|
else if(string.IsNullOrEmpty(nickStr))
|
|
nickStr = string.Empty;
|
|
|
|
if(!string.IsNullOrWhiteSpace(nickStr) && ctx.Chat.Users.Get(name: nickStr, nameTarget: UsersContext.NameTarget.UserAndNickName) != null) {
|
|
ctx.Chat.SendTo(ctx.User, new UserNameInUseErrorS2CPacket(nickStr));
|
|
return;
|
|
}
|
|
|
|
string? previousName = targetUser == ctx.User ? (targetUser.NickName ?? targetUser.UserName) : null;
|
|
ctx.Chat.UpdateUser(targetUser, nickName: nickStr, silent: previousName == null);
|
|
}
|
|
}
|
|
}
|