Reformatting code

This commit is contained in:
2023-11-21 22:04:38 +02:00
parent 79ecff971b
commit 944d59d9a3
37 changed files with 509 additions and 486 deletions

View File

@@ -78,7 +78,7 @@ public class Boot
CommonTasks();
await client.LoginAsync(TokenType.Bot, botToken);
await client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix);
@@ -105,7 +105,7 @@ public class Boot
if (arg.Message.Contains("401"))
{
Config.AppSettings.Remove("token");
Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source:typeof(Boot), type: LogType.CRITICAL);
Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source: typeof(Boot), type: LogType.CRITICAL);
await Config.AppSettings.SaveToFile();
await Task.Delay(4000);
Environment.Exit(0);

View File

@@ -106,9 +106,11 @@ internal class CommandHandler
(
plug.Aliases is not null &&
plug.Aliases.Contains(message.CleanContent
.Substring(mentionPrefix.Length + 1)
.Split(' ')[0])
));
.Substring(mentionPrefix.Length + 1)
.Split(' ')[0]
)
)
);
cleanMessage = message.Content.Substring(mentionPrefix.Length + 1);
}
@@ -120,11 +122,13 @@ internal class CommandHandler
message.Content.Split(' ')[0].Substring(botPrefix.Length) ||
(p.Aliases is not null &&
p.Aliases.Contains(
message.Content.Split(' ')[0]
.Substring(botPrefix.Length))));
message.Content.Split(' ')[0]
.Substring(botPrefix.Length)
))
);
cleanMessage = message.Content.Substring(botPrefix.Length);
}
if (plugin is null)
return;
@@ -138,13 +142,13 @@ internal class CommandHandler
argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean);
Config.Logger.Log(
message: $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"",
source: typeof(CommandHandler),
type: LogType.INFO
);
if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(cmd);
else plugin.ExecuteServer(cmd);

View File

@@ -20,18 +20,19 @@ public class Config
public static async Task Initialize()
{
if (_isLoaded) return;
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
Directory.CreateDirectory("./Data/Logs/Logs");
Directory.CreateDirectory("./Data/Logs/Errors");
Directory.CreateDirectory("./Data/Archives");
Directory.CreateDirectory("./Data/Logs");
AppSettings = new SettingsDictionary<string, string>("./Data/Resources/config.json");
AppSettings["LogFolder"] = "./Data/Logs/Logs";
AppSettings["LogFolder"] = "./Data/Logs";
Logger = new Logger(false, true);
Logger = new Logger(false, true,
AppSettings["LogFolder"] + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log"
);
ArchiveManager.Initialize();
@@ -39,5 +40,5 @@ public class Config
Logger.Log(message: "Config initialized", source: typeof(Config));
}
}

View File

