Cleaned the code

This commit is contained in:
JacobTech 2024-11-15 00:21:02 -05:00
parent 846fd1b6dc
commit 35dc3f9aa3
2 changed files with 84 additions and 121 deletions

View File

@ -4,7 +4,6 @@ namespace Updater;
public record Argumets public record Argumets
{ {
public string? Updater { get; set; } = null!;
public string Process { get; set; } = default!; public string Process { get; set; } = default!;
private string? l = null; private string? l = null;
@ -22,7 +21,6 @@ public record Argumets
{ {
get get
{ {
if (Updater is not null) return "Updater";
return d; return d;
} }
set set
@ -57,8 +55,7 @@ public record Argumets
{ {
get get
{ {
if (goodarg(Branch) && Updater is null) return $"&branch={Branch}"; if (goodarg(Branch)) return $"&branch={Branch}";
if (Updater is not null) return $"&branch=Master";
return ""; return "";
} }
} }
@ -83,7 +80,6 @@ public record Argumets
remp.Add(val); remp.Add(val);
} }
if (goodarg(Updater)) addarg(nameof(Updater), Updater!);
if (goodarg(Process)) addarg(nameof(Process), Process!); if (goodarg(Process)) addarg(nameof(Process), Process!);
if (goodarg(Branch)) addarg(nameof(Branch), Branch!); if (goodarg(Branch)) addarg(nameof(Branch), Branch!);
if (goodarg(RemoteDirectory)) addarg(nameof(RemoteDirectory), RemoteDirectory!); if (goodarg(RemoteDirectory)) addarg(nameof(RemoteDirectory), RemoteDirectory!);
@ -100,8 +96,7 @@ public record Argumets
return return
(goodarg(Process) && (goodarg(Process) &&
goodarg(RemoteDirectory) && goodarg(RemoteDirectory) &&
goodarg(LocalDirectory)) || goodarg(LocalDirectory));
goodarg(Updater);
} }
private bool goodarg(string? arg) private bool goodarg(string? arg)

View File

