Skip to content
This repository has been archived by the owner on Jul 4, 2023. It is now read-only.

Commit

Permalink
Merge pull request #5 from Jesus-QC/dev
Browse files Browse the repository at this point in the history
Up
  • Loading branch information
Jesus-QC authored Nov 21, 2021
2 parents 3a3f011 + e7db8c0 commit 1a22cf0
Show file tree
Hide file tree
Showing 15 changed files with 143 additions and 104 deletions.
4 changes: 2 additions & 2 deletions SecretAdmin/API/Features/Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ protected Module()

public virtual void OnEnabled()
{
Log.Raw($"The module {Name} [{Version}] by {Author} was enabled.", ConsoleColor.DarkMagenta);
Log.SpectreRaw($"The module {Name} [{Version}] by {Author} has been enabled.", "lightcyan1");
}

public virtual void OnDisabled()
{
Log.Raw($"The module {Name} [{Version}] by {Author} was disabled.", ConsoleColor.DarkMagenta);
Log.SpectreRaw($"The module {Name} [{Version}] by {Author} has been disabled.", "lightcyan1");
}

public virtual void OnRegisteringCommands()
Expand Down
26 changes: 16 additions & 10 deletions SecretAdmin/API/ModuleManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using SecretAdmin.API.Features;
using SecretAdmin.Features.Console;
using SecretAdmin.Features.Program;
using Spectre.Console;
using Module = SecretAdmin.API.Features.Module;

namespace SecretAdmin.API
Expand All @@ -16,29 +17,32 @@ public static class ModuleManager
public static void LoadAll()
{
Log.WriteLine();
Log.Raw("Loading modules dependencies!", ConsoleColor.DarkCyan);
Log.SpectreRaw("Loading module dependencies...", "lightpink1");

var startTime = DateTime.Now;
var count = 0;

foreach (var file in Directory.GetFiles(Paths.ModulesDependenciesFolder, "*.dll"))
{
try
{
var assembly = Assembly.UnsafeLoadFrom(file);
Log.Raw($"Dependency {assembly.GetName().Name} ({assembly.GetName().Version}) has been loaded!");
count++;
Log.SpectreRaw($"Dependency {assembly.GetName().Name} ({assembly.GetName().Version}) has been loaded!", "lightcyan1");
}
catch (Exception e)
{
Log.Raw($"Couldn't load the dependency in the path {file}\n{e}", ConsoleColor.Red);
throw;
Log.SpectreRaw($"Couldn't load the dependency in the path {file}", "deeppink2");
AnsiConsole.WriteException(e);
}
}
Log.Raw($"Dependencies loaded in {(DateTime.Now - startTime).TotalMilliseconds}ms", ConsoleColor.Cyan);
Log.Raw("Loading modules!", ConsoleColor.DarkCyan);

Log.SpectreRaw(count > 0 ? $"{count} Dependencies loaded in {(DateTime.Now - startTime).TotalMilliseconds}ms" : "No Dependencies found.", "cornflowerblue");
Log.SpectreRaw("Loading modules...", "lightpink1");

startTime = DateTime.Now;

count = 0;

foreach (var file in Directory.GetFiles(Paths.ModulesFolder, "*.dll"))
{
var assembly = Assembly.Load(File.ReadAllBytes(file));
Expand All @@ -59,15 +63,17 @@ public static void LoadAll()
module?.OnRegisteringCommands();

Modules.Add(module);
count++;
}
}
catch (Exception e)
{
Log.Raw(e, ConsoleColor.Red);
Log.SpectreRaw($"Couldn't load the module in the path {file}", "deeppink2");
AnsiConsole.WriteException(e);
}
}

