Updated display features

This commit is contained in:
2022-07-17 14:21:16 +03:00
parent b8ec6f42df
commit c415fa1c0c
16 changed files with 242 additions and 177 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -3,8 +3,6 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Net.Queue;
using DiscordBot.Discord.Core;
using PluginManager;
using PluginManager.Items;
@@ -45,7 +43,8 @@ public class Program
Console.Write("Prefix = ");
var prefix = Console.ReadLine()![0];
if (prefix == ' ' || char.IsDigit(prefix)) return;
if (prefix == ' ' || char.IsDigit(prefix))
return;
Config.AddValueToVariables("prefix", prefix.ToString(), false);
}
@@ -93,20 +92,33 @@ public class Program
Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkYellow;
List<string> startupMessageList = await ServerCom.ReadTextFromFile("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage");
List<string> startupMessageList = await ServerCom.ReadTextFromURL("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage");
foreach (var message in startupMessageList) Console.WriteLine(message);
foreach (var message in startupMessageList)
Console.WriteLine(message);
Console.WriteLine($"Running on version: {Config.GetValue<string>("Version") ?? System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()}");
Console.WriteLine($"Git URL: {Config.GetValue<string>("GitURL") ?? " Could not find Git URL"}");
Console_Utilities.WriteColorText("&rRemember to close the bot using the ShutDown command &y(sd) &ror some settings won't be saved");
Console_Utilities.WriteColorText("&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"============================ LOG ============================");
try
{
var token = Config.GetValue<string>("token");
#if DEBUG
Console.WriteLine("Starting in DEBUG MODE");
if (!Directory.Exists("./Data/BetaTest"))
Console.WriteLine("Failed to start in debug mode because the folder ./Data/BetaTest does not exist");
else
{
token = File.ReadAllText("./Data/BetaTest/token.txt");
//Debug mode code...
}
#endif
var prefix = Config.GetValue<string>("prefix");
var discordbooter = new Boot(token, prefix);
@@ -239,7 +251,7 @@ public class Program
if (Config.GetValue<bool>("DeleteLogsAtStartup"))
foreach (var file in Directory.GetFiles("./Output/Logs/"))
File.Delete(file);
List<string> OnlineDefaultKeys = await ServerCom.ReadTextFromFile("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys");
List<string> OnlineDefaultKeys = await ServerCom.ReadTextFromURL("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys");
Config.PluginConfig.Load();
@@ -263,7 +275,7 @@ public class Program
}
}
List<string> onlineSettingsList = await ServerCom.ReadTextFromFile("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/OnlineData");
List<string> onlineSettingsList = await ServerCom.ReadTextFromURL("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/OnlineData");
foreach (var key in onlineSettingsList)
{
if (key.Length <= 3 || !key.Contains(' ')) continue;

View File

@@ -22,10 +22,20 @@ internal class Leave : DBCommand
{
if (Data.audioClient is not null && Data.voiceChannel is not null)
{
Data.Playlist.ClearQueue();
Data.MusicPlayer.isPlaying = false;
await Data.audioClient.StopAsync();
await Data.voiceChannel.DisconnectAsync();
}
if (Data.Playlist is not null)
{
Data.Playlist.ClearQueue();
Data.Playlist = new();
}
if (Data.MusicPlayer is not null)
{
Data.MusicPlayer.Stop();
Data.MusicPlayer = null;
}
}
}

View File

@@ -1,9 +1,5 @@
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
using PluginManager.Others;
namespace MusicCommands;
@@ -48,54 +44,8 @@ internal class MusicPlayer
isPlaying = false;
}
/*
public MusicPlayer(Stream input, Stream output)
{
inputStream = input;
outputStream = output;
}
public Stream inputStream { get; } // from FFMPEG
public Stream outputStream { get; } // to Voice Channel
public bool Paused { get; set; }
private bool _stop { get; set; }
public void Stop()
{
_stop = true;
isPlaying = false;
}
public async Task StartSendAudio(int bsize)
{
Paused = false;
_stop = false;
while (!_stop)
{
if (Paused) continue;
var buffer = new byte[bsize];
var bcount = await inputStream.ReadAsync(buffer, 0, bsize);
if (bcount <= 0)
{
Stop();
Data.CurrentlyRunning = null;
break;
}
try
{
await outputStream.WriteAsync(buffer, 0, bcount);
}
catch (Exception ex)
{
await outputStream.FlushAsync();
Functions.WriteLogFile(ex.ToString());
}
}
}*/
}