@@ -163,7 +163,8 @@ public class SqlDatabase
throw new Exception($"Table {tableName} does not exist");
await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'"
);
}
/// <summary>
@@ -238,7 +239,7 @@ public class SqlDatabase
{
var command = _connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
@@ -262,7 +263,7 @@ public class SqlDatabase
{
var command = _connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader();
var reader = command.ExecuteReader();
var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
@@ -343,7 +344,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var answer = await command.ExecuteNonQueryAsync();
var answer = await command.ExecuteNonQueryAsync();
return answer;
}
@@ -357,7 +358,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open();
var command = new SQLiteCommand(query, _connection);
var r = command.ExecuteNonQuery();
var r = command.ExecuteNonQuery();
return r;
}
@@ -372,7 +373,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -394,7 +395,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open();
var command = new SQLiteCommand(query, _connection);
var reader = command.ExecuteReader();
var reader = command.ExecuteReader();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -416,7 +417,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -439,7 +440,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open();
var command = new SQLiteCommand(query, _connection);
var reader = command.ExecuteReader();
var reader = command.ExecuteReader();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -462,7 +463,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
if (!reader.HasRows)
return null;
@@ -479,7 +480,7 @@ public class SqlDatabase
return rows;
}
/// <summary>
/// Create a parameter for a query
/// </summary>
@@ -490,7 +491,7 @@ public class SqlDatabase
{
var parameter = new SQLiteParameter(name);
parameter.Value = value;
if (value is string)
parameter.DbType = DbType.String;
else if (value is int)
@@ -531,13 +532,13 @@ public class SqlDatabase
parameter.DbType = DbType.StringFixedLength;
else if (value is char[])
parameter.DbType = DbType.StringFixedLength;
else
else
return null;
return parameter;
}
/// <summary>
/// Create a parameter for a query. The function automatically detects the type of the value.
/// </summary>
@@ -545,7 +546,7 @@ public class SqlDatabase
/// <returns>The SQLiteParameter that has the name, value and DBType set according to your inputs</returns>
private SQLiteParameter? CreateParameter(KeyValuePair<string, object> parameterValues) =>
CreateParameter(parameterValues.Key, parameterValues.Value);
/// <summary>
/// Execute a query with parameters
/// </summary>
@@ -556,7 +557,7 @@ public class SqlDatabase
{
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters)
{
@@ -564,10 +565,10 @@ public class SqlDatabase
if (p is not null)
command.Parameters.Add(p);
}
return await command.ExecuteNonQueryAsync();
}
/// <summary>
/// Execute a query with parameters that returns a specific type of object. The function will return the first row of the result transformed into the specified type.
/// </summary>
@@ -576,11 +577,11 @@ public class SqlDatabase
/// <param name="parameters">The parameters of the query</param>
/// <typeparam name="T">The return object type</typeparam>
/// <returns>An object of type T that represents the output of the convertor function based on the array of objects that the first row of the result has</returns>
public async Task<T?> ReadObjectOfTypeAsync<T> (string query, Func<object[], T> convertor, params KeyValuePair<string, object>[] parameters)
public async Task<T?> ReadObjectOfTypeAsync<T>(string query, Func<object[], T> convertor, params KeyValuePair<string, object>[] parameters)
{
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters)
{
@@ -588,7 +589,7 @@ public class SqlDatabase
if (p is not null)
command.Parameters.Add(p);
}
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -599,8 +600,8 @@ public class SqlDatabase
return default;
}
/// <summary>
/// Execute a query with parameters that returns a specific type of object. The function will return a list of objects of the specified type.
/// </summary>
@@ -614,7 +615,7 @@ public class SqlDatabase
{
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters)
{
@@ -622,12 +623,12 @@ public class SqlDatabase
if (p is not null)
command.Parameters.Add(p);
}
var reader = await command.ExecuteReaderAsync();
//
if (!reader.HasRows)
return null;
List<T> rows = new();
while (await reader.ReadAsync())
{
@@ -638,4 +639,4 @@ public class SqlDatabase
return rows;
}
}
}

View File

@@ -6,7 +6,7 @@ namespace PluginManager.Interfaces;
public interface DBSlashCommand
{
string Name { get; }
string Name { get; }
string Description { get; }
bool canUseDM { get; }

View File

@@ -5,11 +5,10 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILog
{
string Message { get; set; }
string OutputFile { get; set; }
string Message { get; set; }
Type? Source { get; set; }
LogType Type { get; set; }
LogType Type { get; set; }
DateTime ThrowTime { get; set; }
}

View File

@@ -7,11 +7,13 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILogger
{
bool IsEnabled { get; init; }
bool OutputToFile { get; init; }
bool IsEnabled { get; init; }
bool OutputToFile { get; init; }
string OutputFile { get; init; }
event EventHandler<Log> OnLog;
void Log(
string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO,
string message = "", Type? source = default, LogType type = LogType.INFO,
DateTime throwTime = default);
}

View File

@@ -8,13 +8,13 @@ using PluginManager.Others;
namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs
internal class LoaderArgs: EventArgs
{
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; }
internal object? Plugin { get; init; }
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; }
internal object? Plugin { get; init; }
}
internal class Loader
@@ -26,7 +26,7 @@ internal class Loader
}
private string Path { get; }
private string Path { get; }
private string Extension { get; }
internal event FileLoadedEventHandler? FileLoaded;
@@ -101,28 +101,29 @@ internal class Loader
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" :
typeof(T) == typeof(DBEvent) ? "DBEvent" :
typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" :
null,
Plugin = plugin
}
);
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" :
typeof(T) == typeof(DBEvent) ? "DBEvent" :
typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" :
null,
Plugin = plugin
}
);
}
catch (Exception ex)
{
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
});
{
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
}
);
}
return list;