Log.Raw($"Modules loaded in {(DateTime.Now - startTime).TotalMilliseconds}ms", ConsoleColor.Cyan);
Log.SpectreRaw(count > 0 ? $"{count} Modules loaded in {(DateTime.Now - startTime).TotalMilliseconds}ms" : "No Modules found.", "cornflowerblue");
}
}
}
90 changes: 54 additions & 36 deletions SecretAdmin/Features/Console/Log.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Text.RegularExpressions;
using SecretAdmin.API.Events.EventArgs;
using Spectre.Console;
using SConsole = System.Console;
using static SecretAdmin.Program;
using SEvents = SecretAdmin.API.Events.Handlers.Server;
Expand All @@ -22,83 +23,92 @@ public static void Intro()
_`, :' '_.'' ..': ..'' '_.': : : :: :' .; :: ,. ,. :: :: ,. :
`.__.'`.__.'`.__.':_; `.__.':_; :_;:_;`.__.':_;:_;:_;:_;:_;:_;
");
Write($"Secret Admin - Version v{SecretAdmin.Program.Version}");
WriteLine(" by Jesus-QC", ConsoleColor.Blue);
WriteLine("Released under MIT License Copyright © Jesus-QC 2021", ConsoleColor.Red);
Write($"[cyan]Secret Admin - Version v{SecretAdmin.Program.Version}[/]");
WriteLine(" [lightgoldenrod1]by Jesus-QC[/]");
WriteLine("[thistle1]Released under MIT License Copyright © Jesus-QC 2021[/]");

if (!ConfigManager.SecretAdminConfig.ManualStart)
return;

WriteLine("Press any key to continue.", ConsoleColor.Green);
SConsole.ReadKey();
if (ConfigManager.SecretAdminConfig.ManualStart)
ReadKey();
}

public static void Input(string message, string title = "SERVER")
{
SConsole.ForegroundColor = ConsoleColor.Yellow;
SConsole.Write($"{title} >>> ");
Raw(message, ConsoleColor.Magenta, false);
Write($"\n{title} >>> ", ConsoleColor.Yellow);
WriteLine(message.EscapeMarkup(), ConsoleColor.Magenta);
}

public static void Alert(object message, bool showTimeStamp = true)
{
if (showTimeStamp)
Write($"[{DateTime.Now:T}] ", ConsoleColor.DarkRed);
Write($"[[{DateTime.Now:T}]] ", ConsoleColor.DarkRed);

Write("[SecretAdmin] ", ConsoleColor.Yellow);
Write("[[SecretAdmin]] ", ConsoleColor.Yellow);
SConsole.Write("(Alert) ");
WriteLine(message, ConsoleColor.Gray);
}

public static void ReadKey()
{
SConsole.ForegroundColor = ConsoleColor.White;
WriteLine();
AnsiConsole.Write(new Rule("[darkslategray3]Press any key to continue.[/]"));
SConsole.ReadKey();
}

// Alerts

public static void Raw(object message, ConsoleColor color = ConsoleColor.White, bool showTimeStamp = true) => WriteLine(showTimeStamp ? $"[{DateTime.Now:T}] {message}" : message, color);

public static void Raw(object message, ConsoleColor color = ConsoleColor.White, bool showTimeStamp = true) => WriteLine(showTimeStamp ? $"[[{DateTime.Now:T}]] {message.ToString().EscapeMarkup()}" : message, color);
public static void SpectreRaw(object message, string color = "white", bool showTimeStamp = false, string timestampColor = "white")
{
WriteLine(showTimeStamp ? $"[{timestampColor}][[{DateTime.Now:T}]][/] [{color}]{message.ToString().EscapeMarkup()}[/]" : $"[{color}]{message.ToString().EscapeMarkup()}[/]");
}

private static void Info(string title, string message)
{
Write($"[{DateTime.Now:T}] ", ConsoleColor.Magenta);
Write("[INFO] ", ConsoleColor.DarkCyan);
Write($"{title} ", ConsoleColor.Yellow);
WriteLine(message);
Write($"[[{DateTime.Now:T}]] ", ConsoleColor.Magenta);
Write("[[INFO]] ", ConsoleColor.Cyan);
Write($"[{title}] ", ConsoleColor.Yellow);
WriteLine(message.EscapeMarkup());
}

private static void Error(string title, string message)
{
Write($"[{DateTime.Now:T}] ", ConsoleColor.DarkYellow);
Write("[ERROR] ", ConsoleColor.Red);
Write($"{title} ", ConsoleColor.Yellow);
WriteLine(message, ConsoleColor.Red);
Write($"[[{DateTime.Now:T}]] ", ConsoleColor.Magenta);
Write("[deeppink2][[ERROR]][/] ");
Write($"[{title}] ", ConsoleColor.Yellow);
WriteLine($"[deeppink2]{message.EscapeMarkup()}[/]");
}

