Improved download system

This commit is contained in:
2022-04-25 14:16:34 +03:00
parent 47a1d5a284
commit eb12c012a3
10 changed files with 354 additions and 270 deletions

View File

@@ -1,82 +0,0 @@
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using PluginManager.Items;
namespace PluginManager.Online
{
public class Downloader
{
public bool isWorking { get; private set; }
public int percent { get; private set; }
private string fileName;
private string downloadLink;
public Downloader(string fileName, string fileLink)
{
this.downloadLink = fileLink;
this.fileName = fileName;
}
public async Task DownloadFileAsync(string location = @"./Downloads/", string? pluginType = null, string? customMessage = null)
{
if (customMessage != null)
Console.WriteLine(customMessage);
Directory.CreateDirectory(location);
if (isWorking) return;
isWorking = true;
percent = 0;
Spinner s = new Spinner();
Console.Write("Downloading:\t\t");
s.Start();
#pragma warning disable SYSLIB0014
WebClient client = new WebClient();
#pragma warning restore SYSLIB0014
client.DownloadFileCompleted += (sender, args) =>
{
isWorking = false;
s.Stop();
var c = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("OK");
Console.ForegroundColor = c;
Console.Write(" !\n");
//Console.WriteLine("Your plugin has been successfully downloaded !");
if (pluginType == "Event/Command" || pluginType == "Command/Event")
{
File.Copy(location + fileName, location + "Commands/" + fileName, true);
File.Move(location + fileName, location + "Events/" + fileName, true);
}
};
string l = "";
if (pluginType == "Command")
l = location + "Commands/" + fileName;
else if (pluginType == "Event")
l = location + "Events/" + fileName;
else l = location + fileName;
try
{
await client.DownloadFileTaskAsync(new Uri(this.downloadLink), l);
}
catch
{
var c = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("FAIL");
Console.ForegroundColor = c;
Console.Write(" !\n");
}
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using PluginManager.Others;
namespace PluginManager.Online.Helpers
{
internal static class OnlineFunctions
{
internal static async Task DownloadFileAsync(this HttpClient client, string url, Stream destination, IProgress<float> progress = null, CancellationToken cancellation = default)
{
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
var contentLength = response.Content.Headers.ContentLength;
using (var download = await response.Content.ReadAsStreamAsync())
{
// 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);
return;
}
// Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
var relativeProgress = new Progress<long>(totalBytes => progress.Report((float)totalBytes / contentLength.Value * 100));
// Use extension method to report progress while downloading
await download.CopyToOtherStreamAsync(destination, 81920, relativeProgress, cancellation);
progress.Report(1);
}
}
}
internal static async Task<string> DownloadStringAsync(string url, CancellationToken cancellation = default)
{
using (var client = new HttpClient())
{
return await client.GetStringAsync(url);
}
}
}
}

View File

@@ -15,13 +15,17 @@ namespace PluginManager.Online
public async Task ListAllLanguages()
{
try
{
#pragma warning disable SYSLIB0014
WebClient client = new WebClient();
#pragma warning restore SYSLIB0014
Stream data = await client.OpenReadTaskAsync(link);
string[] lines = (await new StreamReader(data).ReadToEndAsync()).Split('\n');
/*#pragma warning disable SYSLIB0014
WebClient client = new WebClient();
#pragma warning restore SYSLIB0014
Stream data = await client.OpenReadTaskAsync(link);
string[] lines = (await new StreamReader(data).ReadToEndAsync()).Split('\n');*/
List<string> list = await ServerCom.ReadTextFromFile(link);
string[] lines = list.ToArray();
List<string[]> info = new List<string[]>();
info.Add(new string[] { "-", "-" });
info.Add(new string[] { "Language Name", "File Size" });
@@ -34,7 +38,7 @@ namespace PluginManager.Online
info.Add(new string[] { d[0], d[1] });
}
info.Add(new string[] { "-", "-" });
Functions.FormatAndAlignTable(info);
Console_Utilities.FormatAndAlignTable(info);
}
catch (Exception exception)
@@ -49,11 +53,9 @@ namespace PluginManager.Online
{
try
{
#pragma warning disable SYSLIB0014
WebClient client = new WebClient();
#pragma warning restore SYSLIB0014
Stream data = await client.OpenReadTaskAsync(link);
string[] lines = (await new StreamReader(data).ReadToEndAsync()).Split('\n');
List<string> list = await ServerCom.ReadTextFromFile(link);
string[] lines = list.ToArray();
foreach (var line in lines)
{
if (line.Length <= 2) continue;

View File

@@ -21,16 +21,12 @@ namespace PluginManager.Online
{
try
{
#pragma warning disable SYSLIB0014
WebClient client = new WebClient();
#pragma warning restore SYSLIB0014
Stream s = await client.OpenReadTaskAsync(PluginsLink);
string text = await new StreamReader(s).ReadToEndAsync();
List<string> list = await ServerCom.ReadTextFromFile(PluginsLink);
string[] lines = list.ToArray();
List<string[]> data = new List<string[]>();
var op = Functions.GetOperatinSystem();
string[] lines = text.Split('\n');
int len = lines.Length;
string[] titles = { "Name", "Description", "Plugin Type", "Libraries" };
data.Add(new string[] { "-", "-", "-", "-" });
@@ -41,7 +37,7 @@ namespace PluginManager.Online
if (lines[i].Length <= 2) continue;
string[] content = lines[i].Split(',');
string[] display = new string[4];
if (op == PluginManager.Others.OperatingSystem.WINDOWS)
if (op == Others.OperatingSystem.WINDOWS)
{
if (content[4].Contains("Windows"))
{
@@ -71,7 +67,7 @@ namespace PluginManager.Online
data.Add(new string[] { "-", "-", "-", "-" });
Functions.FormatAndAlignTable(data);
Console_Utilities.FormatAndAlignTable(data);
}
catch (Exception exception)
{
@@ -85,13 +81,8 @@ namespace PluginManager.Online
{
try
{
#pragma warning disable SYSLIB0014
WebClient client = new WebClient();
#pragma warning restore SYSLIB0014
Stream s = await client.OpenReadTaskAsync(PluginsLink);
string text = await new StreamReader(s).ReadToEndAsync();
string[] lines = text.Split('\n');
List<string> list = await ServerCom.ReadTextFromFile(PluginsLink);
string[] lines = list.ToArray();
int len = lines.Length;
for (int i = 0; i < len; i++)
{

View File

@@ -1,4 +1,5 @@
using PluginManager.Items;
using PluginManager.Online.Helpers;
using System;
using System.Collections.Generic;
@@ -14,6 +15,14 @@ namespace PluginManager.Online
{
public static async Task<List<string>> ReadTextFromFile(string link)
{
string response = await OnlineFunctions.DownloadStringAsync(link);
string[] lines = response.Split('\n');
return lines.ToList();
//[Obsolete]
#region old code for reading text from link
/*
List<string> s = new List<string>();
WebClient webClient = new WebClient();
var data = await webClient.OpenReadTaskAsync(link);
@@ -21,12 +30,38 @@ namespace PluginManager.Online
s.AddRange(from a in response.Split('\n')
where !a.StartsWith("$")
select a);
return s;
return s;*/
#endregion
}
public static async Task DownloadFileAsync(string URL, string location, IProgress<float> progress)
{
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(5);
using (var file = new FileStream(location, FileMode.Create, FileAccess.Write, FileShare.None))
{
await client.DownloadFileAsync(URL, file, progress);
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public static async Task DownloadFileAsync(string url, string location, int downloadNumber, int totalToDownload)
{
IProgress<float> progress = new Progress<float>(bytes =>
{
Console.Title = $"Downloading {MathF.Round(bytes, 2)}% ({downloadNumber}/{totalToDownload})";
});
await DownloadFileAsync(url, location, progress);
Console.Title = "ONLINE";
return;
//[Obsolete]
#region old download code
/*
WebClient client = new WebClient();
Spinner spinner = new Spinner();
Console.Write("Downloading ");
@@ -52,8 +87,9 @@ namespace PluginManager.Online
finally
{
Console.Title = oldTitle;
}
}*/
#endregion
}
}
}