IW4M-Admin/SharedLibraryCore/Server.cs

349 lines
13 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Serilog.Context;
2018-04-08 02:44:42 -04:00
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Database.Models;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using Data.Models;
2018-04-08 02:44:42 -04:00
namespace SharedLibraryCore
{
public abstract class Server : IGameServer
{
public enum Game
{
COD = -1,
UKN = 0,
IW3 = 1,
IW4 = 2,
IW5 = 3,
IW6 = 4,
T4 = 5,
T5 = 6,
T6 = 7,
2021-04-16 14:35:51 -04:00
T7 = 8,
SHG1 = 9
}
public Server(ILogger<Server> logger, SharedLibraryCore.Interfaces.ILogger deprecatedLogger,
ServerConfiguration config, IManager mgr, IRConConnectionFactory rconConnectionFactory,
IGameLogReaderFactory gameLogReaderFactory)
{
Password = config.Password;
IP = config.IPAddress;
Port = config.Port;
Manager = mgr;
Logger = deprecatedLogger;
ServerConfig = config;
RemoteConnection = rconConnectionFactory.CreateConnection(IP, Port, Password);
EventProcessing = new SemaphoreSlim(1, 1);
Clients = new List<EFClient>(new EFClient[64]);
Reports = new List<Report>();
ClientHistory = new Queue<PlayerHistory>();
2018-03-09 03:01:12 -05:00
ChatHistory = new List<ChatInfo>();
NextMessage = 0;
CustomSayEnabled = Manager.GetApplicationSettings().Configuration().EnableCustomSayName;
CustomSayName = Manager.GetApplicationSettings().Configuration().CustomSayName;
this.gameLogReaderFactory = gameLogReaderFactory;
ServerLogger = logger;
InitializeTokens();
InitializeAutoMessages();
}
public long EndPoint => Convert.ToInt64($"{IP.Replace(".", "")}{Port}");
/// <summary>
/// Returns list of all current players
/// </summary>
/// <returns></returns>
public List<EFClient> GetClientsAsList()
{
return Clients.FindAll(x => x != null && x.NetworkId != 0);
}
2015-08-20 15:23:13 -04:00
/// <summary>
/// Add a player to the server's player list
/// </summary>
/// <param name="P">EFClient pulled from memory reading</param>
2015-08-20 15:23:13 -04:00
/// <returns>True if player added sucessfully, false otherwise</returns>
public abstract Task<EFClient> OnClientConnected(EFClient P);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Remove player by client number
/// </summary>
/// <param name="cNum">Client ID of player to be removed</param>
/// <returns>true if removal succeded, false otherwise</returns>
public abstract Task OnClientDisconnected(EFClient client);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Get a player by name
/// todo: make this an extension
2015-08-20 15:23:13 -04:00
/// </summary>
/// <param name="pName">EFClient name to search for</param>
2015-08-20 15:23:13 -04:00
/// <returns>Matching player if found</returns>
public List<EFClient> GetClientByName(String pName)
{
if (string.IsNullOrEmpty(pName))
{
return new List<EFClient>();
}
pName = pName.Trim().StripColors();
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<bool> ProcessUpdatesAsync(CancellationToken cts) => (Task<bool>)Task.CompletedTask;
2015-08-20 15:23:13 -04:00
/// <summary>
/// Process any server event
/// </summary>
/// <param name="E">Event</param>
/// <returns>True on sucess</returns>
protected abstract Task<bool> ProcessEvent(GameEvent E);
public abstract Task ExecuteEvent(GameEvent E);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Send a message to all players
/// </summary>
/// <param name="message">Message to be sent to all players</param>
public GameEvent Broadcast(string message, EFClient sender = null)
{
2020-10-17 11:47:56 -04:00
string formattedMessage = string.Format(RconParser.Configuration.CommandPrefixes.Say ?? "", $"{(CustomSayEnabled && GameName == Game.IW4 ? $"{CustomSayName}: " : "")}{message.FixIW4ForwardSlash()}");
ServerLogger.LogDebug("All->" + message.StripColors());
var e = new GameEvent()
{
Type = GameEvent.EventType.Broadcast,
Data = formattedMessage,
Owner = this,
Origin = sender,
};
Manager.AddEvent(e);
return e;
}
public void Broadcast(IEnumerable<string> messages, EFClient sender = null)
{
foreach (var message in messages)
{
#pragma warning disable 4014
Broadcast(message, sender).WaitAsync();
#pragma warning restore 4014
}
}
2015-08-20 15:23:13 -04:00
/// <summary>
/// Send a message to a particular players
/// </summary>
2019-08-02 19:04:34 -04:00
/// <param name="message">Message to send</param>
/// <param name="target">EFClient to send message to</param>
protected async Task Tell(string message, EFClient target)
{
if (!Utilities.IsDevelopment)
{
var formattedMessage = string.Format(RconParser.Configuration.CommandPrefixes.Tell,
target.ClientNumber,
$"{(CustomSayEnabled && GameName == Game.IW4 ? $"{CustomSayName}: " : "")}{message.FixIW4ForwardSlash()}");
if (target.ClientNumber > -1 && message.Length > 0 && target.Level != EFClient.Permission.Console)
await this.ExecuteCommandAsync(formattedMessage);
}
else
{
ServerLogger.LogDebug("Tell[{clientNumber}]->{message}", target.ClientNumber, message.StripColors());
}
2019-08-02 19:04:34 -04:00
if (target.Level == EFClient.Permission.Console)
{
Console.ForegroundColor = ConsoleColor.Green;
using (LogContext.PushProperty("Server", ToString()))
{
ServerLogger.LogInformation("Command output received: {message}", message);
}
2019-08-02 19:04:34 -04:00
Console.WriteLine(message.StripColors());
Console.ForegroundColor = ConsoleColor.Gray;
}
}
2015-08-20 15:23:13 -04:00
/// <summary>
/// Send a message to all admins on the server
/// </summary>
/// <param name="message">Message to send out</param>
public void ToAdmins(String message)
{
foreach (var client in GetClientsAsList().Where(c => c.Level > EFClient.Permission.Flagged))
2015-08-20 15:23:13 -04:00
{
client.Tell(message);
2015-08-20 15:23:13 -04:00
}
}
2015-08-20 15:23:13 -04:00
/// <summary>
/// Kick a player from the server
/// </summary>
/// <param name="reason">Reason for kicking</param>
/// <param name="Target">EFClient to kick</param>
public Task Kick(String reason, EFClient Target, EFClient Origin) => Kick(reason, Target, Origin, null);
public abstract Task Kick(string reason, EFClient target, EFClient origin, EFPenalty originalPenalty);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Temporarily ban a player ( default 1 hour ) from the server
/// </summary>
/// <param name="Reason">Reason for banning the player</param>
/// <param name="Target">The player to ban</param>
abstract public Task TempBan(String Reason, TimeSpan length, EFClient Target, EFClient Origin);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Perm ban a player from the server
/// </summary>
/// <param name="Reason">The reason for the ban</param>
/// <param name="Target">The person to ban</param>
/// <param name="Origin">The person who banned the target</param>
abstract public Task Ban(String Reason, EFClient Target, EFClient Origin, bool isEvade = false);
2015-08-20 15:23:13 -04:00
abstract public Task Warn(String Reason, EFClient Target, EFClient Origin);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Unban a player by npID / GUID
/// </summary>
/// <param name="npID">npID of the player</param>
/// <param name="Target">I don't remember what this is for</param>
/// <returns></returns>
abstract public Task Unban(string reason, EFClient Target, EFClient Origin);
2015-08-20 15:23:13 -04:00
/// <summary>
/// Change the current searver map
2015-08-20 15:23:13 -04:00
/// </summary>
/// <param name="mapName">Non-localized map name</param>
public async Task LoadMap(string mapName)
{
await this.ExecuteCommandAsync($"map {mapName}");
}
2015-08-20 15:23:13 -04:00
/// <summary>
/// Initalize the macro variables
/// </summary>
abstract public void InitializeTokens();
2015-08-20 15:23:13 -04:00
/// <summary>
/// Read the map configuration
/// </summary>
protected void InitializeMaps()
{
Maps = new List<Map>();
var gameMaps = Manager.GetApplicationSettings().Configuration().Maps.FirstOrDefault(m => m.Game == GameName);
if (gameMaps != null)
Maps.AddRange(gameMaps.Maps);
}
2015-08-20 15:23:13 -04:00
/// <summary>
/// Initialize the messages to be broadcasted
/// </summary>
protected void InitializeAutoMessages()
{
BroadcastMessages = new List<String>();
2018-05-10 01:34:29 -04:00
if (ServerConfig.AutoMessages != null)
BroadcastMessages.AddRange(ServerConfig.AutoMessages);
BroadcastMessages.AddRange(Manager.GetApplicationSettings().Configuration().AutoMessages);
}
public override string ToString()
{
return $"{IP}:{Port}";
}
protected async Task<bool> ScriptLoaded()
{
try
{
return (await this.GetDvarAsync("sv_customcallbacks", "0")).Value == "1";
}
catch (Exceptions.DvarException)
{
return false;
}
}
// Objects
public IManager Manager { get; protected set; }
[Obsolete]
public SharedLibraryCore.Interfaces.ILogger Logger { get; private set; }
public ServerConfiguration ServerConfig { get; private set; }
public List<Map> Maps { get; protected set; } = new List<Map>();
public List<Report> Reports { get; set; }
2018-03-09 03:01:12 -05:00
public List<ChatInfo> ChatHistory { get; protected set; }
public Queue<PlayerHistory> ClientHistory { get; private set; }
public Game GameName { get; set; }
// Info
private string hostname;
public string Hostname { get => ServerConfig.CustomHostname ?? hostname; protected set => hostname = value; }
public string Website { get; protected set; }
public string Gametype { get; set; }
public string GamePassword { get; protected set; }
public Map CurrentMap { get; set; }
public int ClientNum
{
get
{
return Clients.Where(p => p != null/* && !p.IsBot*/).Count();
}
}
public int MaxClients { get; protected set; }
public List<EFClient> Clients { get; protected set; }
public string Password { get; private set; }
public bool Throttled { get; protected set; }
public bool CustomCallback { get; protected set; }
2018-03-06 02:22:19 -05:00
public string WorkingDirectory { get; protected set; }
public IRConConnection RemoteConnection { get; protected set; }
public IRConParser RconParser { get; set; }
public IEventParser EventParser { get; set; }
2018-09-06 14:25:58 -04:00
public string LogPath { get; protected set; }
public bool RestartRequested { get; set; }
public SemaphoreSlim EventProcessing { get; private set; }
// Internal
public string IP { get; protected set; }
public string Version { get; protected set; }
public bool IsInitialized { get; set; }
protected readonly ILogger ServerLogger;
public int Port { get; private set; }
protected string FSGame;
protected int NextMessage;
protected int ConnectionErrors;
protected List<string> BroadcastMessages;
protected TimeSpan LastMessage;
protected DateTime LastPoll;
2018-05-10 01:34:29 -04:00
protected ManualResetEventSlim OnRemoteCommandResponse;
protected IGameLogReaderFactory gameLogReaderFactory;
// only here for performance
private readonly bool CustomSayEnabled;
private readonly string CustomSayName;
}
}