private static void Debug(string title, string message)
{
Write($"[{DateTime.Now:T}] ", ConsoleColor.DarkGray);
Write("[DEBUG] ", ConsoleColor.Blue);
Write($"{title} ", ConsoleColor.DarkGray);
WriteLine(message, ConsoleColor.Cyan);
Write($"[grey58][[{DateTime.Now:T}]][/] ");
Write("[[DEBUG]] ", ConsoleColor.Blue);
Write($"[grey58][{title}][/] ");
WriteLine(message.EscapeMarkup(), ConsoleColor.Cyan);
}

private static void Warn(string title, string message)
{
Write($"[{DateTime.Now:T}] ", ConsoleColor.Yellow);
Write("[WARN] ", ConsoleColor.Magenta);
Write($"{title} ", ConsoleColor.DarkYellow);
WriteLine(message, ConsoleColor.Yellow);
Write($"[[{DateTime.Now:T}]] ", ConsoleColor.Magenta);
Write("[gold1][[WARN]][/] ");
Write($"[plum2][{title}][/] ", ConsoleColor.DarkYellow);
WriteLine(message.EscapeMarkup(), ConsoleColor.Yellow);
}

public static void WriteLine(object message = null, ConsoleColor color = ConsoleColor.White)
{
SConsole.ForegroundColor = color;
SConsole.WriteLine(message);
ProgramLogger?.AppendLog(message, true);
AnsiConsole.MarkupLine(message?.ToString() ?? "");
}

public static void Write(object message = null, ConsoleColor color = ConsoleColor.White)
{
SConsole.ForegroundColor = color;
SConsole.Write(message);
ProgramLogger?.AppendLog(message);
AnsiConsole.Markup(message?.ToString() ?? "");
}

public static T GetOption<T>(string msg, T def) => AnsiConsole.Ask($"[lightcyan3]{msg}[/]", def);
public static bool GetConfirm(string msg, bool def) => AnsiConsole.Confirm($"[lightcyan3]{msg}[/]", def);

public static void HandleMessage(string message, byte code)
{
Expand Down Expand Up @@ -136,7 +146,15 @@ public static void HandleMessage(string message, byte code)
}
else
{
Raw(message, (ConsoleColor)code);
switch (code)
{
case 10:
SpectreRaw(message, "springgreen3", true, "slateblue1");
break;
default:
Raw(message, (ConsoleColor)code);
break;
}
}
}

