Moved to json file format

This commit is contained in:
2022-06-04 18:55:29 +03:00
parent 8fcd33e734
commit 0b6b57cc84
39 changed files with 501 additions and 1712 deletions

87
PluginManager/Config.cs Normal file
View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager
{
public static class Config
{
private static readonly Dictionary<string, string> ApplicationVariables = new();
private static readonly List<string> ConstantTokens = new() { "token" };
public static void AppendToDictionary(Dictionary<string, string> dictionary)
{
foreach (var kvp in dictionary) ApplicationVariables.TryAdd(kvp.Key, kvp.Value);
}
public static bool AddValueToVariables(string key, string value, bool constant)
{
bool req = AddValueToVariables(key, value);
if (constant) ConstantTokens.Add(key);
return req;
}
public static bool AddValueToVariables(string key, string value)
{
if (ApplicationVariables.ContainsKey(key))
{
return false;
}
ApplicationVariables.Add(key, value);
return true;
}
public static string? GetValue(string key)
{
if (!ApplicationVariables.ContainsKey(key))
{
if (key != "token") Console.WriteLine("The key is not present in the dictionary");
return null;
}
return ApplicationVariables[key];
}
public static bool SetValue(string key, string value)
{
if (!ApplicationVariables.ContainsKey(key)) return false;
if (ConstantTokens.Contains(key)) return false;
ApplicationVariables[key] = value;
return true;
}
public static bool RemoveKey(string key)
{
if (ConstantTokens.Contains(key)) return false;
ApplicationVariables.Remove(key);
return true;
}
public static async void SaveDictionary()
{
string path = Functions.dataFolder + "var.dat";
await Functions.SaveToJsonFile(path, ApplicationVariables);
}
public static async void LoadDictionary()
{
string path = Functions.dataFolder + "var.dat";
var d = await Functions.ConvertFromJson<Dictionary<string, string>>(path);
ApplicationVariables.Clear();
AppendToDictionary(d);
}
public static string GetKey(string value) => ApplicationVariables.Keys.FirstOrDefault(x => ApplicationVariables[x] == value);
public static bool ContainsValue(string value) => ApplicationVariables.ContainsValue(value);
public static bool ContainsKey(string key) => ApplicationVariables.ContainsKey(key);
}
}

View File

@@ -1,16 +1,12 @@
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using PluginManager.LanguageSystem;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
@@ -18,13 +14,10 @@ namespace PluginManager.Items
{
public class ConsoleCommandsHandler
{
private static PluginsManager manager = new PluginsManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
private static LanguageManager languageManager = new LanguageManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Languages");
private static PluginsManager manager = new("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
public static List<Tuple<string, string, Action<string[]>>>? commandList = new List<Tuple<string, string, Action<string[]>>>();
private DiscordSocketClient client;
private DiscordSocketClient client;
public ConsoleCommandsHandler(DiscordSocketClient client)
{
@@ -73,14 +66,9 @@ namespace PluginManager.Items
if (name == null || name.Length < 2)
name = typeName;
if (success)
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[CMD] Successfully loaded command : " + name);
else Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_SUCCESS"], name));
Console.WriteLine("[CMD] Successfully loaded command : " + name);
else
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception.Message);
else
Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_FAIL"], name, exception.Message));
Console.ForegroundColor = ConsoleColor.Red;
};
loader.onEVELoad += (name, typeName, success, exception) =>
@@ -89,15 +77,9 @@ namespace PluginManager.Items
name = typeName;
Console.ForegroundColor = ConsoleColor.Green;
if (success)
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else
Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["EVENT_LOAD_SUCCESS"], name));
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception.Message);
else
Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["EVENT_LOAD_FAIL"], name, exception.Message));
Console.ForegroundColor = ConsoleColor.Red;
};
loader.LoadPlugins();
@@ -205,75 +187,47 @@ namespace PluginManager.Items
});
AddCommand("setlang", "set language", (args) =>
{
if (args.Length == 1)
AddCommand("value", "read value from VariableStack", (args) =>
{
Console.WriteLine("Please specify language");
return;
if (args.Length != 2) return;
if (!Config.ContainsKey(args[1])) return;
string data = Config.GetValue(args[1]);
Console.WriteLine($"{args[1]} => {data}");
}
Language.SetLanguage(args[0]);
});
);
AddCommand("listlang", "List all available languages", async () =>
{
await languageManager.ListAllLanguages();
});
AddCommand("dwlang", "Download language", async (args) =>
{
if (args.Length == 1)
AddCommand("addv", "add variable to the system variables", async (args) =>
{
Console.WriteLine("Please specify language");
return;
if (args.Length < 3) return;
string in1 = args[1];
if (!Config.ContainsKey(in1))
Config.AddValueToVariables(in1, Functions.MergeStrings(args, 2));
else
Config.SetValue(in1, Functions.MergeStrings(args, 2));
Console.WriteLine($"Updated config file with the following command: {in1} => {Config.GetValue(in1)}");
Config.SaveDictionary();
}
string Lname = args.MergeStrings(1);
string[] link = await languageManager!.GetDownloadLink(Lname);
try
);
AddCommand("remv", "remove variable from system variables", (args) =>
{
if (link[0] is null || link is null)
{
if (Lname == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
return;
}
Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
return;
}
if (link[1].Contains("CrossPlatform") || link[1].Contains("cp"))
{
string path2 = Functions.langFolder + Lname + ".lng";
await ServerCom.DownloadFileAsync(link[0], path2);
Console.WriteLine("\n");
}
else Console_Utilities.WriteColorText("The language you are trying to download (&b" + Lname + "&c) is not compatible with the version of this bot. User &glistlang &ccommand in order to see all available languages for your current version !\n" + link[1]);
return;
if (args.Length < 2) return;
Config.RemoveKey(args[1]);
Config.SaveDictionary();
}
catch
);
AddCommand("sd", "Shuts down the discord bot", async () =>
{
if (Lname == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
return;
}
Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
return;
await client.StopAsync();
await client.DisposeAsync();
Config.SaveDictionary();
Environment.Exit(0);
}
});
AddCommand("token", "Display the token used by the bot", () =>
{
if (System.IO.File.Exists("./Data/Resources/DiscordBotCore.data"))
Console.WriteLine("Token: " + Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '='));
else Console.WriteLine("File could not be found. Please register token");
});
);
}
public static void AddCommand(string command, string description, Action<string[]> action)
@@ -286,8 +240,6 @@ namespace PluginManager.Items
public static void AddCommand(string command, string description, Action action)
{
AddCommand(command, description, (args) => action());
/* Console.WriteLine("Added command: " + command);*/
}
public static void RemoveCommand(string command)