View File

@@ -131,7 +131,8 @@ public class PluginLoader
builder.Options = slash.Options;
onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded,
args.Exception);
args.Exception
);
await _client.CreateGlobalApplicationCommandAsync(builder.Build());
}
@@ -161,7 +162,7 @@ public class PluginLoader
else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type))
{
var instance = (DBSlashCommand)Activator.CreateInstance(type);
var builder = new SlashCommandBuilder();
var builder = new SlashCommandBuilder();
builder.WithName(instance.Name);
builder.WithDescription(instance.Description);
builder.WithDMPermission(instance.canUseDM);
@@ -177,6 +178,6 @@ public class PluginLoader
//Console.WriteLine(ex.Message);
Config.Logger.Log(ex.Message, source: typeof(PluginLoader), type: LogType.ERROR);
}
}
}

View File

@@ -19,10 +19,10 @@ internal static class OnlineFunctions
/// <param name="cancellation">The cancellation token</param>
/// <returns></returns>
internal static async Task DownloadFileAsync(
this HttpClient client, string url, Stream destination,
IProgress<float>? progress = null,
IProgress<long>? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default)
this HttpClient client, string url, Stream destination,
IProgress<float>? progress = null,
IProgress<long>? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default)
{
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation))
{
@@ -35,7 +35,7 @@ internal static class OnlineFunctions
if (progress == null || !contentLength.HasValue)
{
await download.CopyToAsync(destination, cancellation);
if(!contentLength.HasValue)
if (!contentLength.HasValue)
progress?.Report(100f);
return;
}

View File

@@ -10,7 +10,7 @@ namespace PluginManager.Online;
public class PluginsManager
{
#if DEBUG
/// <summary>
/// The Plugin Manager constructor
@@ -22,16 +22,16 @@ public class PluginsManager
PluginsLink = plink;
VersionsLink = vlink;
}
#endif
/// <summary>
/// The Plugin Manager constructor. It uses the default links and the default branch.
/// </summary>
/// <param name="branch">The main branch from where the plugin manager gets its info</param>
public PluginsManager(string? branch = "releases")
{
PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList";
PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList";
VersionsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/Versions";
}
@@ -95,7 +95,7 @@ public class PluginsManager
}
catch (Exception exception)
{
Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR );
Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR);
}
return null;
@@ -135,16 +135,18 @@ public class PluginsManager
for (var i = 0; i < len; i++)
{
var contents = lines[i].Split(',');
if(Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows"))
{if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows"))
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };
if (contents.Length == 5)
return new[] { contents[2], contents[3], string.Empty };
throw new Exception("Failed to download plugin. Invalid Argument Length");
if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };
if (contents.Length == 5)
return new[] { contents[2], contents[3], string.Empty };
throw new Exception("Failed to download plugin. Invalid Argument Length");
}
}
}else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux"))
else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux"))
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };

View File

@@ -30,7 +30,7 @@ public static class ServerCom
/// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param>
/// <returns></returns>
public static async Task DownloadFileAsync(
string URL, string location, IProgress<float> progress,
string URL, string location, IProgress<float> progress,
IProgress<long>? downloadedBytes)
{
using (var client = new HttpClient())
@@ -48,15 +48,15 @@ public static class ServerCom
{
await DownloadFileAsync(URl, location, progress, null);
}
public static Task CreateDownloadTask(string URl, string location)
{
return DownloadFileAsync(URl, location, null, null);
}
public static Task CreateDownloadTask(string URl, string location, IProgress<float> progress)
{
return DownloadFileAsync(URl, location, progress, null);
}
}

View File

