sharp-chat/SharpChat/Commands/CreateChannelCommand.cs

66 lines
2.5 KiB
C#
Raw Normal View History

using SharpChat.Packet;
using System.Linq;
namespace SharpChat.Commands {
public class CreateChannelCommand : IChatCommand {
public bool IsMatch(ChatCommandContext ctx) {
return ctx.NameEquals("create");
}
public void Dispatch(ChatCommandContext ctx) {
if(ctx.User.Can(ChatUserPermissions.CreateChannel)) {
ctx.User.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{ctx.Name}"));
return;
}
string firstArg = ctx.Args.First();
bool createChanHasHierarchy;
if(!ctx.Args.Any() || (createChanHasHierarchy = firstArg.All(char.IsDigit) && ctx.Args.Length < 2)) {
ctx.User.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR));
return;
}
int createChanHierarchy = 0;
if(createChanHasHierarchy)
if(!int.TryParse(firstArg, out createChanHierarchy))
createChanHierarchy = 0;
if(createChanHierarchy > ctx.User.Rank) {
ctx.User.Send(new LegacyCommandResponse(LCR.INSUFFICIENT_HIERARCHY));
return;
}
string createChanName = string.Join('_', ctx.Args.Skip(createChanHasHierarchy ? 1 : 0));
if(!ChatChannel.CheckName(createChanName)) {
ctx.User.Send(new LegacyCommandResponse(LCR.CHANNEL_NAME_INVALID));
return;
}
lock(ctx.Chat.ChannelsAccess) {
if(ctx.Chat.Channels.Any(c => c.NameEquals(createChanName))) {
ctx.User.Send(new LegacyCommandResponse(LCR.CHANNEL_ALREADY_EXISTS, true, createChanName));
return;
}
ChatChannel createChan = new() {
Name = createChanName,
IsTemporary = !ctx.User.Can(ChatUserPermissions.SetChannelPermanent),
Rank = createChanHierarchy,
Owner = ctx.User,
};
ctx.Chat.Channels.Add(createChan);
lock(ctx.Chat.UsersAccess) {
foreach(ChatUser ccu in ctx.Chat.Users.Where(u => u.Rank >= ctx.Channel.Rank))
ccu.Send(new ChannelCreatePacket(ctx.Channel));
}
ctx.Chat.SwitchChannel(ctx.User, createChan, createChan.Password);
ctx.User.Send(new LegacyCommandResponse(LCR.CHANNEL_CREATED, false, createChan.Name));
}
}
}
}