Fixed some text and added some missing texts to commands. Added new command to clear screen and formated code.

This commit is contained in:
2023-07-03 14:39:50 +03:00
parent 4a6a12baae
commit 298e557260
36 changed files with 1503 additions and 1542 deletions

View File

@@ -1,57 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.Interfaces;
using PluginManager.Loaders;
namespace PluginManager.Others.Actions
namespace PluginManager.Others.Actions;
public class InternalActionManager
{
public class InternalActionManager
public Dictionary<string, ICommandAction> Actions = new();
public ActionsLoader loader;
public InternalActionManager(string path, string extension)
{
public ActionsLoader loader;
public Dictionary<string, ICommandAction> Actions = new Dictionary<string, ICommandAction>();
loader = new ActionsLoader(path, extension);
}
public InternalActionManager(string path, string extension)
public async Task Initialize()
{
loader.ActionLoadedEvent += OnActionLoaded;
var m_actions = await loader.Load();
if (m_actions == null) return;
foreach (var action in m_actions)
Actions.Add(action.ActionName, action);
}
private void OnActionLoaded(string name, string typeName, bool success, Exception? e)
{
if (!success)
{
loader = new ActionsLoader(path, extension);
Config.Logger.Error(e);
return;
}
public async Task Initialize()
Config.Logger.Log($"Action {name} loaded successfully", typeName);
}
public async Task<string> Execute(string actionName, params string[]? args)
{
if (!Actions.ContainsKey(actionName))
{
loader.ActionLoadedEvent += OnActionLoaded;
var m_actions = await loader.Load();
if(m_actions == null) return;
foreach(var action in m_actions)
Actions.Add(action.ActionName, action);
Config.Logger.Log($"Action {actionName} not found", "InternalActionManager", LogLevel.WARNING);
return "Action not found";
}
private void OnActionLoaded(string name, string typeName, bool success, Exception? e)
try
{
if (!success)
{
Config.Logger.Error(e);
return;
}
Config.Logger.Log($"Action {name} loaded successfully", typeName, LogLevel.INFO);
await Actions[actionName].Execute(args);
return "Action executed";
}
public async Task<string> Execute(string actionName, params string[]? args)
catch (Exception e)
{
if (!Actions.ContainsKey(actionName))
{
Config.Logger.Log($"Action {actionName} not found", "InternalActionManager", LogLevel.WARNING);
return "Action not found";
}
try{
await Actions[actionName].Execute(args);
return "Action executed";
}catch(Exception e){
Config.Logger.Log(e.Message, "InternalActionManager", LogLevel.ERROR);
return e.Message;
}
Config.Logger.Log(e.Message, "InternalActionManager", LogLevel.ERROR);
return e.Message;
}
}
}

View File