View File

@@ -1,161 +0,0 @@
using PluginManager.Others;
using System.Collections.Generic;
using System;
using System.IO;
using System.Threading.Tasks;
namespace PluginManager.LanguageSystem
{
public class Language
{
/// <summary>
/// The active language
/// </summary>
public static Language? ActiveLanguage = null;
private static readonly string LanguageFileExtension = ".lng";
/// <summary>
/// The name of the language
/// </summary>
public string LanguageName { get; }
/// <summary>
/// The file where the language is imported from
/// </summary>
public string fileName { get; }
/// <summary>
/// The dictionary of the language
/// </summary>
public Dictionary<string, string> LanguageWords { get; }
/// <summary>
/// The Language constructor
/// </summary>
/// <param name="fileName">The file to import the language from</param>
/// <param name="words">The dictionary of the language</param>
/// <param name="LanguageName">The name of the language</param>
private Language(string fileName, Dictionary<string, string> words, string LanguageName)
{
this.fileName = fileName;
this.LanguageName = LanguageName;
LanguageWords = words;
}
/// <summary>
/// Load language from file
/// </summary>
/// <param name="LanguageFileLocation">The file path</param>
/// <returns></returns>
public static Language? CreateLanguageFromFile(string LanguageFileLocation)
{
if (!LanguageFileLocation.EndsWith(LanguageFileExtension))
{
Console.WriteLine("Failed to load language from file: " + LanguageFileLocation +
"\nFile extension is not " + LanguageFileExtension);
return null;
}
string[] lines = File.ReadAllLines(LanguageFileLocation);
var languageName = "Unknown";
var words = new Dictionary<string, string>();
foreach (string line in lines)
{
if (line.StartsWith("#") || line.Length < 4)
continue;
string[] sLine = line.Split('=');
if (sLine[0] == "LANGUAGE_NAME")
{
languageName = sLine[1];
continue;
}
words.Add(sLine[0], sLine[1]);
}
Functions.WriteLogFile("Successfully loaded language: " + languageName + " from file : " +
LanguageFileLocation.Replace('\\', '/'));
return new Language(LanguageFileLocation, words, languageName);
}
/// <summary>
/// Format text by inserting parameters
/// </summary>
/// <param name="text">The raw text</param>
/// <param name="args">The arguments</param>
/// <returns></returns>
public string FormatText(string text, params string[] args)
{
if (ActiveLanguage == null) return text;
int l = args.Length;
for (var i = 0; i < l; i++) text = text.Replace($"{i}", args[i]);
return text;
}
public static bool LoadLanguage()
{
string folder = Functions.langFolder;
string langSettings = "./Data/Resources/Language.txt";
if (!File.Exists(langSettings))
File.WriteAllText(langSettings, "Language=English");
//Load language from the specified file ...
Language.ActiveLanguage = null;
string langname = Functions.readCodeFromFile(langSettings, "Language", '=');
if (langname == "English")
{
Language.ActiveLanguage = null;
return true;
}
foreach (var file in Directory.GetFiles(folder))
{
if (Functions.readCodeFromFile(file, "LANGUAGE_NAME", '=') == langname)
{
Language.ActiveLanguage = Language.CreateLanguageFromFile(file);
return true;
}
}
if (Language.ActiveLanguage == null)
{
File.WriteAllText(langSettings, "Language=English");
Console_Utilities.WriteColorText($"Failed to find language &r{langname} &c! Check available languages using command: &glistlang");
return false;
}
return false;
}
public static void SetLanguage(string LanguageName)
{
string langSettings = Functions.dataFolder + "Language.txt";
File.WriteAllText(langSettings, "Language=" + LanguageName);
try
{
bool success = LoadLanguage();
if (success)
{
Console_Utilities.WriteColorText($"Language has been setted to: &g{LanguageName}");
return;
}
}
catch (Exception ex)
{
Console_Utilities.WriteColorText($"Could not find language &r{LanguageName}.");
Functions.WriteErrFile(ex.ToString());
File.WriteAllText(langSettings, "Language=English");
LoadLanguage();
}
}
}
}

