2 Commits

Author SHA1 Message Date
68a83b052a Updater added 2022-08-28 12:59:41 +03:00
d689eee7fa 2022-08-26 10:42:15 +03:00
21 changed files with 800 additions and 209 deletions

Binary file not shown.

View File

@@ -1,11 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Others;
@@ -34,6 +31,16 @@ internal class Help : DBCommand
/// </summary>
public string Usage => "help <command>";
/// <summary>
/// Check if the command can be used <inheritdoca DM <see cref="IChannel" />/>
/// </summary>
public bool canUseDM => true;
/// <summary>
/// Check if the command can be used in a server
/// </summary>
public bool canUseServer => true;
/// <summary>
/// Check if the command require administrator to be executed
/// </summary>
@@ -43,9 +50,12 @@ internal class Help : DBCommand
/// The main body of the command
/// </summary>
/// <param name="context">The command context</param>
public void ExecuteServer(SocketCommandContext context)
/// <param name="message">The command message</param>
/// <param name="client">The discord bot client</param>
/// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param>
public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
var args = Functions.GetArguments(context.Message);
var args = Functions.GetArguments(message);
if (args.Count != 0)
{
foreach (var item in args)
@@ -62,29 +72,33 @@ internal class Help : DBCommand
var embedBuilder = new EmbedBuilder();
var adminCommands = "";
var adminCommands = "";
var normalCommands = "";
var DMCommands = "";
foreach (var cmd in PluginLoader.Commands!)
{
if (cmd.canUseDM)
DMCommands += cmd.Command + " ";
if (cmd.requireAdmin)
adminCommands += cmd.Command + " ";
else
if (cmd.canUseServer)
normalCommands += cmd.Command + " ";
}
embedBuilder.AddField("Admin Commands", adminCommands);
embedBuilder.AddField("Normal Commands", normalCommands);
embedBuilder.AddField("DM Commands", DMCommands);
context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
private EmbedBuilder GenerateHelpCommand(string command)
{
var embedBuilder = new EmbedBuilder();
var cmd = PluginLoader.Commands!.Find(p => p.Command == command || (p.Aliases is not null && p.Aliases.Contains(command)));
var cmd = PluginLoader.Commands!.Find(p => p.Command == command || (p.Aliases is not null && p.Aliases.Contains(command)));
if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.GetValue<string>("prefix") + cmd.Usage);
embedBuilder.AddField("Usage", cmd.Usage);
embedBuilder.AddField("Description", cmd.Description);
if (cmd.Aliases is null)
return embedBuilder;

View File

@@ -30,19 +30,33 @@ internal class Restart : DBCommand
/// </summary>
public string Usage => "restart [-p | -c | -args | -cmd] <args>";
/// <summary>
/// Check if the command can be used <inheritdoca DM <see cref="IChannel" />/>
/// </summary>
public bool canUseDM => false;
/// <summary>
/// Check if the command can be used in a server
/// </summary>
public bool canUseServer => true;
/// <summary>
/// Check if the command require administrator to be executed
/// </summary>
public bool requireAdmin => true;
public bool requireAdmin => false;
/// <summary>
/// The main body of the command
/// </summary>
/// <param name="context">The command context</param>
public async void ExecuteServer(DiscordLibCommands.SocketCommandContext context)
/// <param name="message">The command message</param>
/// <param name="client">The discord bot client</param>
/// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param>
public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
var args = Functions.GetArguments(context.Message);
var OS = Functions.GetOperatingSystem();
if (!(message.Author as SocketGuildUser).hasPermission(DiscordLib.GuildPermission.Administrator)) return;
var args = Functions.GetArguments(message);
var OS = Functions.GetOperatingSystem();
if (args.Count == 0)
{
switch (OS)

View File

@@ -1,10 +1,8 @@
using System;
using System.Collections.Generic;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager;
using PluginManager.Interfaces;
@@ -29,6 +27,16 @@ internal class Settings : DBCommand
/// </summary>
public string Usage => "set [keyword] [new Value]";
/// <summary>
/// Check if the command can be used <inheritdoca DM <see cref="IChannel" />/>
/// </summary>
public bool canUseDM => true;
/// <summary>
/// Check if the command can be used in a server
/// </summary>
public bool canUseServer => true;
/// <summary>
/// Check if the command require administrator to be executed
/// </summary>
@@ -38,13 +46,16 @@ internal class Settings : DBCommand
/// The main body of the command
/// </summary>
/// <param name="context">The command context</param>
public async void Execute(SocketCommandContext context)
/// <param name="message">The command message</param>
/// <param name="client">The discord bot client</param>
/// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param>
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
var channel = context.Message.Channel;
var channel = message.Channel;
try
{
var content = context.Message.Content;
var data = content.Split(' ');
var content = message.Content;
var data = content.Split(' ');
var keyword = data[1];
if (keyword.ToLower() == "help")
{

View File

@@ -1,13 +1,10 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager;
using static PluginManager.Others.Functions;
namespace DiscordBot.Discord.Core;
@@ -47,7 +44,7 @@ internal class Boot
public Boot(string botToken, string botPrefix)
{
this.botPrefix = botPrefix;
this.botToken = botToken;
this.botToken = botToken;
}
@@ -65,7 +62,7 @@ internal class Boot
{
DiscordSocketConfig config = new DiscordSocketConfig { AlwaysDownloadUsers = true };
client = new DiscordSocketClient(config);
client = new DiscordSocketClient(config);
service = new CommandService();
CommonTasks();
@@ -84,9 +81,9 @@ internal class Boot
{
if (client == null) return;
client.LoggedOut += Client_LoggedOut;
client.Log += Log;
client.LoggedIn += LoggedIn;
client.Ready += Ready;
client.Log += Log;
client.LoggedIn += LoggedIn;
client.Ready += Ready;
}
private Task Client_LoggedOut()
@@ -99,7 +96,7 @@ internal class Boot
private Task Ready()
{
Console.Title = "ONLINE";
isReady = true;
isReady = true;
return Task.CompletedTask;
}
@@ -141,5 +138,4 @@ internal class Boot
return Task.CompletedTask;
}
}

View File

@@ -1,10 +1,8 @@
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Others;
using PluginManager.Others.Permissions;
@@ -13,9 +11,9 @@ namespace DiscordBot.Discord.Core;
internal class CommandHandler
{
private readonly string botPrefix;
private readonly string botPrefix;
private readonly DiscordSocketClient client;
private readonly CommandService commandService;
private readonly CommandService commandService;
/// <summary>
/// Command handler constructor
@@ -25,9 +23,9 @@ internal class CommandHandler
/// <param name="botPrefix">The prefix to watch for</param>
public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix)
{
this.client = client;
this.client = client;
this.commandService = commandService;
this.botPrefix = botPrefix;
this.botPrefix = botPrefix;
}
/// <summary>
@@ -77,19 +75,57 @@ internal class CommandHandler
var plugin = PluginLoader.Commands!.Where(p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length) || (p.Aliases is not null && p.Aliases.Contains(message.Content.Split(' ')[0].Substring(botPrefix.Length)))).FirstOrDefault();
if (plugin is null) throw new System.Exception("Failed to run command. !");
if (plugin.requireAdmin && !context.Message.Author.isAdmin())
return;
if (plugin != null)
{
if (message.Channel == await message.Author.CreateDMChannelAsync())
{
if (plugin.canUseDM)
{
if (plugin.requireAdmin)
{
if (message.Author.isAdmin())
{
plugin.Execute(context, message, client, true);
Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
return;
}
if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(context);
else plugin.ExecuteServer(context);
await message.Channel.SendMessageAsync("This command is for administrators only !");
return;
}
plugin.Execute(context, message, client, true);
Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
return;
}
await message.Channel.SendMessageAsync("This command is not for DMs");
return;
}
if (plugin.canUseServer)
{
if (plugin.requireAdmin)
{
if (message.Author.isAdmin())
{
plugin.Execute(context, message, client, false);
Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
return;
}
await message.Channel.SendMessageAsync("This command is for administrators only !");
return;
}
plugin.Execute(context, message, client, false);
Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
}
}
}
catch (System.Exception ex)
catch
{
ex.WriteErrFile();
}
}
}