@@ -26,7 +26,7 @@ public class InternalActionManager
Actions.TryAdd(action.ActionName, action);
}
}
public async Task Refresh()
{
Actions.Clear();
@@ -59,7 +59,7 @@ public class InternalActionManager
}
catch (Exception e)
{
Config.Logger.Log(e.Message , type: LogType.ERROR, source: typeof(InternalActionManager));
Config.Logger.Log(e.Message, type: LogType.ERROR, source: typeof(InternalActionManager));
return e.Message;
}
}

View File

@@ -37,24 +37,24 @@ public static class ArchiveManager
if (!File.Exists(archName))
throw new Exception("Failed to load file !");
byte[]? data = null;
using (var zip = ZipFile.OpenRead(archName))
{
var entry = zip.Entries.FirstOrDefault(entry => entry.FullName == fileName || entry.Name == fileName);
if (entry is null) throw new Exception("File not found in archive");
var MemoryStream = new MemoryStream();
var stream = entry.Open();
await stream.CopyToAsync(MemoryStream);
data = MemoryStream.ToArray();
stream.Close();
MemoryStream.Close();
}
return data;
}
@@ -117,7 +117,7 @@ public static class ArchiveManager
{
if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES)
{
var totalZIPFiles = archive.Entries.Count();
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
@@ -173,4 +173,4 @@ public static class ArchiveManager
}
}
}
}
}

View File

@@ -29,19 +29,19 @@ public class DBCommandExecutingArguments
{
this.cleanContent = message.Content.Substring(Config.DiscordBot.botPrefix.Length);
}
var split = this.cleanContent.Split(' ');
string[]? argsClean = null;
if (split.Length > 1)
argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
this.commandUsed = split[0];
this.arguments = argsClean;
this.arguments = argsClean;
}
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
}

View File

@@ -40,8 +40,8 @@ public enum InternalActionRunType
ON_CALL
}
internal enum ExceptionExitCode : int
internal enum ExceptionExitCode: int
{
CONFIG_FAILED_TO_LOAD = 1,
CONFIG_KEY_NOT_FOUND = 2,
CONFIG_KEY_NOT_FOUND = 2,
}

View File

@@ -54,8 +54,8 @@ public static class Functions
/// <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,
this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null,
CancellationToken cancellationToken = default)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
@@ -76,7 +76,7 @@ public static class Functions
progress?.Report(totalBytesRead);
}
}
public static T SelectRandomValueOf<T>()
{

View File

@@ -38,10 +38,10 @@ public class JsonManager
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text);
await text.FlushAsync();
text.Close();
return (obj ?? default)!;
}
}
}

View File