@ -2,7 +2,6 @@ using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Net; using System.Net;
using System.Reflection; using System.Reflection;
using System.Text.Json;
using GraphicsManager; using GraphicsManager;
using GraphicsManager.Enums; using GraphicsManager.Enums;
using GraphicsManager.Objects; using GraphicsManager.Objects;
@ -26,8 +25,8 @@ public class NewUpdater : FPSWindow
public NewUpdater(NativeWindowSettings nws, GameWindowSettings gws, Argumets args) public NewUpdater(NativeWindowSettings nws, GameWindowSettings gws, Argumets args)
:base(nws, gws) :base(nws, gws)
{ {
base.ShowMissingChar = false; ShowMissingChar = false;
base.LogFrames = false; LogFrames = false;
Speed = new() Speed = new()
{ {
Interval = 500 Interval = 500
@ -63,7 +62,6 @@ public class NewUpdater : FPSWindow
InnerShader = Rectangle.DefaultAlphaShader[Context] InnerShader = Rectangle.DefaultAlphaShader[Context]
}); });
fi.PixelHeight = (uint)WallDistance; fi.PixelHeight = (uint)WallDistance;
Controls.Add(Total_Downloaded = new(fi) Controls.Add(Total_Downloaded = new(fi)
{ {
@ -107,23 +105,11 @@ public class NewUpdater : FPSWindow
Download.DoWork += Download_DoWork; Download.DoWork += Download_DoWork;
Download.RunWorkerCompleted += Download_RunWorkerCompleted; Download.RunWorkerCompleted += Download_RunWorkerCompleted;
Download.WorkerReportsProgress = true; Download.WorkerReportsProgress = true;
Invoke(new Action(() => { Download.RunWorkerAsync(); })); Invoke(Download.RunWorkerAsync);
Speed.Start(); Speed.Start();
Controls.Add(new Label(fi)
{
Location = new(10,10),
Text = FloatToInt(-0.11304348f, true).ToString() + " / "
+ FloatToInt(-0.133858263f, true).ToString() + " / "
+ FloatToInt(-0.314960629f, true).ToString() + " / "
+ FloatToInt(-0.341389941f, true).ToString() + " / "
+ FloatToInt(-0.5748032f, true).ToString()
});
} }
private ulong last = 0; private ulong last;
private void Speed_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) private void Speed_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{ {
@ -133,19 +119,14 @@ public class NewUpdater : FPSWindow
last = TotalProgress.ProgressValue; last = TotalProgress.ProgressValue;
speeds.Add(BytesPertenthSec * 2); speeds.Add(BytesPertenthSec * 2);
if (speeds.Count > 25) speeds.RemoveAt(0); if (speeds.Count > 25) speeds.RemoveAt(0);
//Debug.WriteLine($"l: {last}");
//Debug.WriteLine($"bps: {BytesPertenthSec}");
if (Transfer_Speed is not null && speeds.Average() != 0) Transfer_Speed.Text = Download_Speed_Neat(speeds.Average()); if (Transfer_Speed is not null && speeds.Average() != 0) Transfer_Speed.Text = Download_Speed_Neat(speeds.Average());
} }
private bool ran = true;
private void Download_DoWork(object? sender, DoWorkEventArgs e) private void Download_DoWork(object? sender, DoWorkEventArgs e)
{ {
try try
{ {
ChangeProcessText("Deleting old program files");
void TryDeleteDir(string? dir) void TryDeleteDir(string? dir)
{ {
if (string.IsNullOrEmpty(dir) || string.IsNullOrWhiteSpace(dir)) return; if (string.IsNullOrEmpty(dir) || string.IsNullOrWhiteSpace(dir)) return;
@ -162,7 +143,10 @@ public class NewUpdater : FPSWindow
{ {
file.Delete(); file.Delete();
} }
catch { } catch
{
// ignored
}
} }
foreach (var subdir in dirInfo.GetDirectories()) foreach (var subdir in dirInfo.GetDirectories())
{ {
@ -172,64 +156,43 @@ public class NewUpdater : FPSWindow
} }
TryDeleteDir(Argumets.LocalDirectory); TryDeleteDir(Argumets.LocalDirectory);
Directory.CreateDirectory(Argumets.LocalDirectory); Directory.CreateDirectory(Argumets.LocalDirectory);
if (Argumets.Updater is not null) TryDeleteDir(Argumets.Updater);
if (Argumets.Updater is not null) Directory.CreateDirectory(Argumets.Updater);
#pragma warning disable SYSLIB0014 // Type or member is obsolete
using WebClient webPre = new();
#pragma warning restore SYSLIB0014 // Type or member is obsolete
ChangeProcessText("Getting update info");
string pp =
$"https://{Handler.Domain}/Updater/Files?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}";
string rem = webPre.DownloadString($"https://{Handler.Domain}/Updater/Files?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}");
//string uri;
try try
{ {
ulong realmax = ulong.Parse(webPre.DownloadString($"https://{Handler.Domain}/Updater/GetSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}")); HttpClient client = new();
TotalProgress.MaxProgressValue = realmax;
Console.WriteLine(TotalProgress.MaxProgressValue);
string[] files = rem.Split('\n');
int c = -1;
Tuple<ProgressBar<ulong>, Label, int> getpb() Task<string> files_pre = client.GetStringAsync($"https://{Handler.Domain}/Updater/Files?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}");
Task<string> max_pre = client.GetStringAsync(
$"https://{Handler.Domain}/Updater/GetSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}");
max_pre.Wait();
TotalProgress.MaxProgressValue = ulong.Parse(max_pre.Result);
files_pre.Wait();
string[] files = files_pre.Result.Split('\n');
Queue<int> IndexesWaiting = new();
for (int i = 0; i < cf.Format.DownloadThreads; i++)
{ {
c++; IndexesWaiting.Enqueue(i);
if (c == ProgressThreads.Count) c = 0;
return ProgressThreads[c];
} }
_ = Parallel.ForEach(files, new ParallelOptions() {MaxDegreeOfParallelism = cf.Format.DownloadThreads},file => _ = Parallel.ForEach(files, new ParallelOptions() { MaxDegreeOfParallelism = cf.Format.DownloadThreads },
file =>
{ {
#pragma warning disable SYSLIB0014 // Type or member is obsolete try
using WebClient web = new();
#pragma warning restore SYSLIB0014 // Type or member is obsolete
if (string.IsNullOrEmpty(file)) return;
string uri = $"https://{Handler.Domain}/Updater/GetFileSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriVersion}{Argumets.UriSeflContaind}{Argumets.UriPlatform}&file={file}";
Uri u = new($"https://{Handler.Domain}/Updater/GetFile?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriVersion}{Argumets.UriSeflContaind}{Argumets.UriPlatform}&file={file}");
string[] temp = file.Split('/');
if (file.Contains('/'))
{ {
int v;
string cur = ""; lock (IndexesWaiting)
for (int i = 0; i < temp.Length - 1; i++)
{ {
cur += temp[i] + "/"; v = IndexesWaiting.Dequeue();
if (Argumets.Updater is null)
{
if (!Directory.Exists(Argumets.LocalDirectory + cur))
Directory.CreateDirectory(Argumets.LocalDirectory + cur);
} }
else Tuple<ProgressBar<ulong>, Label, int> pb = ProgressThreads[v];
StartDownloadForFile(file, pb.Item1, pb.Item2).Wait();
IndexesWaiting.Enqueue(v);
}
catch (Exception exception)
{ {
if (!Directory.Exists(Argumets.Updater + cur)) Console.WriteLine(exception);
Directory.CreateDirectory(Argumets.Updater + cur);
} }
} }
} );
DownloadFile(getpb(), web, uri, u, temp, file.Replace("/", Handler.Slash)).Wait();
});
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -249,54 +212,65 @@ public class NewUpdater : FPSWindow
} }
} }
private async Task StartDownloadForFile(string file, ProgressBar<ulong> pb, Label pbLabel)
private Task DownloadFile(Tuple<ProgressBar<ulong>, Label, int> pb, WebClient web, string uri, Uri u, string[] temp, string file)
{ {
while (!web.IsBusy) if (string.IsNullOrWhiteSpace(file)) return;
string[] temp = file.Split('/');
if (file.Contains('/'))
{ {
string cur = "";
string a = web.DownloadString(uri); for (int i = 0; i < temp.Length - 1; i++)
pb.Item1.MaxProgressValue = ulong.Parse(a);
pb.Item1.ProgressValue = 0;
web.DownloadProgressChanged += (sender, args) =>
{ {
ulong tmp = (ulong)args.BytesReceived - pb.Item1.ProgressValue; cur = Path.Join(cur, temp[i]);
TotalProgress.ProgressValue += tmp; if (!Directory.Exists(Path.Join(Argumets.LocalDirectory, cur)))
Directory.CreateDirectory(Path.Join(Argumets.LocalDirectory, cur));
pb.Item1.ProgressValue = (ulong)args.BytesReceived; }
if (ran) }
{ using HttpClient client = new();
ran = false; string max = await client.GetStringAsync($"https://{Handler.Domain}/Updater/GetFileSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriVersion}{Argumets.UriSeflContaind}{Argumets.UriPlatform}&file={file}");
Invoke(() => Invoke(() =>
{ {
Total_Downloaded!.Text = pb.ProgressValue = 0;
$"Downloaded {TotalDownloadAmountNeat(TotalProgress.ProgressValue)}"; pb.MaxProgressValue = ulong.Parse(max);
ran = true;
});
}
};
string s = $"Downloading {temp[^1]}"; string s = $"Downloading {temp[^1]}";
ChangeProcessText(s);
try try
{ {
pb.Item2.Text = s; pbLabel.Text = s;
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e); Console.WriteLine(e);
} }
if (Argumets.Updater is null) });
{ await DownloadFileAsync(pb,
web.DownloadFileTaskAsync(u, Path.Combine(Argumets.LocalDirectory, file)).Wait(); $"https://{Handler.Domain}/Updater/GetFile?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriVersion}{Argumets.UriSeflContaind}{Argumets.UriPlatform}&file={file}",
} file.Replace("/", Handler.Slash));
else
{
web.DownloadFileTaskAsync(u, Path.Combine(Argumets.Updater, file)).Wait();
} }
return Task.CompletedTask; private async Task DownloadFileAsync(ProgressBar<ulong> progressBar, string url, string destinationPath)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
using (var contentStream = await response.Content.ReadAsStreamAsync())
using (var fileStream = new FileStream(Path.Join(Argumets.LocalDirectory, destinationPath), FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
var buffer = new byte[8192];
long totalRead = 0;
int bytesRead;
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fileStream.WriteAsync(buffer, 0, bytesRead);
totalRead += bytesRead;
TotalProgress.ProgressValue += (ulong)bytesRead;
progressBar.ProgressValue = (ulong)totalRead;
}
}
} }
return Task.CompletedTask;
} }
private void Download_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e) private void Download_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
@ -311,12 +285,6 @@ public class NewUpdater : FPSWindow
} }
} }
private void ChangeProcessText(string Process)
{
Console.WriteLine(Process);
//queue.Enqueue(new Action(() => { if (Current_Process is not null) Current_Process.Text = $"{Process}"; }));
}
#region Neat #region Neat
private string Download_Speed_Neat(double Number) private string Download_Speed_Neat(double Number)
{ {