View File

@@ -41,7 +41,7 @@ namespace PluginManager.Loaders
internal List<T>? Load()
{
List<T> list = new List<T>();
List<T> list = new List<T>();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
@@ -54,7 +54,14 @@ namespace PluginManager.Loaders
Assembly.LoadFrom(file);
if (FileLoaded != null)
{
LoaderArgs args = new LoaderArgs() { Exception = null, TypeName = nameof(T), IsLoaded = false, PluginName = file, Plugin = null };
LoaderArgs args = new LoaderArgs()
{
Exception = null,
TypeName = nameof(T),
IsLoaded = false,
PluginName = file,
Plugin = null
};
FileLoaded.Invoke(args);
}
}
@@ -63,9 +70,9 @@ namespace PluginManager.Loaders
{
Type interfaceType = typeof(T);
Type[] types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
list.Clear();
@@ -77,15 +84,32 @@ namespace PluginManager.Loaders
list.Add(plugin);
if (PluginLoaded != null) { PluginLoaded.Invoke(new() { Exception = null, IsLoaded = true, PluginName = type.FullName, TypeName = nameof(T), Plugin = plugin }); }
if (PluginLoaded != null)
{
PluginLoaded.Invoke(new()
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = nameof(T),
Plugin = plugin
}
);
}
}
catch (Exception ex)
{
if (PluginLoaded != null) { PluginLoaded.Invoke(new() { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) }); }
if (PluginLoaded != null)
{
PluginLoaded.Invoke(new() { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) });
}
}
}
}
catch (Exception ex) { Functions.WriteErrFile(ex.ToString()); }
catch (Exception ex)
{
Functions.WriteErrFile(ex.ToString());
}
return list;

View File

@@ -57,13 +57,7 @@ namespace PluginManager.Loaders
Events = new List<DBEvent>();
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
if (LanguageSystem.Language.ActiveLanguage != null)
Console_Utilities.WriteColorText(
LanguageSystem.Language.ActiveLanguage.FormatText(
LanguageSystem.Language.ActiveLanguage.LanguageWords["PLUGIN_LOADING_START"]
)
);
Console.WriteLine("Loading plugins");
Loader<DBCommand> commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
Loader<DBEvent> eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);

View File