View File

@@ -8,7 +8,7 @@
<StartupObject />
<SignAssembly>False</SignAssembly>
<IsPublishable>True</IsPublishable>
<AssemblyVersion>1.0.0.13</AssemblyVersion>
<AssemblyVersion>1.0.0.10</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

View File

@@ -32,6 +32,10 @@ public class Program
public static void Main(string[] args)
{
Console.WriteLine("Loading resources ...");
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins/Commands");
Directory.CreateDirectory("./Data/Plugins/Events");
PreLoadComponents().Wait();
do
{
@@ -221,6 +225,23 @@ public class Program
return;
}
if (len > 0 && args[0] == "/test")
{
int p = 1;
bool allowed = true;
Console.CancelKeyPress += (sender, e) => allowed = false;
Console_Utilities.ProgressBar bar = new(ProgressBarType.NO_END);// { NoColor = false, Color = ConsoleColor.DarkRed };
Console.WriteLine("Press Ctrl + C to stop.");
while (p <= int.MaxValue - 1 && allowed)
{
bar.Update(100 / p);
await Task.Delay(100);
p++;
}
return;
}
if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage")))
{
if (args.Contains("lp") || args.Contains("loadplugins"))
@@ -246,13 +267,6 @@ public class Program
len = 0;
}
if (len > 0 && args[0] == "/updateplug")
{
string plugName = args.MergeStrings(1);
Console.WriteLine("Updating " + plugName);
await ConsoleCommandsHandler.ExecuteCommad("dwplug" + plugName);
return;
}
if (len == 0 || (args[0] != "--exec" && args[0] != "--execute"))
{
@@ -334,10 +348,6 @@ public class Program
{
Console_Utilities.ProgressBar main = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start();
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins/Commands");
Directory.CreateDirectory("./Data/Plugins/Events");
Directory.CreateDirectory("./Data/PAKS");
await Config.LoadConfig();
if (Config.ContainsKey("DeleteLogsAtStartup"))
if (Config.GetValue<bool>("DeleteLogsAtStartup"))
@@ -371,7 +381,7 @@ public class Program
List<string> onlineSettingsList = await ServerCom.ReadTextFromURL("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/OnlineData");
main.Stop("Loaded online settings. Loading updates ...");
main.Stop();
foreach (var key in onlineSettingsList)
{
if (key.Length <= 3 || !key.Contains(' ')) continue;
@@ -388,16 +398,14 @@ public class Program
string url = $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0.zip";
//string url2 = $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}-preview/net6.0.zip";
Process.Start(".\\Updater\\Updater.exe", $"{newVersion} {url} {Process.GetCurrentProcess().ProcessName}");
Process.Start("./Updater/Updater.exe", $"/update {url} ./DiscordBot.exe ./");
}
else
{
string url = $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip";
Process.Start("./Updater/Updater", $"/update {url} ./DiscordBot ./");
}
//Environment.Exit(0);
Environment.Exit(0);
}
break;
@@ -414,7 +422,7 @@ public class Program
Config.UpdaterVersion = updaternewversion;
File.Delete("Updater.zip");
await Config.SaveConfig(SaveType.NORMAL);
bar.Stop("Updater has been updated !");
bar.Stop();
Console.Clear();
}
break;

View File

@@ -11,7 +11,7 @@ namespace PluginManager
{
internal class AppConfig
{
public string? UpdaterVersion { get; set; }
public string UpdaterVersion { get; set; }
public Dictionary<string, object>? ApplicationVariables { get; init; }
public List<string>? ProtectedKeyWords { get; init; }
public Dictionary<string, string>? PluginVersions { get; init; }
@@ -184,11 +184,6 @@ namespace PluginManager
SaveConfig(SaveType.NORMAL);
}
public static bool IsReadOnly(string key)
{
return appConfig.ProtectedKeyWords.Contains(key);
}
public static async Task SaveConfig(SaveType type)
{
if (type == SaveType.NORMAL)
@@ -234,6 +229,6 @@ namespace PluginManager
public static bool ContainsValue<T>(T value) => appConfig!.ApplicationVariables!.ContainsValue(value!);
public static bool ContainsKey(string key) => appConfig!.ApplicationVariables!.ContainsKey(key);
public static IDictionary<string, object> GetAllVariables() => appConfig.ApplicationVariables;
public static ReadOnlyDictionary<string, object> GetAllVariables() => new(appConfig!.ApplicationVariables!);
}
}

View File

@@ -1,5 +1,4 @@
using System.Collections.Generic;
using Discord.Commands;
using Discord.WebSocket;
@@ -29,20 +28,27 @@ public interface DBCommand
/// </summary>
string Usage { get; }
/// <summary>
/// true if the command can be used in a DM channel, otherwise false
/// </summary>
bool canUseDM { get; }
/// <summary>
/// true if the command can be used in a server, otherwise false
/// </summary>
bool canUseServer { get; }
/// <summary>
/// true if the command requre admin, otherwise false
/// </summary>
bool requireAdmin { get; }
/// <summary>
/// The main body of the command. This is what is executed when user calls the command in Server
/// The main body of the command. This is what is executed when user calls the command
/// </summary>
/// <param name="context">The disocrd Context</param>
void ExecuteServer(SocketCommandContext context) { }
/// <summary>
/// The main body of the command. This is what is executed when user calls the command in DM
/// </summary>
/// <param name="context">The disocrd Context</param>
void ExecuteDM(SocketCommandContext context) { }
/// <param name="message">The message that the user types</param>
/// <param name="client">The discord client of the bot</param>
/// <param name="isDM">true if the message was sent from DM, otherwise false. It is always false if canUseDM is false</param>
void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM);
}