View File

@@ -19,7 +19,7 @@ namespace PluginManager
{
public static class PluginConfig
{
public static List<Tuple<string, PluginType>> InstalledPlugins = new();
public static readonly List<Tuple<string, PluginType>> InstalledPlugins = new();
public static void Load()
{

View File

@@ -5,7 +5,7 @@ using PluginManager.Others;
namespace PluginManager.Items;
internal class Command
public class Command
{
/// <summary>
/// The author of the command
@@ -20,10 +20,7 @@ internal class Command
{
Author = message.Author;
var data = message.Content.Split(' ');
if (data.Length > 1)
Arguments = new List<string>(data.MergeStrings(1).Split(' '));
else
Arguments = new List<string>();
Arguments = data.Length > 1 ? new List<string>(data.MergeStrings(1).Split(' ')) : new List<string>();
CommandName = data[0].Substring(1);
PrefixUsed = data[0][0];
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
@@ -48,7 +47,7 @@ public class ConsoleCommandsHandler
}
items.Add(new[] { "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(items);
Console_Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
}
else
{
@@ -147,7 +146,7 @@ public class ConsoleCommandsHandler
{
Console.WriteLine($"Downloading requirements for plugin : {name}");
var lines = await ServerCom.ReadTextFromFile(info[2]);
var lines = await ServerCom.ReadTextFromURL(info[2]);
foreach (var line in lines)
{

View File

@@ -18,21 +18,19 @@ namespace PluginManager.Online.Helpers
/// <param name="progress">The <see cref="IProgress{T}"/> that is used to track the download progress</param>
/// <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, CancellationToken cancellation = default)
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)
{
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation))
{
var contentLength = response.Content.Headers.ContentLength;
using (var download = await response.Content.ReadAsStreamAsync())
using (var download = await response.Content.ReadAsStreamAsync(cancellation))
{
// Ignore progress reporting when no progress reporter was
// passed or when the content length is unknown
if (progress == null || !contentLength.HasValue)
{
await download.CopyToAsync(destination);
await download.CopyToAsync(destination, cancellation);
return;
}
@@ -41,9 +39,11 @@ namespace PluginManager.Online.Helpers
{
progress.Report((float)totalBytes / contentLength.Value * 100);
downloadedBytes?.Report(totalBytes);
});
}
);
// Use extension method to report progress while downloading
await download.CopyToOtherStreamAsync(destination, 81920, relativeProgress, cancellation);
await download.CopyToOtherStreamAsync(destination, bufferSize, relativeProgress, cancellation);
progress.Report(1);
}
}
@@ -57,10 +57,8 @@ namespace PluginManager.Online.Helpers
/// <returns></returns>
internal static async Task<string> DownloadStringAsync(string url, CancellationToken cancellation = default)
{
using (var client = new HttpClient())
{
return await client.GetStringAsync(url);
}
using var client = new HttpClient();
return await client.GetStringAsync(url, cancellation);
}

View File

@@ -30,7 +30,7 @@ public class PluginsManager
{
try
{
var list = await ServerCom.ReadTextFromFile(PluginsLink);
var list = await ServerCom.ReadTextFromURL(PluginsLink);
var lines = list.ToArray();
var data = new List<string[]>();
@@ -43,7 +43,8 @@ public class PluginsManager
data.Add(new[] { "-", "-", "-", "-", "-" });
for (var i = 0; i < len; i++)
{
if (lines[i].Length <= 2) continue;
if (lines[i].Length <= 2)
continue;
var content = lines[i].Split(',');
var display = new string[titles.Length];
if (op == OperatingSystem.WINDOWS)
@@ -54,7 +55,7 @@ public class PluginsManager
display[1] = content[1];
display[2] = content[2];
if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
display[3] = ((await ServerCom.ReadTextFromURL(content[5])).Count + 1).ToString();
else
display[3] = "1";
@@ -72,7 +73,8 @@ public class PluginsManager
display[0] = content[0];
display[1] = content[1];
display[2] = content[2];
if (content.Length == 6 && (content[5] != null || content[5].Length > 2)) display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
display[3] = ((await ServerCom.ReadTextFromURL(content[5])).Count + 1).ToString();
if (Config.PluginConfig.Contains(content[0]) || Config.PluginConfig.Contains(content[0]))
display[4] = "✓";
else
@@ -88,7 +90,7 @@ public class PluginsManager
}
catch (Exception exception)
{
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
}
}
@@ -102,7 +104,7 @@ public class PluginsManager
{
try
{
var list = await ServerCom.ReadTextFromFile(PluginsLink);
var list = await ServerCom.ReadTextFromURL(PluginsLink);
var lines = list.ToArray();
var len = lines.Length;
for (var i = 0; i < len; i++)
@@ -110,8 +112,10 @@ public class PluginsManager
var contents = lines[i].Split(',');
if (contents[0] == name)
{
if (contents.Length == 6) return new[] { contents[2], contents[3], contents[5] };
if (contents.Length == 5) return new[] { contents[2], contents[3], string.Empty };
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");
}
}

View File

@@ -9,15 +9,14 @@ using PluginManager.Others;
namespace PluginManager.Online
{
public class ServerCom
public static class ServerCom
{
/// <summary>
/// Read all lines from a file async
/// </summary>
/// <param name="link">The link of the file</param>
/// <returns></returns>
public static async Task<List<string>> ReadTextFromFile(string link)
public static async Task<List<string>> ReadTextFromURL(string link)
{
string response = await OnlineFunctions.DownloadStringAsync(link);
string[] lines = response.Split('\n');
@@ -53,14 +52,11 @@ namespace PluginManager.Online
public static async Task DownloadFileAsync(string URL, string location)
{
bool isDownloading = true;
int c_progress = 0;
float c_progress = 0;
Console_Utilities.ProgressBar pbar = new Console_Utilities.ProgressBar { Max = 100, NoColor = true };
Console_Utilities.ProgressBar pbar = new Console_Utilities.ProgressBar { Max = 100f, NoColor = true };
IProgress<float> progress = new Progress<float>(percent =>
{
c_progress = (int)percent;
});
IProgress<float> progress = new Progress<float>(percent => { c_progress = percent; });
Task updateProgressBarTask = new Task(() =>
@@ -68,7 +64,8 @@ namespace PluginManager.Online
while (isDownloading)
{
pbar.Update(c_progress);
if (c_progress == 100) break;
if (c_progress == 100f)
break;
Thread.Sleep(500);
}
}
@@ -78,8 +75,8 @@ namespace PluginManager.Online
await DownloadFileAsync(URL, location, progress);
c_progress = 100;
pbar.Update(100);
c_progress = pbar.Max;
pbar.Update(100f);
isDownloading = false;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Discord;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -48,7 +49,7 @@ namespace PluginManager.Others
if (progress.CanAproximateTo(Max))
Console.Write(progress + " % ✓");
else
Console.Write(progress + " % ");
Console.Write(MathF.Round(progress, 2) + " % ");
}
else
Console.Write(progress + $"{speed} {unit}/s ");
@@ -63,7 +64,9 @@ namespace PluginManager.Others
/// A way to create a table based on input data
/// </summary>
/// <param name="data">The List of arrays of strings that represent the rows.</param>
public static void FormatAndAlignTable(List<string[]> data)
public static void FormatAndAlignTable(List<string[]> data, TableFormat format = TableFormat.CENTER_EACH_COLUMN_BASED)
{
if (format == TableFormat.CENTER_EACH_COLUMN_BASED)
{
char tableLine = '-';
char tableCross = '+';
@@ -71,17 +74,17 @@ namespace PluginManager.Others
int[] len = new int[data[0].Length];
foreach (var line in data)
{
for (int i = 0; i < line.Length; i++)
if (line[i].Length > len[i])
len[i] = line[i].Length;
}
foreach (string[] row in data)
{
if (row[0][0] == tableLine) Console.Write(tableCross);
else Console.Write(tableWall);
if (row[0][0] == tableLine)
Console.Write(tableCross);
else
Console.Write(tableWall);
for (int l = 0; l < row.Length; l++)
{
if (row[l][0] == tableLine)
@@ -97,7 +100,6 @@ namespace PluginManager.Others
}
else
{
int lenHalf = row[l].Length / 2;
for (int i = 0; i < ((len[l] + 4) / 2 - lenHalf); ++i)
Console.Write(" ");
@@ -110,46 +112,135 @@ namespace PluginManager.Others
Console.Write(row[l][0] == tableLine ? tableCross : tableWall);
}
Console.WriteLine(); //end line
}
return;
}
if (format == TableFormat.CENTER_OVERALL_LENGTH)
{
int maxLen = 0;
foreach (string[] row in data)
foreach (string s in row)
if (s.Length > maxLen)
maxLen = s.Length;
int div = (maxLen + 4) / 2;
foreach (string[] row in data)
{
Console.Write("\t");
if (row[0] == "-")
Console.Write("+");
else
Console.Write("|");
foreach (string s in row)
{
if (s == "-")
{
for (int i = 0; i < maxLen + 4; ++i)
Console.Write("-");
}
else if (s.Length == maxLen)
{
Console.Write(" ");
Console.Write(s);
Console.Write(" ");
}
else
{
int lenHalf = s.Length / 2;
for (int i = 0; i < div - lenHalf; ++i)
Console.Write(" ");
Console.Write(s);
for (int i = div + lenHalf + 1; i < maxLen + 4; ++i)
Console.Write(" ");
if (s.Length % 2 == 0)
Console.Write(" ");
}
if (s == "-")
Console.Write("+");
else
Console.Write("|");
}
Console.WriteLine(); //end line
}
return;
}
if (format == TableFormat.DEFAULT)
{
int[] widths = new int[data[0].Length];
int space_between_columns = 5;
for (int i = 0; i < data.Count; i++)
{
for (int j = 0; j < data[i].Length; j++)
{
if (data[i][j].Length > widths[j])
widths[j] = data[i][j].Length;
}
}
public static void WriteColorText(string text, bool appendNewLine = true)
for (int i = 0; i < data.Count; i++)
{
for (int j = 0; j < data[i].Length; j++)
{
if (data[i][j] == "-")
data[i][j] = " ";
Console.Write(data[i][j]);
for (int k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
Console.Write(" ");
}
string[] words = text.Split(' ');
ConsoleColor fg = Console.ForegroundColor;
Dictionary<string, ConsoleColor> colors = new Dictionary<string, ConsoleColor>()
Console.WriteLine();
}
return;
}
throw new Exception("Unknown type of table");
}
public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{
{ "&g", ConsoleColor.Green },
{ "&b", ConsoleColor.Blue },
{ "&r", ConsoleColor.Red },
{ "&m", ConsoleColor.Magenta },
{ "&y", ConsoleColor.Yellow },
{ "&c", fg }
ConsoleColor initialForeGround = Console.ForegroundColor;
Dictionary<char, ConsoleColor> colors = new()
{
{ 'g', ConsoleColor.Green },
{ 'b', ConsoleColor.Blue },
{ 'r', ConsoleColor.Red },
{ 'm', ConsoleColor.Magenta },
{ 'y', ConsoleColor.Yellow },
{ 'c', initialForeGround }
};
foreach (string word in words)
char[] input = text.ToCharArray();
for (int i = 0; i < input.Length; i++)
{
if (word.Length >= 2)
if (input[i] == '&')
{
string prefix = word.Substring(0, 2);
if (colors.ContainsKey(prefix))
Console.ForegroundColor = colors[prefix];
if (i + 1 < input.Length)
{
if (colors.ContainsKey(input[i + 1]))
{
Console.ForegroundColor = colors[input[i + 1]];
i++;
}
}
}
else
Console.Write(input[i]);
}
string m = colors.Keys.Aggregate(word, (current, key) => current.Replace(key, ""));
Console.Write(m + " ");
Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd)
Console.WriteLine();
}
Console.CursorLeft--;
if (appendNewLine)
Console.Write('\n');
Console.ForegroundColor = fg;
}
}
}

View File

@@ -29,3 +29,5 @@ public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL }
public enum PluginType { Command, Event, Unknown }
public enum UnzipProgressType { PercentageFromNumberOfFiles, PercentageFromTotalSize }
public enum TableFormat { CENTER_EACH_COLUMN_BASED, CENTER_OVERALL_LENGTH, DEFAULT }

View File

@@ -38,6 +38,11 @@ namespace PluginManager.Others
/// </summary>
public static readonly string pakFolder = @"./Data/Resources/PAK/";
/// <summary>
/// Beta testing folder
/// </summary>
public static readonly string betaFolder = @"./Data/BetaTest/";
/// <summary>
/// Read data from a file that is inside an archive (ZIP format)