@@ -4,60 +4,46 @@ using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger;
public class Log : ILog
public class Log: ILog
{
public string Message { get; set; }
public string OutputFile { get; set; }
public Type? Source { get; set; }
public LogType Type { get; set; }
public DateTime ThrowTime { get; set; }
public Log(string message, string outputFile, Type? source, LogType type, DateTime throwTime)
public string Message { get; set; }
public Type? Source { get; set; }
public LogType Type { get; set; }
public DateTime ThrowTime { get; set; }
public Log(string message, Type? source, LogType type, DateTime throwTime)
{
Message = message;
OutputFile = outputFile;
Source = source;
Type = type;
ThrowTime = throwTime;
Message = message;
Source = source;
Type = type;
ThrowTime = throwTime;
}
public Log(string message, string outputFile, Type? source, LogType type)
public Log(string message, Type? source, LogType type)
{
Message = message;
OutputFile = outputFile;
Source = source;
Type = type;
ThrowTime = DateTime.Now;
Message = message;
Source = source;
Type = type;
ThrowTime = DateTime.Now;
}
public Log(string message, string outputFile, Type? source)
public Log(string message, Type? source)
{
Message = message;
OutputFile = outputFile;
Source = source;
Type = LogType.INFO;
ThrowTime = DateTime.Now;
Message = message;
Source = source;
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public Log(string message, string outputFile)
{
Message = message;
OutputFile = outputFile;
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public Log(string message)
{
Message = message;
OutputFile = "";
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
Message = message;
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public static implicit operator Log(string message) => new (message);
public static implicit operator Log(string message) => new(message);
public static implicit operator string(Log log) => $"[{log.ThrowTime}] {log.Message}";
@@ -65,7 +51,7 @@ public class Log : ILog
{
return $"[{ThrowTime}] [{Source}] [{Type}] {Message}";
}
public string AsShortString()
{
return this;

View File

@@ -6,64 +6,72 @@ using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger;
public sealed class Logger : ILogger
public sealed class Logger: ILogger
{
public bool IsEnabled { get; init; }
public bool OutputToFile { get; init; }
public bool IsEnabled { get; init; }
public bool OutputToFile { get; init; }
public string? OutputFile { get; init; }
private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, LogType lowestLogLevel = LogType.INFO)
private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, string outputFile, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = outputToFile;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = outputFile;
}
public Logger(bool useShortVersion, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = false;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = null;
}
public event EventHandler<Log>? OnLog;
private async Task Log(Log logMessage)
{
if (!IsEnabled) return;
OnLog?.Invoke(this, logMessage);
if (logMessage.Type < LowestLogLevel) return;
if (OutputToFile)
await File.AppendAllTextAsync(
logMessage.OutputFile,
(UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n");
OutputFile!,
(UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n"
);
}
public async void Log(string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default)
public async void Log(string message = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default)
{
if (!IsEnabled) return;
if (type < LowestLogLevel) return;
if (string.IsNullOrEmpty(message)) return;
if (string.IsNullOrEmpty(outputFile)) outputFile = Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
if(throwTime == default) throwTime = DateTime.Now;
if (throwTime == default) throwTime = DateTime.Now;
if (source == default) source = typeof(Log);
await Log(new Log(message, outputFile, source, type, throwTime));
await Log(new Log(message, source, type, throwTime));
}
public async void Log(Exception exception, LogType logType = LogType.ERROR, Type? source = null)
{
if (!IsEnabled) return;
if (logType < LowestLogLevel) return;
await Log(new Log(exception.Message,
Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log",
source, logType, DateTime.Now));
await Log(new Log(exception.Message, source, logType, DateTime.Now));
}
}

View File

@@ -5,11 +5,11 @@ using System.Threading.Tasks;
namespace PluginManager.Others;
public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
public class SettingsDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
public string? _file { get; }
private IDictionary<TKey, TValue>? _dictionary;
public SettingsDictionary(string? file)
{
_file = file;
@@ -19,7 +19,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
SaveToFile();
}
}
public async Task SaveToFile()
{
if (!string.IsNullOrEmpty(_file))
@@ -36,8 +36,8 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
string FileContent = File.ReadAllText(_file);
if (string.IsNullOrEmpty(FileContent))
File.WriteAllText(_file, "{}");
if(!FileContent.Contains("{") || !FileContent.Contains("}"))
if (!FileContent.Contains("{") || !FileContent.Contains("}"))
File.WriteAllText(_file, "{}");
}
else
@@ -61,7 +61,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _dictionary!).GetEnumerator();
return ((IEnumerable)_dictionary!).GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item)
@@ -89,7 +89,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
return this._dictionary!.Remove(item);
}
public int Count => _dictionary!.Count;
public int Count => _dictionary!.Count;
public bool IsReadOnly => _dictionary!.IsReadOnly;
public void Add(TKey key, TValue value)
{
@@ -116,9 +116,9 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
get
{
if (this._dictionary!.ContainsKey(key))
if(this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
if (this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
return this._dictionary[key];
return default!;
}
set => this._dictionary![key] = value;
@@ -126,4 +126,4 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
public ICollection<TKey> Keys => _dictionary!.Keys;
public ICollection<TValue> Values => _dictionary!.Values;
}
}

View File

@@ -9,10 +9,10 @@
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<None Remove="BlankWindow1.xaml" />
<None Remove="BlankWindow1.xaml"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.11.0" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118" />
<PackageReference Include="Discord.Net" Version="3.11.0"/>
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118"/>
</ItemGroup>
</Project>