View File

@@ -14,7 +14,9 @@ using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Online.Helpers;
using PluginManager.Online.Updates;
using PluginManager.Others;
namespace PluginManager.Items;
public class ConsoleCommandsHandler
@@ -160,22 +162,13 @@ public class ConsoleCommandsHandler
path = "./Data/Plugins/" + info[0] + "s/" + name + "." + (info[0] == "Command" ? PluginLoader.pluginCMDExtension : PluginLoader.pluginEVEExtension);
else
path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
if (Others.OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{
await ServerCom.DownloadFileAsync(info[1], path);
}
else if (Others.OperatingSystem.LINUX == Functions.GetOperatingSystem())
{
Others.Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
await ServerCom.DownloadFileNoProgressAsync(info[1], path);
bar.Stop("Plugin Downloaded !");
}
if (info[0] == "Event")
Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Event));
else if (info[0] == "Command")
Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Command));
//Console.WriteLine("Downloading: " + path + " [" + info[1] + "]");
await ServerCom.DownloadFileAsync(info[1], path);
if (info[0] == "Command" || info[0] == "Event")
if (info[0] == "Event")
Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Event));
else if (info[0] == "Command")
Config.PluginConfig.InstalledPlugins.Add(new(name, PluginType.Command));
Console.WriteLine("\n");
@@ -195,26 +188,16 @@ public class ConsoleCommandsHandler
var split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}");
if (File.Exists("./" + split[1])) File.Delete("./" + split[1]);
if (Others.OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
else if (Others.OperatingSystem.LINUX == Functions.GetOperatingSystem())
{
Others.Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]);
bar.Stop("Item downloaded !");
}
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine();
if (split[0].EndsWith(".pak"))
File.Move("./" + split[1], "./Data/PAKS/" + split[1], true);
else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg"))
if (split[0].EndsWith(".zip") || split[0].EndsWith(".pak") || split[0].EndsWith(".pkg"))
{
Console.WriteLine($"Extracting {split[1]} ...");
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);// { Max = 100f, Color = ConsoleColor.Green };
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END) { Max = 100f, Color = ConsoleColor.Green };
bar.Start();
await Functions.ExtractArchive("./" + split[1], "./", null, UnzipProgressType.PercentageFromTotalSize);
bar.Stop("Extracted");
bar.Stop();
Console.WriteLine("\n");
File.Delete("./" + split[1]);
}
@@ -225,12 +208,10 @@ public class ConsoleCommandsHandler
VersionString? ver = await VersionString.GetVersionOfPackageFromWeb(name);
if (ver is null) throw new Exception("Incorrect version");
Config.SetPluginVersion(name, $"{ver.PackageVersionID}.{ver.PackageMainVersion}.{ver.PackageCheckVersion}");
// Console.WriteLine();
isDownloading = false;
}
);
@@ -283,18 +264,17 @@ public class ConsoleCommandsHandler
bar.Start();
await Config.SaveConfig(SaveType.NORMAL);
await Config.SaveConfig(SaveType.BACKUP);
bar.Stop("Saved config !");
await Task.Delay(4000);
bar.Stop();
Console.WriteLine();
await client.StopAsync();
await client.DisposeAsync();
await Task.Delay(1000);
Environment.Exit(0);
}
);
AddCommand("import", "Load an external command", "import [pluginName]", async (args) =>
AddCommand("extern", "Load an external command", "extern [pluginName]", async (args) =>
{
if (args.Length <= 1) return;
string pName = Functions.MergeStrings(args, 1);

View File

@@ -42,15 +42,12 @@ namespace PluginManager.Others
public bool NoColor { get; init; }
public ProgressBarType type { get; set; }
public int TotalLength { get; private set; }
private int BarLength = 32;
private int position = 1;
private bool positive = true;
private bool isRunning;
public async void Start()
{
if (type != ProgressBarType.NO_END)
@@ -66,23 +63,6 @@ namespace PluginManager.Others
}
}
public async void Start(string message)
{
if (type != ProgressBarType.NO_END)
throw new Exception("Only NO_END progress bar can use this method");
if (isRunning)
throw new Exception("This progress bar is already running");
isRunning = true;
TotalLength = message.Length + BarLength + 5;
while (isRunning)
{
UpdateNoEnd(message);
await System.Threading.Tasks.Task.Delay(100);
}
}
public void Stop()
{
if (type != ProgressBarType.NO_END)
@@ -92,45 +72,20 @@ namespace PluginManager.Others
isRunning = false;
}
public void Stop(string message)
{
Stop();
if (message is not null)
{
Console.CursorLeft = 0;
for (int i = 0; i < BarLength + message.Length + 1; i++)
Console.Write(" ");
Console.CursorLeft = 0;
Console.WriteLine(message);
}
}
public void Update(float progress)
{
if (type == ProgressBarType.NO_END)
throw new Exception("This function is for progress bars with end");
UpdateNormal(progress);
}
private void UpdateNoEnd(string message)
{
Console.CursorLeft = 0;
Console.Write("[");
for (int i = 1; i <= position; i++)
Console.Write(" ");
Console.Write("<==()==>");
position += positive ? 1 : -1;
for (int i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Console.Write(" ");
Console.Write("] " + message);
if (position == BarLength - 1 || position == 1)
positive = !positive;
switch (type)
{
case ProgressBarType.NORMAL:
UpdateNormal(progress);
return;
case ProgressBarType.NO_END:
if (progress <= 99.9f)
UpdateNoEnd();
return;
default:
return;
}
}
private void UpdateNoEnd()
@@ -146,8 +101,6 @@ namespace PluginManager.Others
Console.Write("]");
if (position == BarLength - 1 || position == 1)
positive = !positive;
}

View File

@@ -50,42 +50,21 @@ namespace PluginManager.Others
/// <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)
public static async Task<Stream?> ReadFromPakAsync(string FileName, string archFile)
{
archFile = pakFolder + archFile;
if (!File.Exists(archFile))
throw new Exception("Failed to load file !");
Directory.CreateDirectory(pakFolder);
if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !");
try
{
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 (Stream s = entry.Open())
using (StreamReader reader = new StreamReader(s))
{
textValue = await reader.ReadToEndAsync();
reader.Close();
s.Close();
fs.Close();
}
}
}
return textValue;
}
catch
{
await Task.Delay(100);
return await ReadFromPakAsync(FileName, archFile);
}
using ZipArchive archive = ZipFile.OpenRead(archFile);
ZipArchiveEntry? entry = archive.GetEntry(FileName);
if (entry is null) return Stream.Null;
MemoryStream stream = new MemoryStream();
await (entry?.Open()!).CopyToAsync(stream);
return stream;
}
/// <summary>
/// Write logs to file
/// </summary>
@@ -108,11 +87,6 @@ namespace PluginManager.Others
File.AppendAllText(errPath, ErrMessage + " \n");
}
public static void WriteErrFile(this Exception ex)
{
WriteErrFile(ex.ToString());
}
/// <summary>
/// Merge one array of strings into one string
/// </summary>