@@ -4,136 +4,138 @@ using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace PluginManager.Others
namespace PluginManager.Others;
public static class ArchiveManager
{
public static class ArchiveManager
private static string? archiveFolder;
public static bool isInitialized { get; private set; }
public static void Initialize()
{
public static bool isInitialized { get; private set; }
private static string? archiveFolder;
if (isInitialized) throw new Exception("ArchiveManager is already initialized");
public static void Initialize()
if (!Config.Data.ContainsKey("ArchiveFolder"))
Config.Data["ArchiveFolder"] = "./Data/PAKS/";
archiveFolder = Config.Data["ArchiveFolder"];
isInitialized = true;
}
/// <summary>
/// Read data from a file that is inside an archive (ZIP format)
/// </summary>
/// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<string?> ReadFromPakAsync(string FileName, string archFile)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
archFile = archiveFolder + archFile;
if (!File.Exists(archFile))
throw new Exception("Failed to load file !");
try
{
if (isInitialized) throw new Exception("ArchiveManager is already initialized");
if (!Config.Data.ContainsKey("ArchiveFolder"))
Config.Data["ArchiveFolder"] = "./Data/PAKS/";
archiveFolder = Config.Data["ArchiveFolder"];
isInitialized = true;
}
/// <summary>
/// Read data from a file that is inside an archive (ZIP format)
/// </summary>
/// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<string?> ReadFromPakAsync(string FileName, string archFile)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
archFile = archiveFolder + archFile;
if (!File.Exists(archFile))
throw new Exception("Failed to load file !");
try
{
string? textValue = null;
using (var fs = new FileStream(archFile, FileMode.Open))
string? textValue = null;
using (var fs = new FileStream(archFile, FileMode.Open))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Read))
{
foreach (var entry in zip.Entries)
if (entry.Name == FileName || entry.FullName == FileName)
using (var s = entry.Open())
using (var reader = new StreamReader(s))
{
textValue = await reader.ReadToEndAsync();
reader.Close();
s.Close();
fs.Close();
}
using (var reader = new StreamReader(s))
{
textValue = await reader.ReadToEndAsync();
reader.Close();
s.Close();
fs.Close();
}
}
return textValue;
}
catch (Exception ex)
{
Config.Logger.Log(ex.Message, "Archive Manager", LogLevel.ERROR); // Write the error to a file
await Task.Delay(100);
return await ReadFromPakAsync(FileName, archFile);
}
return textValue;
}
/// <summary>
/// Extract zip to location
/// </summary>
/// <param name="zip">The zip location</param>
/// <param name="folder">The target location</param>
/// <param name="progress">The progress that is updated as a file is processed</param>
/// <param name="type">The type of progress</param>
/// <returns></returns>
public static async Task ExtractArchive(string zip, string folder, IProgress<float> progress,
UnzipProgressType type)
catch (Exception ex)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
Directory.CreateDirectory(folder);
using (var archive = ZipFile.OpenRead(zip))
Config.Logger.Log(ex.Message, "Archive Manager", LogLevel.ERROR); // Write the error to a file
await Task.Delay(100);
return await ReadFromPakAsync(FileName, archFile);
}
}
/// <summary>
/// Extract zip to location
/// </summary>
/// <param name="zip">The zip location</param>
/// <param name="folder">The target location</param>
/// <param name="progress">The progress that is updated as a file is processed</param>
/// <param name="type">The type of progress</param>
/// <returns></returns>
public static async Task ExtractArchive(
string zip, string folder, IProgress<float> progress,
UnzipProgressType type)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
Directory.CreateDirectory(folder);
using (var archive = ZipFile.OpenRead(zip))
{
if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES)
{
if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES)
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/")) // it is a folder
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
else
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
}
catch (Exception ex)
{
Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}", "Archive Manager", LogLevel.ERROR);
}
currentZIPFile++;
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentZIPFile / totalZIPFiles * 100);
}
}
else if (type == UnzipProgressType.PERCENTAGE_FROM_TOTAL_SIZE)
{
ulong zipSize = 0;
foreach (var entry in archive.Entries)
zipSize += (ulong)entry.CompressedLength;
ulong currentSize = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/"))
{
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
continue;
}
if (entry.FullName.EndsWith("/")) // it is a folder
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
else
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentSize += (ulong)entry.CompressedLength;
}
catch (Exception ex)
{
Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}", "Archive Manager", LogLevel.ERROR);
Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}",
"Archive Manager", LogLevel.ERROR);
}
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentSize / zipSize * 100);
currentZIPFile++;
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentZIPFile / totalZIPFiles * 100);
}
}
else if (type == UnzipProgressType.PERCENTAGE_FROM_TOTAL_SIZE)
{
ulong zipSize = 0;
foreach (var entry in archive.Entries)
zipSize += (ulong)entry.CompressedLength;
ulong currentSize = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/"))
{
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
continue;
}
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentSize += (ulong)entry.CompressedLength;
}
catch (Exception ex)
{
Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}",
"Archive Manager", LogLevel.ERROR);
}
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentSize / zipSize * 100);
}
}
}

View File

@@ -1,27 +1,20 @@
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others
namespace PluginManager.Others;
public class DBCommandExecutingArguments
{
public class DBCommandExecutingArguments
public DBCommandExecutingArguments(
SocketCommandContext context, string cleanContent, string commandUsed, string[]? arguments)
{
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get;init; }
public string[]? arguments { get;init; }
public DBCommandExecutingArguments(SocketCommandContext context, string cleanContent, string commandUsed, string[]? arguments)
{
this.context = context;
this.cleanContent = cleanContent;
this.commandUsed = commandUsed;
this.arguments = arguments;
}
this.context = context;
this.cleanContent = cleanContent;
this.commandUsed = commandUsed;
this.arguments = arguments;
}
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
}

View File

@@ -39,4 +39,4 @@ public enum InternalActionRunType
{
ON_STARTUP,
ON_CALL
}
}

View File

@@ -19,6 +19,15 @@ public static class Functions
/// </summary>
public static readonly string dataFolder = @"./Data/Resources/";
public static Color RandomColor
{
get
{
var random = new Random();
return new Color(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}
}
/// <summary>
/// Get the Operating system you are runnin on
/// </summary>
@@ -43,9 +52,10 @@ public static class Functions
/// <exception cref="ArgumentOutOfRangeException">Triggered if <paramref name="bufferSize" /> is less then or equal to 0</exception>
/// <exception cref="InvalidOperationException">Triggered if <paramref name="stream" /> is not readable</exception>
/// <exception cref="ArgumentException">Triggered in <paramref name="destination" /> is not writable</exception>
public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null,
CancellationToken cancellationToken = default)
public static async Task CopyToOtherStreamAsync(
this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null,
CancellationToken cancellationToken = default)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (destination == null) throw new ArgumentNullException(nameof(destination));
@@ -54,10 +64,11 @@ public static class Functions
if (!destination.CanWrite)
throw new ArgumentException("Destination stream is not writable", nameof(destination));
var buffer = new byte[bufferSize];
var buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken)
.ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
@@ -102,9 +113,9 @@ public static class Functions
return (obj ?? default)!;
}
public static T SelectRandomValueOf<T> ()
public static T SelectRandomValueOf<T>()
{
var enums = Enum.GetValues(typeof(T));
var enums = Enum.GetValues(typeof(T));
var random = new Random();
return (T)enums.GetValue(random.Next(enums.Length));
}
@@ -114,13 +125,4 @@ public static class Functions
Random random = new();
return values[random.Next(values.Length)];
}
public static Discord.Color RandomColor
{
get
{
Random random = new Random();
return new Discord.Color(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}
}
}
}