Expand Down
1 change: 0 additions & 1 deletion SecretAdmin/Features/Program/ArgumentsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
{
public static class ArgumentsManager
{
// TODO: this
/*
* Arguments:
* --reconfigure -r
Expand Down
9 changes: 8 additions & 1 deletion SecretAdmin/Features/Program/InputManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using SecretAdmin.Features.Console;
using SecretAdmin.Features.Server.Enums;

namespace SecretAdmin.Features.Program
{
Expand All @@ -12,7 +13,7 @@ public static void Start()

if (string.IsNullOrWhiteSpace(input))
continue;

input = input.TrimStart();

Log.DeletePrevConsoleLine();
Expand All @@ -24,6 +25,12 @@ public static void Start()

private static void ManageInput(string input)
{
if (SecretAdmin.Program.Server.Status == ServerStatus.Restarting)
{
Log.Alert("The server hasn't been initialized yet.");
return;
}

Log.Input(input);
SecretAdmin.Program.Server.Socket.SendMessage(input);
}
Expand Down
5 changes: 3 additions & 2 deletions SecretAdmin/Features/Program/Paths.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using System;
using System.IO;

namespace SecretAdmin.Features.Program
{
Expand All @@ -15,7 +16,7 @@ public static class Paths

public static void Load()
{
MainFolder = "SecretAdmin";
MainFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SecretAdmin");
LogsFolder = Path.Combine(MainFolder, "Logs");
ServerLogsFolder = Path.Combine(LogsFolder, "Server");
ProgramLogsFolder = Path.Combine(LogsFolder, "SecretAdmin");
Expand Down
54 changes: 15 additions & 39 deletions SecretAdmin/Features/Program/ProgramIntroduction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.IO;
using SecretAdmin.Features.Console;
using SecretAdmin.Features.Program.Config;
using Spectre.Console;

namespace SecretAdmin.Features.Program
{
Expand All @@ -22,63 +23,38 @@ public static void ShowIntroduction()

var cfg = new MainConfig
{
AutoUpdater = GetOption("Do you want to enable the auto updater?"),
ManualStart = GetOption("Do you want to manually have to enter a key to start the server?"),
SafeShutdown = GetOption("Do you want to safe shutdown the game processes?"),
ArchiveLogsDays = GetOption("In how many days the logs should be archived?", "1"),
RestartOnCrash = GetOption("Should the server automatically restart itself when it crashes?"),
RestartWithLowMemory = GetOption("Should the server restart itself when it has low memory?"),
MaxDefaultMemory = GetOption("Max memory the server can use, in MB.", "2048")
AutoUpdater = Log.GetConfirm("Do you want to enable the auto updater?", true),
ManualStart = Log.GetConfirm("Do you want to manually have to enter a key to start the server?", false),
SafeShutdown = Log.GetConfirm("Do you want to safe shutdown the game processes?", true),
ArchiveLogsDays = Log.GetOption("In how many days the logs should be archived?", 1),
RestartOnCrash = Log.GetConfirm("Should the server automatically restart itself when it crashes?", true),
RestartWithLowMemory = Log.GetConfirm("Should the server restart itself when it has low memory?", true),
MaxDefaultMemory = Log.GetOption("Max memory the server can use, in MB.", 2048)
};

Paths.Load();
SecretAdmin.Program.ConfigManager.SaveConfig(cfg);

Log.WriteLine();
Log.Raw("That were all the program configs! You can edit them always in /SecretAdmin/config.yml.", ConsoleColor.Cyan);
Log.Alert("Time to edit the default server configs.");
Log.SpectreRaw($"That were all the program configs! You can edit them always in {Paths.ProgramConfig}.","skyblue2");
Log.Alert("Time to edit the default server configs.\n");

// Server Options

var srvConfig = new ServerConfig()
{
Port = (uint)GetOption("Which should be the default server port?", "7777"),
RoundsToRestart = GetOption("In how many rounds the server should restart itself. -1 disable, 0 every round", "-1")
Port = Log.GetOption("Which should be the default server port?", (uint)7777),
RoundsToRestart = Log.GetOption("In how many rounds the server should restart itself. -1 disable, 0 every round", -1)
};

Log.SpectreRaw($"That were your default server configs! You can edit them always in {Path.Combine(Paths.ServerConfigsFolder, "default.yml")}.","skyblue2");
SecretAdmin.Program.ConfigManager.SaveServerConfig(srvConfig);

// Start the server

Log.Alert("Ok, thats all! Time to enjoy the server :)");
System.Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine("Press any key to continue.");
System.Console.ReadKey();
Directory.CreateDirectory("SecretAdmin");
}

private static bool GetOption(string msg)
{
START:
Log.Alert($"{msg} yes (y) / no (n)");
var opt = System.Console.ReadLine()?.ToLower();
if (!string.IsNullOrWhiteSpace(opt) && (opt[0] == 'y' || opt[0] == 'n'))
return opt[0] == 'y';
Log.Alert("An error occurred parsing the input, please try again!");
goto START;
}

private static int GetOption(string msg, string def)
{
START:
Log.Alert($"{msg} introduce a number. (default = {def})");
var opt = System.Console.ReadLine();
if (string.IsNullOrWhiteSpace(opt))
return int.Parse(def);
if (int.TryParse(opt, out var z))
return z;
Log.Alert("An error occurred parsing the input, please try again!");
goto START;
Log.ReadKey();
Directory.CreateDirectory(Paths.MainFolder);
}
}
}
Loading

0 comments on commit 1a22cf0

Please sign in to comment.