View File

@@ -23,6 +23,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CMD_LevelingSystem", "CMD_L
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Roles", "Roles\Roles.csproj", "{954F2AA9-6624-4554-946D-0F17B84487C3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Others", "Others", "{727BBA0B-9114-4BC8-B9A8-3F461449A564}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Updater", "Updater\Updater.csproj", "{24616F7E-E2E9-45A3-8A44-AB51FCD2D525}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -57,6 +61,10 @@ Global
{954F2AA9-6624-4554-946D-0F17B84487C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{954F2AA9-6624-4554-946D-0F17B84487C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{954F2AA9-6624-4554-946D-0F17B84487C3}.Release|Any CPU.Build.0 = Release|Any CPU
{24616F7E-E2E9-45A3-8A44-AB51FCD2D525}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{24616F7E-E2E9-45A3-8A44-AB51FCD2D525}.Debug|Any CPU.Build.0 = Debug|Any CPU
{24616F7E-E2E9-45A3-8A44-AB51FCD2D525}.Release|Any CPU.ActiveCfg = Release|Any CPU
{24616F7E-E2E9-45A3-8A44-AB51FCD2D525}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -69,6 +77,8 @@ Global
{EEC445DC-0C4B-43EA-8694-606BA0390B77} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012}
{1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{954F2AA9-6624-4554-946D-0F17B84487C3} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{727BBA0B-9114-4BC8-B9A8-3F461449A564} = {1862ABD5-7C30-4F15-A561-45AC8A9CA10E}
{24616F7E-E2E9-45A3-8A44-AB51FCD2D525} = {727BBA0B-9114-4BC8-B9A8-3F461449A564}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF}

454
Updater/.gitignore vendored Normal file
View File

@@ -0,0 +1,454 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# JetBrains Rider
.idea/
*.sln.iml
##
## Visual Studio Code
##
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

7
Updater/App.axaml Normal file
View File

@@ -0,0 +1,7 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Updater.App">
<Application.Styles>
<FluentTheme Mode="Dark"/>
</Application.Styles>
</Application>

24
Updater/App.axaml.cs Normal file
View File

@@ -0,0 +1,24 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
namespace Updater
{
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow = new MainWindow() { Width = 250, Height = 50 };
}
base.OnFrameworkInitializationCompleted();
}
}
}

