using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using SharedLibraryCore.Helpers; using SharedLibraryCore.Objects; using SharedLibraryCore.Dtos; using SharedLibraryCore.Configuration; using SharedLibraryCore.Interfaces; using SharedLibraryCore.Database.Models; namespace SharedLibraryCore { public abstract class Server { public enum Game { COD = -1, UKN = 0, IW3 = 1, IW4 = 2, IW5 = 3, IW6 = 4, T4 = 5, T5 = 6, T6 = 7, T7 = 8 } public Server(IManager mgr, ServerConfiguration config) { Password = config.Password; IP = config.IPAddress; Port = config.Port; Manager = mgr; Logger = Manager.GetLogger(this.EndPoint); Logger.WriteInfo(this.ToString()); ServerConfig = config; RemoteConnection = new RCon.Connection(IP, Port, Password, Logger, null); Clients = new List(new EFClient[18]); Reports = new List(); ClientHistory = new Queue(); ChatHistory = new List(); NextMessage = 0; CustomSayEnabled = Manager.GetApplicationSettings().Configuration().EnableCustomSayName; CustomSayName = Manager.GetApplicationSettings().Configuration().CustomSayName; InitializeTokens(); InitializeAutoMessages(); } public long EndPoint => Convert.ToInt64($"{IP.Replace(".", "")}{Port}"); //Returns current server port set by `net_port` -- *INT* public int GetPort() { return Port; } //Returns list of all current players public List GetClientsAsList() { return Clients.FindAll(x => x != null && x.NetworkId != 0); } /// /// Add a player to the server's player list /// /// EFClient pulled from memory reading /// True if player added sucessfully, false otherwise abstract public Task OnClientConnected(EFClient P); /// /// Remove player by client number /// /// Client ID of player to be removed /// true if removal succeded, false otherwise abstract public Task OnClientDisconnected(EFClient client); /// /// Get a player by name /// /// EFClient name to search for /// Matching player if found public List GetClientByName(String pName) { if (string.IsNullOrEmpty(pName)) { return new List(); } string[] QuoteSplit = pName.Split('"'); bool literal = false; if (QuoteSplit.Length > 1) { pName = QuoteSplit[1]; literal = true; } if (literal) { return GetClientsAsList().Where(p => p.Name?.ToLower() == pName.ToLower()).ToList(); } return GetClientsAsList().Where(p => (p.Name?.ToLower() ?? "").Contains(pName.ToLower())).ToList(); } virtual public Task ProcessUpdatesAsync(CancellationToken cts) => (Task)Task.CompletedTask; /// /// Process any server event /// /// Event /// True on sucess abstract protected Task ProcessEvent(GameEvent E); abstract public Task ExecuteEvent(GameEvent E); /// /// Send a message to all players /// /// Message to be sent to all players public GameEvent Broadcast(string message, EFClient sender = null) { string formattedMessage = String.Format(RconParser.Configuration.CommandPrefixes.Say, $"{(CustomSayEnabled ? $"{CustomSayName}: " : "")}{message}"); #if DEBUG == true Logger.WriteVerbose(message.StripColors()); #endif var e = new GameEvent() { Type = GameEvent.EventType.Broadcast, Data = formattedMessage, Owner = this, Origin = sender, }; Manager.GetEventHandler().AddEvent(e); return e; } /// /// Send a message to a particular players /// /// Message to send /// EFClient to send message to protected async Task Tell(String Message, EFClient Target) { #if !DEBUG string formattedMessage = String.Format(RconParser.Configuration.CommandPrefixes.Tell, Target.ClientNumber, $"{(CustomSayEnabled ? $"{CustomSayName}: " : "")}{Message}"); if (Target.ClientNumber > -1 && Message.Length > 0 && Target.Level != EFClient.Permission.Console) await this.ExecuteCommandAsync(formattedMessage); #else Logger.WriteVerbose($"{Target.ClientNumber}->{Message.StripColors()}"); await Task.CompletedTask; #endif if (Target.Level == EFClient.Permission.Console) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(Message.StripColors()); Console.ForegroundColor = ConsoleColor.Gray; } // prevent this from queueing up too many command responses if (CommandResult.Count > 15) { CommandResult.RemoveAt(0); } // it was a remote command so we need to add it to the command result queue if (Target.ClientNumber < 0) { CommandResult.Add(new CommandResponseInfo() { Response = Message.StripColors(), ClientId = Target.ClientId }); } } /// /// Send a message to all admins on the server /// /// Message to send out public void ToAdmins(String message) { foreach (var client in GetClientsAsList().Where(c => c.Level > EFClient.Permission.Flagged)) { client.Tell(message); } } /// /// Kick a player from the server /// /// Reason for kicking /// EFClient to kick abstract protected Task Kick(String Reason, EFClient Target, EFClient Origin); /// /// Temporarily ban a player ( default 1 hour ) from the server /// /// Reason for banning the player /// The player to ban abstract protected Task TempBan(String Reason, TimeSpan length, EFClient Target, EFClient Origin); /// /// Perm ban a player from the server /// /// The reason for the ban /// The person to ban /// The person who banned the target abstract protected Task Ban(String Reason, EFClient Target, EFClient Origin, bool isEvade = false); abstract protected Task Warn(String Reason, EFClient Target, EFClient Origin); /// /// Unban a player by npID / GUID /// /// npID of the player /// I don't remember what this is for /// abstract public Task Unban(string reason, EFClient Target, EFClient Origin); /// /// Change the current searver map /// /// Non-localized map name public async Task LoadMap(string mapName) { await this.ExecuteCommandAsync($"map {mapName}"); } public async Task LoadMap(Map newMap) { await this.ExecuteCommandAsync($"map {newMap.Name}"); } /// /// Initalize the macro variables /// abstract public void InitializeTokens(); /// /// Read the map configuration /// protected void InitializeMaps() { Maps = new List(); var gameMaps = Manager.GetApplicationSettings().Configuration().Maps.FirstOrDefault(m => m.Game == GameName); if (gameMaps != null) Maps.AddRange(gameMaps.Maps); } /// /// Initialize the messages to be broadcasted /// protected void InitializeAutoMessages() { BroadcastMessages = new List(); if (ServerConfig.AutoMessages != null) BroadcastMessages.AddRange(ServerConfig.AutoMessages); BroadcastMessages.AddRange(Manager.GetApplicationSettings().Configuration().AutoMessages); } public override string ToString() { return $"{IP}:{Port}"; } protected async Task ScriptLoaded() { try { return (await this.GetDvarAsync("sv_customcallbacks")).Value == "1"; } catch (Exceptions.DvarException) { return false; } } // Objects public IManager Manager { get; protected set; } public ILogger Logger { get; private set; } public ServerConfiguration ServerConfig { get; private set; } public List Maps { get; protected set; } public List Reports { get; set; } public List ChatHistory { get; protected set; } public Queue ClientHistory { get; private set; } public Game GameName { get; protected set; } // Info public string Hostname { get; protected set; } public string Website { get; protected set; } public string Gametype { get; set; } public Map CurrentMap { get; set; } public int ClientNum { get { return Clients.Where(p => p != null).Count(); } } public int MaxClients { get; protected set; } public List Clients { get; protected set; } public string Password { get; private set; } public bool Throttled { get; protected set; } public bool CustomCallback { get; protected set; } public string WorkingDirectory { get; protected set; } public RCon.Connection RemoteConnection { get; protected set; } public IRConParser RconParser { get; protected set; } public IEventParser EventParser { get; set; } public string LogPath { get; protected set; } public bool RestartRequested { get; set; } // Internal public string IP { get; protected set; } public string Version { get; protected set; } public bool IsInitialized { get; set; } protected int Port; protected string FSGame; protected int NextMessage; protected int ConnectionErrors; protected List BroadcastMessages; protected TimeSpan LastMessage; protected DateTime LastPoll; protected ManualResetEventSlim OnRemoteCommandResponse; // only here for performance private readonly bool CustomSayEnabled; private readonly string CustomSayName; //Remote public IList CommandResult = new List(); } }