@@ -7,6 +7,8 @@ using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Items;
using System.Threading;
using System.Text.Json;
using System.Text;
namespace PluginManager.Others
{
@@ -40,22 +42,6 @@ namespace PluginManager.Others
/// </summary>
public static readonly string pakFolder = @"./Data/Resources/PAKS/";
/// <summary>
/// The mark that the line is a comment
/// </summary>
private static readonly char commentMark = '#';
/// <summary>
/// Read data from file
/// </summary>
/// <param name="fileName">File name</param>
/// <param name="Code">Setting name</param>
/// <param name="separator">Separator between setting key code and its value</param>
/// <returns>The value of the specified setting key code in the specified file (<see cref="string"/>)</returns>
public static string? readCodeFromFile(string fileName, string Code, char separator)
=> File.ReadAllLines(fileName)
.Where(p => p.StartsWith(Code) && !p.StartsWith(commentMark.ToString()))
.First().Split(separator)[1] ?? null;
/// <summary>
/// Read data from a file that is inside an archive (ZIP format)
@@ -67,17 +53,16 @@ namespace PluginManager.Others
{
archFile = pakFolder + archFile;
Directory.CreateDirectory(pakFolder);
if (!File.Exists(archFile))
throw new FileNotFoundException("Failed to load file !");
if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !");
string? textValue = null;
var fs = new FileStream(archFile, FileMode.Open);
var zip = new ZipArchive(fs, ZipArchiveMode.Read);
var fs = new FileStream(archFile, FileMode.Open);
var zip = new ZipArchive(fs, ZipArchiveMode.Read);
foreach (var entry in zip.Entries)
{
if (entry.Name == FileName || entry.FullName == FileName)
{
Stream s = entry.Open();
Stream s = entry.Open();
StreamReader reader = new StreamReader(s);
textValue = await reader.ReadToEndAsync();
reader.Close();
@@ -86,6 +71,7 @@ namespace PluginManager.Others
break;
}
}
return textValue;
}
@@ -96,8 +82,7 @@ namespace PluginManager.Others
public static void WriteLogFile(string LogMessage)
{
string logsPath = logFolder + "Log.txt";
if (!Directory.Exists(logFolder))
Directory.CreateDirectory(logFolder);
if (!Directory.Exists(logFolder)) Directory.CreateDirectory(logFolder);
File.AppendAllText(logsPath, LogMessage + " \n");
}
@@ -108,8 +93,7 @@ namespace PluginManager.Others
public static void WriteErrFile(string ErrMessage)
{
string errPath = errFolder + "Error.txt";
if (!Directory.Exists(errFolder))
Directory.CreateDirectory(errFolder);
if (!Directory.Exists(errFolder)) Directory.CreateDirectory(errFolder);
File.AppendAllText(errPath, ErrMessage + " \n");
}
@@ -132,10 +116,10 @@ namespace PluginManager.Others
File.AppendAllText(file, Code + separator + newValue + "\n");
ok = true;
}
else File.AppendAllText(file, line + "\n");
else
File.AppendAllText(file, line + "\n");
if (!ok)
File.AppendAllText(file, Code + separator + newValue + "\n");
if (!ok) File.AppendAllText(file, Code + separator + newValue + "\n");
}
/// <summary>
@@ -146,8 +130,8 @@ namespace PluginManager.Others
/// <returns>A string built based on the array</returns>
public static string MergeStrings(this string[] s, int indexToStart)
{
string r = "";
int len = s.Length;
string r = "";
int len = s.Length;
if (len <= indexToStart) return "";
for (int i = indexToStart; i < len - 1; ++i)
{
@@ -192,8 +176,7 @@ namespace PluginManager.Others
int len = args.Length;
if (len < 2) return;
for (int i = 0; i < len - 2; i++)
path += args[i] + "/";
for (int i = 0; i < len - 2; i++) path += args[i] + "/";
path += args[len - 2] + ".txt";
@@ -215,20 +198,15 @@ namespace PluginManager.Others
/// <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)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize));
if (!stream.CanRead)
throw new InvalidOperationException("The stream is not readable.");
if (!destination.CanWrite)
throw new ArgumentException("Destination stream is not writable", nameof(destination));
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (destination == null) throw new ArgumentNullException(nameof(destination));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize));
if (!stream.CanRead) throw new InvalidOperationException("The stream is not readable.");
if (!destination.CanWrite) throw new ArgumentException("Destination stream is not writable", nameof(destination));
byte[] buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
byte[] buffer = new byte[bufferSize];
long totalBytesRead = 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);
@@ -246,15 +224,12 @@ namespace PluginManager.Others
/// <returns></returns>
public static async Task ExtractArchive(string zip, string folder, IProgress<float> progress)
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
using (ZipArchive archive = ZipFile.OpenRead(zip))
{
int totalZIPFiles = archive.Entries.Count();
int totalZIPFiles = archive.Entries.Count();
int currentZIPFile = 0;
foreach (ZipArchiveEntry entry in archive.Entries)
{
@@ -262,8 +237,13 @@ namespace PluginManager.Others
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
else
try { entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); }
catch { }
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
}
catch
{
}
currentZIPFile++;
await Task.Delay(10);
@@ -281,5 +261,40 @@ namespace PluginManager.Others
return (bytes / 1024.0 / 1024.0 / 1024.0, "GB");
}
public static async Task SaveToJsonFile<T>(string file, T Data)
{
string jsonText = JsonSerializer.Serialize(Data, typeof(T));
await File.WriteAllTextAsync(file, jsonText);
}
public static async Task<T> ConvertFromJson<T>(string input)
{
Stream text;
if (File.Exists(input))
text = File.Open(input, FileMode.OpenOrCreate);
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text);
text.Close();
return obj;
}
public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element)
{
Stream text;
if (File.Exists(input))
text = File.OpenRead(input);
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
var jsonObject = JsonDocument.Parse(text);
var data = jsonObject.RootElement.TryGetProperty(codeName, out element);
return data;
}
}
}