View File

@@ -1,53 +1,60 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others.Logger
namespace PluginManager.Others.Logger;
public class DBLogger
{
public class DBLogger
public delegate void LogHandler(string message, LogLevel logType);
private readonly string _errFolder;
private readonly string _logFolder;
private readonly List<LogMessage> ErrorHistory = new();
private readonly List<LogMessage> LogHistory = new();
public DBLogger()
{
private List<LogMessage> LogHistory = new List<LogMessage>();
private List<LogMessage> ErrorHistory = new List<LogMessage>();
_logFolder = Config.Data["LogFolder"];
_errFolder = Config.Data["ErrorFolder"];
}
public IReadOnlyList<LogMessage> Logs => LogHistory;
public IReadOnlyList<LogMessage> Errors => ErrorHistory;
public IReadOnlyList<LogMessage> Logs => LogHistory;
public IReadOnlyList<LogMessage> Errors => ErrorHistory;
public delegate void LogHandler(string message, LogLevel logType);
public event LogHandler LogEvent;
public event LogHandler LogEvent;
private string _logFolder;
private string _errFolder;
public void Log(string message, string sender = "unknown", LogLevel type = LogLevel.INFO)
{
Log(new LogMessage(message, type, sender));
}
public DBLogger()
{
_logFolder = Config.Data["LogFolder"];
_errFolder = Config.Data["ErrorFolder"];
}
public void Error(Exception? e)
{
Log(e.Message, e.Source, LogLevel.ERROR);
}
public void Log(string message, string sender = "unknown", LogLevel type = LogLevel.INFO) => Log(new LogMessage(message, type, sender));
public void Error(Exception? e) => Log(e.Message, e.Source, LogLevel.ERROR);
public void Log(LogMessage message)
{
if (LogEvent is not null)
LogEvent?.Invoke(message.Message, message.Type);
public void Log(LogMessage message)
{
if(LogEvent is not null)
LogEvent?.Invoke(message.Message, message.Type);
if (message.Type != LogLevel.ERROR && message.Type != LogLevel.CRITICAL)
LogHistory.Add(message);
else
ErrorHistory.Add(message);
}
if (message.Type != LogLevel.ERROR && message.Type != LogLevel.CRITICAL)
LogHistory.Add(message);
else
ErrorHistory.Add(message);
}
public void Log(string message, object sender, LogLevel type = LogLevel.NONE)
{
Log(message, sender.GetType().Name, type);
}
public void Log(string message, object sender, LogLevel type = LogLevel.NONE) => Log(message, sender.GetType().Name, type);
public async void SaveToFile()
{
await Functions.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", LogHistory);
await Functions.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", ErrorHistory);
}
public async void SaveToFile()
{
await Functions.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json",
LogHistory);
await Functions.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json",
ErrorHistory);
}
}

View File

@@ -1,47 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others.Logger
namespace PluginManager.Others.Logger;
public class LogMessage
{
public class LogMessage
public LogMessage(string message, LogLevel type)
{
public string Message { get; set; }
public LogLevel Type { get; set; }
public string Time { get; set; }
public string Sender { get; set; }
public LogMessage(string message, LogLevel type)
{
Message = message;
Type = type;
Time = DateTime.Now.ToString("HH:mm:ss");
}
Message = message;
Type = type;
Time = DateTime.Now.ToString("HH:mm:ss");
}
public LogMessage(string message, LogLevel type, string sender) : this(message, type)
{
Sender = sender;
}
public LogMessage(string message, LogLevel type, string sender) : this(message, type)
{
Sender = sender;
}
public override string ToString()
{
return $"[{Time}] {Message}";
}
public string Message { get; set; }
public LogLevel Type { get; set; }
public string Time { get; set; }
public string Sender { get; set; }
public static explicit operator LogMessage(string message)
{
return new LogMessage(message, LogLevel.INFO);
}
public override string ToString()
{
return $"[{Time}] {Message}";
}
public static explicit operator LogMessage((string message, LogLevel type) tuple)
{
return new LogMessage(tuple.message, tuple.type);
}
public static explicit operator LogMessage(string message)
{
return new LogMessage(message, LogLevel.INFO);
}
public static explicit operator LogMessage((string message, LogLevel type, string sender) tuple)
{
return new LogMessage(tuple.message, tuple.type, tuple.sender);
}
public static explicit operator LogMessage((string message, LogLevel type) tuple)
{
return new LogMessage(tuple.message, tuple.type);
}
public static explicit operator LogMessage((string message, LogLevel type, string sender) tuple)
{
return new LogMessage(tuple.message, tuple.type, tuple.sender);
}
}

View File

@@ -1,5 +1,4 @@
using System.Linq;
using Discord;
using Discord.WebSocket;
@@ -62,4 +61,4 @@ public static class DiscordPermissions
{
return isAdmin((SocketGuildUser)user);
}
}
}