12
Updater/MainWindow.axaml Normal file
View File

@@ -0,0 +1,12 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="250" d:DesignHeight="50"
x:Class="Updater.MainWindow"
Title="Updater">
<StackPanel Margin="0">
<Label Content="Updating ... "/>
<ProgressBar x:Class="Updater.MainWindow" x:Name="progressBar1" IsIndeterminate="True" />
</StackPanel>
</Window>

View File

@@ -0,0 +1,36 @@
using Avalonia.Controls;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Threading.Tasks;
namespace Updater
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Activated += (sender, e) => FormActive();
}
public async void FormActive()
{
if (Program.Command != "/update")
return;
await Task.Delay(3000);
WebClient c = new WebClient();
Directory.CreateDirectory("./Updater/Downloads");
await c.DownloadFileTaskAsync(Program.Link, "./Updater/Downloads/Update.zip");
await Task.Run(() => ZipFile.ExtractToDirectory("./Updater/Downloads/Update.zip", Program.Location, true));
Process.Start(Program.AppToOpen);
File.Delete("./Updater/Downloads/Update.zip");
Environment.Exit(0);
}
}
}

34
Updater/Program.cs Normal file
View File

@@ -0,0 +1,34 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using System;
namespace Updater
{
internal class Program
{
public static string Command, Link, AppToOpen, Location;
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
[STAThread]
public static void Main(string[] args)
{
Command = args[0];
Link = args[1];
AppToOpen = args[2];
Location = string.Join(' ', args, 3, args.Length - 3);
BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
}
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}
}

27
Updater/Updater.csproj Normal file
View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<!--Avalonia doesen't support TrimMode=link currently,but we are working on that https://github.com/AvaloniaUI/Avalonia/issues/6892 -->
<TrimMode>copyused</TrimMode>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
</PropertyGroup>
<ItemGroup>
<None Remove=".gitignore" />
</ItemGroup>
<ItemGroup>
<!--This helps with theme dll-s trimming.
If you will publish your application in self-contained mode with p:PublishTrimmed=true and it will use Fluent theme Default theme will be trimmed from the output and vice versa.
https://github.com/AvaloniaUI/Avalonia/issues/5593 -->
<TrimmableAssembly Include="Avalonia.Themes.Fluent" />
<TrimmableAssembly Include="Avalonia.Themes.Default" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.10.18" />
<PackageReference Include="Avalonia.Desktop" Version="0.10.18" />
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="0.10.18" />
<PackageReference Include="XamlNameReferenceGenerator" Version="1.3.4" />
</ItemGroup>
</Project>