pre atomic total

This commit is contained in:
JacobTech 2024-11-14 11:57:44 -05:00
parent a4955ef20a
commit 2764601d1a
7 changed files with 200 additions and 494 deletions

View File

@ -7,7 +7,7 @@ public class Config
{ {
public static ConfigFile MakeFile() public static ConfigFile MakeFile()
{ {
if (!File.Exists(Program.JT + "/Updater/Config/Settings.json")) if (!File.Exists(Handler.JT + "/Updater/Config/Settings.json"))
{ {
ConfigFile file = new(); ConfigFile file = new();
file.Format = new Format() file.Format = new Format()
@ -51,10 +51,10 @@ public class Config
A = 1f A = 1f
} }
}; };
if (!Directory.Exists(Program.JT)) Directory.CreateDirectory(Program.JT); if (!Directory.Exists(Handler.JT)) Directory.CreateDirectory(Handler.JT);
if (!Directory.Exists(Program.JT + "/Updater")) Directory.CreateDirectory(Program.JT + "/Updater" ); if (!Directory.Exists(Handler.JT + "/Updater")) Directory.CreateDirectory(Handler.JT + "/Updater" );
if (!Directory.Exists(Program.JT + "/Updater/Config")) Directory.CreateDirectory(Program.JT + "/Updater/Config"); if (!Directory.Exists(Handler.JT + "/Updater/Config")) Directory.CreateDirectory(Handler.JT + "/Updater/Config");
FileStream ms = new(Program.JT + "/Updater/Config/Settings.json", FileMode.Create); FileStream ms = new(Handler.JT + "/Updater/Config/Settings.json", FileMode.Create);
JsonSerializer.Serialize(new Utf8JsonWriter(ms), JsonSerializer.Serialize(new Utf8JsonWriter(ms),
file, file,
ConfigFileContext.Default.ConfigFile); ConfigFileContext.Default.ConfigFile);
@ -69,7 +69,7 @@ public class Config
public static string GetFile() public static string GetFile()
{ {
_ = MakeFile(); _ = MakeFile();
return File.ReadAllText(Program.JT + "/Updater/Config/Settings.json"); return File.ReadAllText(Handler.JT + "/Updater/Config/Settings.json");
} }
public static ConfigFile GetConfig() public static ConfigFile GetConfig()
@ -79,14 +79,14 @@ public class Config
ConfigFile? temp = JsonSerializer.Deserialize(GetFile(), ConfigFileContext.Default.ConfigFile); ConfigFile? temp = JsonSerializer.Deserialize(GetFile(), ConfigFileContext.Default.ConfigFile);
if (temp is null) if (temp is null)
{ {
File.Delete(Program.JT + "/Updater/Config/Settings.json"); File.Delete(Handler.JT + "/Updater/Config/Settings.json");
temp = MakeFile(); temp = MakeFile();
} }
int max = Environment.ProcessorCount * 2; int max = Environment.ProcessorCount * 2;
if (temp.Format.DownloadThreads > max) if (temp.Format.DownloadThreads > max)
{ {
temp.Format.DownloadThreads = max; temp.Format.DownloadThreads = max;
FileStream ms = new(Program.JT + "/Updater/Config/Settings.json", FileMode.Create); FileStream ms = new(Handler.JT + "/Updater/Config/Settings.json", FileMode.Create);
JsonSerializer.Serialize(new Utf8JsonWriter(ms), JsonSerializer.Serialize(new Utf8JsonWriter(ms),
temp, temp,
ConfigFileContext.Default.ConfigFile); ConfigFileContext.Default.ConfigFile);
@ -94,7 +94,7 @@ public class Config
if (temp.Format.DownloadThreads < 1) if (temp.Format.DownloadThreads < 1)
{ {
temp.Format.DownloadThreads = 1; temp.Format.DownloadThreads = 1;
FileStream ms = new(Program.JT + "/Updater/Config/Settings.json", FileMode.Create); FileStream ms = new(Handler.JT + "/Updater/Config/Settings.json", FileMode.Create);
JsonSerializer.Serialize(new Utf8JsonWriter(ms), JsonSerializer.Serialize(new Utf8JsonWriter(ms),
temp, temp,
ConfigFileContext.Default.ConfigFile); ConfigFileContext.Default.ConfigFile);
@ -103,7 +103,7 @@ public class Config
} }
catch catch
{ {
File.Delete(Program.JT + "/Updater/Config/Settings.json"); File.Delete(Handler.JT + "/Updater/Config/Settings.json");
return MakeFile(); return MakeFile();
} }
} }

130
Updater/Handler.cs Normal file
View File

@ -0,0 +1,130 @@
using System.Diagnostics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Common.Input;
using OpenTK.Windowing.Desktop;
namespace Updater;
public static class Handler
{
public static string JT
{
get
{
string tmp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "JacobTech");
if (OperatingSystem.IsLinux())
{
tmp = Path.Combine(Environment.GetEnvironmentVariable("HOME")!, ".config/");
tmp += "JacobTech";
}
return tmp;
}
}
public static string Slash
{
get
{
if (OperatingSystem.IsWindows()) return "\\";
else return "/";
}
}
public const string Domain = "www.JacobTech.com";
internal static Argumets Argumets { get; } = new();
internal static readonly NativeWindowSettings Settings = new()
{
Title = "Updater",
WindowBorder = WindowBorder.Fixed,
APIVersion = new Version(3, 2),
StartFocused = true,
Size = new(694, 105)
};
internal static readonly GameWindowSettings GameWindowSettings = new()
{
UpdateFrequency = 30
};
public const string UpdateArg = "--StartUpdate",
PostUpdateArg = "--PostUpdate";
public static void PreUpdate(string app)
{
string p = Path.Join(Path.GetTempPath(), Path.GetRandomFileName());
if (!Directory.Exists(p)) Directory.CreateDirectory(p);
void CoppyDir(string path, string dir)
{
DirectoryInfo DI = new(path);
foreach (FileInfo file in DI.GetFiles())
{
file.CopyTo(Path.Join(dir, file.Name), true);
}
foreach (DirectoryInfo file in DI.GetDirectories())
{
Directory.CreateDirectory(Path.Join(dir, file.Name));
CoppyDir(file.FullName, Path.Join(dir, file.Name));
}
}
CoppyDir(Directory.GetCurrentDirectory(), p);
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
{
Process m = Process.Start("/usr/bin/chmod", $"+x \"{Path.Combine(p, app)}\"");
m.WaitForExit();
}
Process pp = new Process()
{
StartInfo = new()
{
FileName = Path.Join(p, app),
WorkingDirectory = p,
Arguments = UpdateArg + $" '{Directory.GetCurrentDirectory()}'"
}
};
pp.Start();
pp.WaitForExit();
}
public static void StartUpdate(WindowIcon Icon, string App, string RemoteDirectory, string LocalDirectory, string ConfigPath, string Platform, string Branch = "main", bool SelfContained = false, string? ProgramVersion = null)
{
Argumets.Loc = ConfigPath;
Argumets.RemoteDirectory = RemoteDirectory;
Argumets.LocalDirectory = LocalDirectory;
Argumets.DLL = App;
Argumets.Branch = Branch;
Argumets.Version = ProgramVersion;
Argumets.SeflContaind = SelfContained;
Argumets.Platform = Platform;
//Settings.Icon = Icon;
NewUpdater NU = new(Settings, GameWindowSettings, Argumets);
NU.Run();
NU.Close();
NU.Dispose();
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
{
Process m = Process.Start("/usr/bin/chmod", $"+x \"{Path.Combine(Argumets.LocalDirectory, Argumets.DLL)}\"");
m.WaitForExit();
}
Process.Start(new ProcessStartInfo()
{
FileName = Path.Combine(Argumets.LocalDirectory, Argumets.DLL),
Arguments = PostUpdateArg + $" '{Directory.GetCurrentDirectory()}'",
WorkingDirectory = Argumets.LocalDirectory,
CreateNoWindow = true,
UseShellExecute = true,
})!.WaitForExit();
}
public static void PostUpdate(string LocalDirectory)
{
if (Directory.Exists(LocalDirectory)) Directory.Delete(LocalDirectory, true);
}
}

View File

@ -15,9 +15,9 @@ namespace Updater;
public class NewUpdater : FPSWindow public class NewUpdater : FPSWindow
{ {
private readonly ConfigFile cf; private readonly ConfigFile cf;
private ProgressBar TotalProgress; private ProgressBar<ulong> TotalProgress;
private Argumets Argumets; private Argumets Argumets;
private List<Tuple<ProgressBar, Label>> ProgressThreads = new(); private List<Tuple<ProgressBar<ulong>, Label, int>> ProgressThreads = new();
private readonly BackgroundWorker Download = new(); private readonly BackgroundWorker Download = new();
private Label? Total_Downloaded, Transfer_Speed; private Label? Total_Downloaded, Transfer_Speed;
private readonly System.Timers.Timer Speed; private readonly System.Timers.Timer Speed;
@ -26,6 +26,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;
base.LogFrames = false;
Speed = new() Speed = new()
{ {
Interval = 500 Interval = 500
@ -37,25 +39,24 @@ public class NewUpdater : FPSWindow
//small = (uint)Math.Round(0.078740157480315 * StartGUI.Height, 0); //small = (uint)Math.Round(0.078740157480315 * StartGUI.Height, 0);
//RenderObjects.Add(Transfer_Speed = new RenderText("Download Speed", "OpenSans-Regular", small, -0.9381188f, -0.05263158f, 1.2f, new Vector2(1f, 0f), new Vector4(cf.Colors.Text.R, cf.Colors.Text.G, cf.Colors.Text.B, cf.Colors.Text.A))); //RenderObjects.Add(Transfer_Speed = new RenderText("Download Speed", "OpenSans-Regular", small, -0.9381188f, -0.05263158f, 1.2f, new Vector2(1f, 0f), new Vector4(cf.Colors.Text.R, cf.Colors.Text.G, cf.Colors.Text.B, cf.Colors.Text.A)));
FontFamily r = FontFamily.LoadFontFamily(Tools.GetResourceStream(Assembly.GetExecutingAssembly(), "Updater.Resource.OpenSans.zip"), "OpenSans").Result; FontFamily r = FontFamily.LoadFontFamily(Tools.GetResourceStream(Assembly.GetExecutingAssembly(), "Updater.Resource.OpenSans.zip"), "OpenSans");
FontInteraction fi = FontInteraction.Load(r); FontInteraction fi = FontInteraction.Load(r);
cf = Config.GetConfig(); cf = Config.GetConfig();
Size = new(cf.Scale(Size.X), cf.Scale(Size.Y)); Size = new(cf.Scale(Size.X), cf.Scale(Size.Y));
Argumets = args; Argumets = args;
int WallDistance = cf.Scale(15); int WallDistance = cf.Scale(15);
BackgroundColor = cf.Colors.Background.ToColor4(); BackgroundColor = cf.Colors.Background.ToColor4();
Texture ProgressbarTexture = TextureManager.AddTexture(File.OpenRead("/home/jacob/Pictures/Progress.png")); Texture ProgressbarTexture = TextureManager.AddTexture(File.OpenRead("/home/jacob/Pictures/Progress.png"));
Controls.Add(TotalProgress = new ProgressBar(ProgressbarTexture) Controls.Add(TotalProgress = new(ProgressbarTexture)
{ {
Location = new(WallDistance, cf.Scale(70), 0), Location = new(WallDistance, cf.Scale(70)),
Size = new(Size.X - WallDistance - WallDistance, cf.Scale(20)), Size = new(Size.X - WallDistance - WallDistance, cf.Scale(20)),
BackgroundColor = cf.Colors.Progress_bars.Backcolor.ToColor4(), BackgroundColor = cf.Colors.Progress_bars.Backcolor.ToColor4(),
ProgressColor = cf.Colors.Progress_bars.Fillcolor.ToColor4(), ProgressColor = cf.Colors.Progress_bars.Fillcolor.ToColor4(),
ProgressValue = 5, ProgressValue = 5,
ProgressGap = (uint)cf.Scale(3), ProgressGap = new(cf.Scale(3)),
Shader = Rectangle.DefaultAlphaShader[Context], Shader = Rectangle.DefaultAlphaShader[Context],
TextureDisplay = TextureDisplay.ProgressHorizontalCenter, TextureDisplay = TextureDisplay.ProgressHorizontalCenter,
UpdateOnDraw = true, UpdateOnDraw = true,
@ -67,28 +68,28 @@ public class NewUpdater : FPSWindow
Controls.Add(Total_Downloaded = new(fi) Controls.Add(Total_Downloaded = new(fi)
{ {
Text = "D", Text = "D",
Location = new((int)FloatToInt(-0.9381188f), (int)FloatToInt(0.149797574f + 0.14f, true), 0) Location = new((int)FloatToInt(-0.9381188f), (int)FloatToInt(0.149797574f + 0.14f, true))
}); });
Controls.Add(Transfer_Speed = new(fi) Controls.Add(Transfer_Speed = new(fi)
{ {
Text = "abcdefghijklmnopqrstuvwxyz", Text = "abcdefghijklmnopqrstuvwxyz",
Location = new(Total_Downloaded.Location.X, (int)FloatToInt(-0.05263158f + 0.09f, true), 0) Location = new(Total_Downloaded.Location.X, (int)FloatToInt(-0.05263158f + 0.09f, true))
}); });
int gap = cf.Scale(10); int gap = cf.Scale(10);
for (int i = 0; i < cf.Format.DownloadThreads; i++) for (int i = 0; i < cf.Format.DownloadThreads; i++)
{ {
ProgressBar temp; ProgressBar<ulong> temp;
Size = new(Size.X, Size.Y + gap + TotalProgress.Size.Y); Size = new(Size.X, Size.Y + gap + TotalProgress.Size.Y);
Label l = new(fi) Label l = new(fi)
{ {
Color = Color4.Black, Color = Color4.Black,
Text = "Downloading ...." Text = "Downloading ...."
}; };
l.Location = new(cf.Scale(5), (int)(((TotalProgress.Size.Y - l.TrueHeight) / 2) - fi.PixelHeight + l.PostiveTrueHeight), 0); l.Location = new(cf.Scale(5), (TotalProgress.Size.Y - l.Size.Y) / 2);
Controls.Add(temp = new ProgressBar(ProgressbarTexture) Controls.Add(temp = new(ProgressbarTexture)
{ {
Location = new(WallDistance, cf.Scale(70) + (TotalProgress.Size.Y * (i + 1)) + (gap * (i + 1)), 0), Location = new(WallDistance, cf.Scale(70) + (TotalProgress.Size.Y * (i + 1)) + (gap * (i + 1))),
Size = TotalProgress.Size, Size = TotalProgress.Size,
BackgroundColor = TotalProgress.BackgroundColor, BackgroundColor = TotalProgress.BackgroundColor,
ProgressColor = TotalProgress.ProgressColor, ProgressColor = TotalProgress.ProgressColor,
@ -100,7 +101,7 @@ public class NewUpdater : FPSWindow
InnerShader = TotalProgress.InnerShader InnerShader = TotalProgress.InnerShader
}); });
temp.Controls.Add(l); temp.Controls.Add(l);
ProgressThreads.Add(new(temp,l)); ProgressThreads.Add(new(temp,l, i));
} }
Download.DoWork += Download_DoWork; Download.DoWork += Download_DoWork;
@ -110,9 +111,10 @@ public class NewUpdater : FPSWindow
Speed.Start(); Speed.Start();
Controls.Add(new Label(fi) Controls.Add(new Label(fi)
{ {
Location = new(10,10,0), Location = new(10,10),
Text = FloatToInt(-0.11304348f, true).ToString() + " / " Text = FloatToInt(-0.11304348f, true).ToString() + " / "
+ FloatToInt(-0.133858263f, true).ToString() + " / " + FloatToInt(-0.133858263f, true).ToString() + " / "
+ FloatToInt(-0.314960629f, true).ToString() + " / " + FloatToInt(-0.314960629f, true).ToString() + " / "
@ -122,6 +124,7 @@ public class NewUpdater : FPSWindow
} }
private ulong last = 0; private ulong last = 0;
Queue<ulong> ProgressQuee = new();
private void Speed_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) private void Speed_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{ {
@ -131,8 +134,13 @@ 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($"l: {last}");
Debug.WriteLine($"bps: {BytesPertenthSec}"); //Debug.WriteLine($"bps: {BytesPertenthSec}");
for (int i = 0; i < ProgressQuee.Count; i++)
{
Console.WriteLine(TotalProgress.ProgressValue);
TotalProgress.ProgressValue += ProgressQuee.Dequeue();
}
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());
} }
@ -142,15 +150,6 @@ public class NewUpdater : FPSWindow
{ {
try try
{ {
bool goodpre = true;
while (goodpre)
{
while (!Program.IsProcessOpen(Argumets.Process))
{
goodpre = false;
break;
}
}
ChangeProcessText("Deleting old program files"); ChangeProcessText("Deleting old program files");
void TryDeleteDir(string? dir) void TryDeleteDir(string? dir)
@ -186,17 +185,19 @@ public class NewUpdater : FPSWindow
using WebClient webPre = new(); using WebClient webPre = new();
#pragma warning restore SYSLIB0014 // Type or member is obsolete #pragma warning restore SYSLIB0014 // Type or member is obsolete
ChangeProcessText("Getting update info"); ChangeProcessText("Getting update info");
string rem = webPre.DownloadString($"https://{Program.Domain}/Updater/Files?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}"); 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; //string uri;
try try
{ {
ulong realmax = ulong.Parse(webPre.DownloadString($"https://{Program.Domain}/Updater/GetSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}")); ulong realmax = ulong.Parse(webPre.DownloadString($"https://{Handler.Domain}/Updater/GetSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriSeflContaind}{Argumets.UriPlatform}{Argumets.UriVersion}"));
TotalProgress.MaxProgressValue = realmax; TotalProgress.MaxProgressValue = realmax;
Console.WriteLine(TotalProgress.MaxProgressValue); Console.WriteLine(TotalProgress.MaxProgressValue);
string[] files = rem.Split('\n'); string[] files = rem.Split('\n');
int c = -1; int c = -1;
Tuple<ProgressBar, Label> getpb() Tuple<ProgressBar<ulong>, Label, int> getpb()
{ {
c++; c++;
if (c == ProgressThreads.Count) c = 0; if (c == ProgressThreads.Count) c = 0;
@ -209,8 +210,8 @@ public class NewUpdater : FPSWindow
#pragma warning restore SYSLIB0014 // Type or member is obsolete #pragma warning restore SYSLIB0014 // Type or member is obsolete
if (string.IsNullOrEmpty(file)) return; if (string.IsNullOrEmpty(file)) return;
string uri = $"https://{Program.Domain}/Updater/GetFileSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriVersion}{Argumets.UriSeflContaind}{Argumets.UriPlatform}&file={file}"; string uri = $"https://{Handler.Domain}/Updater/GetFileSize?directory={Argumets.RemoteDirectory}{Argumets.UriBranch}{Argumets.UriVersion}{Argumets.UriSeflContaind}{Argumets.UriPlatform}&file={file}";
Uri u = new($"https://{Program.Domain}/Updater/GetFile?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('/'); string[] temp = file.Split('/');
if (file.Contains('/')) if (file.Contains('/'))
{ {
@ -233,7 +234,7 @@ public class NewUpdater : FPSWindow
} }
DownloadFile(getpb(), web, uri, u, temp, file.Replace("/", Program.Slash)).Wait(); DownloadFile(getpb(), web, uri, u, temp, file.Replace("/", Handler.Slash)).Wait();
}); });
} }
catch (Exception ex) catch (Exception ex)
@ -244,7 +245,7 @@ public class NewUpdater : FPSWindow
int line = frame.GetFileLineNumber(); int line = frame.GetFileLineNumber();
string msg = $"Error in Updater.exe in function Download_DoWork on line '{line}' through error '{ex.Message}'\nERROR:\n'{ex}' FRAM:\n '{frame}'"; string msg = $"Error in Updater.exe in function Download_DoWork on line '{line}' through error '{ex.Message}'\nERROR:\n'{ex}' FRAM:\n '{frame}'";
MessageBox.Show(ex.ToString()); MessageBox.Show(ex.ToString());
_ = new HttpClient().PostAsync($"https://{Program.Domain}/Updater/Error/updater", new StringContent(msg)); _ = new HttpClient().PostAsync($"https://{Handler.Domain}/Updater/Error/updater", new StringContent(msg));
} }
} }
catch (Exception exception) catch (Exception exception)
@ -254,27 +255,31 @@ public class NewUpdater : FPSWindow
} }
} }
private Task DownloadFile(Tuple<ProgressBar, Label> pb, WebClient web, string uri, Uri u, string[] temp, string file) private readonly string m_Locker = "THREAD_LOCKER";
private Task DownloadFile(Tuple<ProgressBar<ulong>, Label, int> pb, WebClient web, string uri, Uri u, string[] temp, string file)
{ {
while (!web.IsBusy) while (!web.IsBusy)
{ {
string a = web.DownloadString(uri); string a = web.DownloadString(uri);
//Invoke(new Action(() =>pb.MaxProgressValue = ulong.Parse(a)));
pb.Item1.MaxProgressValue = ulong.Parse(a); pb.Item1.MaxProgressValue = ulong.Parse(a);
pb.Item1.ProgressValue = 0; pb.Item1.ProgressValue = 0;
//ulong byres = 0;
web.DownloadProgressChanged += (sender, args) => web.DownloadProgressChanged += (sender, args) =>
{ {
TotalProgress.ProgressValue += (ulong)args.BytesReceived - pb.Item1.ProgressValue; ulong tmp = (ulong)args.BytesReceived - pb.Item1.ProgressValue;
ProgressQuee.Enqueue(tmp);
pb.Item1.ProgressValue = (ulong)args.BytesReceived; pb.Item1.ProgressValue = (ulong)args.BytesReceived;
if (ran) if (ran)
{ {
ran = false; ran = false;
Invoke( () => Invoke( () =>
{ {
// Total_Downloaded!.Text = Total_Downloaded!.Text =
// $"Downloaded {TotalDownloadAmountNeat(TotalProgress.ProgressValue)}"; $"Downloaded {TotalDownloadAmountNeat(TotalProgress.ProgressValue)}";
ran = true; ran = true;
}); });
} }
@ -307,7 +312,6 @@ public class NewUpdater : FPSWindow
{ {
try try
{ {
StartGUI.close = true;
Close(); Close();
} }
catch (Exception exception) catch (Exception exception)

View File

@ -1,236 +1,20 @@
using System.Diagnostics; namespace Updater;
using System.Reflection;
namespace Updater;
public class Program public class Program
{ {
public static string Slash
{
get
{
if (OperatingSystem.IsWindows()) return "\\";
else return "/";
}
}
public static string JT
{
get
{
string tmp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "JacobTech");
if (OperatingSystem.IsLinux())
{
tmp = Path.Combine(Environment.GetEnvironmentVariable("HOME")!, ".config/");
tmp += "JacobTech";
}
return tmp;
}
}
public static string[] rawargs;
public static bool NewUpdater = false;
private static string? del = null;
public const string Domain = "www.JacobTech.com";
internal static Argumets Argumets { get; } = new();
[STAThread] [STAThread]
public static int Main(string[] args) public static int Main(string[] args)
{ {
try try
{ {
#if DEBUG Handler.StartUpdate(null!, "Luski", "Luski", "/home/jacob/Documents/test",
args = new string[] { "--process", "vyukgykgyh", "--remotedirectory", "Luski", "--localdirectory", $"/home/jacob/Documents/Updater/Updater/bin/Release/ttt", "--dll", "Luski", "--selfcontained", "false", "--branch", "Dev", "--platform", "linux-x64" }; "/home/jacob/Documents/test/cfg.json", "linux-x64");
string bbbbbb = $"\"{string.Join("\" \"", args)}\"";
#endif
rawargs = args;
int skip = 0;
if (args.Length > 2)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("--"))
{
if (((args.Length - 1) >= (i + 1)))
{
switch (args[i].Remove(0, 2).ToLower())
{
case "updater":
skip++;
NewUpdater = true;
Argumets.Updater = args[i + 1];
break;
case "setconfig":
skip++;
Argumets.Loc = args[i + 1];
break;
case "process":
skip++;
Argumets.Process = args[i + 1];
break;
case "remotedirectory":
skip++;
Argumets.RemoteDirectory = args[i + 1];
break;
case "branch":
skip++;
Argumets.Branch = args[i + 1];
break;
case "localdirectory":
skip++;
Argumets.LocalDirectory = args[i + 1];
break;
case "dll":
skip++;
Argumets.DLL = args[i + 1];
break;
case "version":
skip++;
Argumets.Version = args[i + 1];
break;
case "selfcontained":
skip++;
Argumets.SeflContaind = bool.Parse(args[i + 1]);
break;
case "platform":
skip++;
Argumets.Platform = args[i + 1];
break;
}
i++;
}
else
{
Console.WriteLine($"Argument {args[i].Remove(0, 2)} had no value");
return 1;
}
}
}
if (!Argumets.Verify())
{
Console.WriteLine("Not enough arguments were given");
return 1;
}
skip *= 2;
Argumets.args = args.Skip(skip).ToList();
if (FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion != new HttpClient().GetAsync($"https://www.jacobtech.com/Updater/GetProgramVersion?directory=Updater{Argumets.UriPlatform}{Argumets.UriSeflContaind}").Result.Content.ReadAsStringAsync().Result)
{
//todo this is broken
if (Argumets.Updater is not null)
{
StartGUI.Main(Argumets);
}
string newdir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
void MoveDir(string Base, string Move)
{
if (!Directory.Exists(Move)) Directory.CreateDirectory(Move);
DirectoryInfo di = new(Base);
foreach (FileInfo file in di.GetFiles())
{
file.CopyTo(Path.Combine(Move, file.Name));
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
MoveDir(dir.FullName, Path.Combine(Move, dir.Name));
Directory.Delete(dir.FullName);
}
}
MoveDir(AppDomain.CurrentDomain.BaseDirectory, newdir);
Process p = new();
p.StartInfo.FileName = Path.Combine(newdir, AppDomain.CurrentDomain.FriendlyName);
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
{
Process m = Process.Start("/usr/bin/chmod", $"+x {Path.Combine(newdir, AppDomain.CurrentDomain.FriendlyName)}");
m.WaitForExit();
}
p.StartInfo.WorkingDirectory = newdir;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = $" --updater \"{AppDomain.CurrentDomain.BaseDirectory}\" \"{string.Join("\" \"", args)}\"";
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.Start();
return 0; return 0;
} }
if (Argumets.Updater is not null)
{
Directory.Delete(Argumets.Updater, true);
Argumets.Updater = null;
}
if (!Directory.Exists(JT)) Directory.CreateDirectory(JT);
if (!Directory.Exists(Path.Combine(JT + "Updater"))) Directory.CreateDirectory(Path.Combine(JT + "Updater"));
if (!Directory.Exists(Path.Combine(JT + $"Updater{Program.Slash}Config"))) Directory.CreateDirectory(Path.Combine(JT + $"Updater{Program.Slash}Config"));
_ = Config.MakeFile();
//return 0;
return StartGUI.Main(Argumets);
}
else
{
_ = MessageBox.Show("Not nough arguments were given");
Console.WriteLine("Not nough arguments were given");
return 1;
}
}
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e); Console.WriteLine(e);
return 1; return 1;
} }
} }
public static bool IsProcessOpen(string name)
{
if (!NewUpdater)
{
bool @out = false;
foreach (Process clsProcess in Process.GetProcessesByName(name.ToLower()))
{
if (clsProcess.ProcessName.ToLower().Contains(name.ToLower()))
{
@out = true;
}
}
return @out;
}
else
{
if (!IsUpdaterProcessOpen())
{
if (del != null)
{
try
{
if (Directory.Exists(del)) Directory.Delete(del, true);
del = null;
}
catch
{
}
}
bool @out = false;
foreach (Process clsProcess in Process.GetProcessesByName(name.ToLower()))
{
if (clsProcess.ProcessName.ToLower().Contains(name.ToLower()))
{
@out = true;
}
}
return @out;
}
else
{
return false;
}
}
}
public static bool IsUpdaterProcessOpen()
{
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length <= 1)
{
return false;
}
return true;
}
} }

View File

@ -1,168 +0,0 @@
#if true
using System.Diagnostics;
using OpenTK.Mathematics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Common.Input;
using OpenTK.Windowing.Desktop;
using SixLabors.ImageSharp.PixelFormats;
using System.Reflection;
using System.Text.Json;
using GraphicsManager;
using SixLabors.ImageSharp;
using Image = OpenTK.Windowing.Common.Input.Image;
namespace Updater;
public class StartGUI
{
//internal static int Width = 694;
//internal static int Height = 216;
public static SixLabors.ImageSharp.Image<Rgba32>? Logo { get; private set; }
static readonly NativeWindowSettings Settings = new()
{
Title = "Updater",
WindowBorder = WindowBorder.Fixed,
APIVersion = new Version(3, 2),
StartFocused = true,
Size = new(694, 105)
};
private static readonly GameWindowSettings GameWindowSettings = new()
{
RenderFrequency = 24,
UpdateFrequency = 30
};
internal static NewUpdater? Up;
public static bool close = false;
/// <summary>
/// <para>args[0] = Process</para>
/// <para>args[1] = Remote Program dir</para>
/// <para>args[2] = Remote Program Branch</para>
/// <para>args[3] = Local Program Dir</para>
/// <para>args[4] = exe file</para>
/// </summary>
/// <param name="args"></param>
internal static int Main(Argumets args)
{
/*
var mmm = Monitors.GetMonitors();
if (mmm is not null && mmm.Any())
{
var mi = mmm.First();
int tempw = (int)Math.Round(mi.HorizontalResolution * 0.2127604166666667);
int temph = (int)Math.Round(mi.VerticalResolution * 0.1175925925925926);
if (tempw < Width) tempw = Width;
Width = tempw;
if (temph < Height) temph = Height;
Height = temph - 30;
// Settings.CurrentMonitor = mi.Handle;
}
//Settings.Size = new Vector2i(Width, Height);
*/
Image<Rgba32> Logo = SixLabors.ImageSharp.Image.Load<Rgba32>(Tools.GetResourceStream(Assembly.GetExecutingAssembly(), "Updater.Resource.Logo.png"));
Logo.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> mm);
byte[] pixels = new byte[4 * Logo.Width * Logo.Height];
Logo.CopyPixelDataTo(pixels);
Settings.Icon = new WindowIcon(new Image(Logo.Width, Logo.Height, pixels));
(Up = new NewUpdater(Settings, GameWindowSettings, args)).Run();
Up.Close();
Up.Dispose();
if (close)
{
if (args.Updater is not null)
{
Process p = new();
p.StartInfo.FileName = Path.Combine(args.Updater, AppDomain.CurrentDomain.FriendlyName);
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
{
Process m = Process.Start("/usr/bin/chmod", $"+x {Path.Combine(args.Updater, AppDomain.CurrentDomain.FriendlyName)}");
m.WaitForExit();
}
p.StartInfo.WorkingDirectory = args.Updater;
p.StartInfo.CreateNoWindow = true;
Program.rawargs[1] = AppDomain.CurrentDomain.BaseDirectory;
p.StartInfo.Arguments = $"\"{string.Join("\" \"", Program.rawargs)}\"";
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.Start();
Console.WriteLine("Program done");
return 0;
}
else
{
if (args.Loc is not null)
{
FileInfo fi = new(args.Loc);
if (!fi.Directory!.Exists) Directory.CreateDirectory(fi.Directory.FullName);
UpdaterSettings temp;
if (!File.Exists(args.Loc))
{
File.WriteAllText(args.Loc, JsonSerializer.Serialize(new UpdaterSettings(), UpdaterSettingsContext.Default.UpdaterSettings));
temp = new();
}
try
{
UpdaterSettings? ss = JsonSerializer.Deserialize(File.ReadAllText(args.Loc), UpdaterSettingsContext.Default.UpdaterSettings);
if (ss is null)
{
ss = new();
}
temp = ss;
}
catch
{
temp = new();
}
temp.Updater = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName);
if (args.Platform is not null) temp.Platform = args.Platform!.ToLower();
temp.SelfContained = args.SeflContaind;
temp.Branch = args.Branch!.ToLower() switch
{
"dev" => Branch.Dev,
"beta" => Branch.Beta,
"master" or _ => Branch.Master
};
File.WriteAllText(args.Loc, JsonSerializer.Serialize(temp, UpdaterSettingsContext.Default.UpdaterSettings));
}
if (string.IsNullOrEmpty(args.DLL) || string.IsNullOrWhiteSpace(args.DLL))
{
return 0;
}
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
{
Process m = Process.Start("/usr/bin/chmod", $"+x \"{Path.Combine(args.LocalDirectory, args.DLL)}\"");
m.WaitForExit();
}
string a = "";
foreach (string arg in args.args!)
{
a += arg + " ";
}
Process.Start(new ProcessStartInfo()
{
FileName = Path.Combine(args.LocalDirectory, args.DLL),
Arguments = a,
WorkingDirectory = args.LocalDirectory,
CreateNoWindow = true,
UseShellExecute = true,
})!.WaitForExit();
}
}
return 0;
}
}
#endif

View File

@ -1,15 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StartupObject>Updater.Program</StartupObject> <FileVersion>1.0.0.0</FileVersion>
<ApplicationIcon>Logo.ico</ApplicationIcon>
<FileVersion>2.0.0.0</FileVersion>
<AnalysisLevel>latest</AnalysisLevel> <AnalysisLevel>latest</AnalysisLevel>
<Company>JacobTech, LLC</Company> <Company>JacobTech, LLC</Company>
<Version>1.0.0-alpha02</Version>
<Title>Updater</Title>
<Authors>JacobTech</Authors>
<RepositoryUrl>https://git.jacobtech.com/JacobTech.com/Updater</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<OutputType>Exe</OutputType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>portable</DebugType> <DebugType>portable</DebugType>
@ -25,7 +28,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="GraphicsManager" Version="1.0.7-alpha95" /> <PackageReference Include="GraphicsManager" Version="1.1.1-alpha23" />
<PackageReference Include="WindowsAPICodePack-Shell" Version="1.1.1"> <PackageReference Include="WindowsAPICodePack-Shell" Version="1.1.1">
<NoWarn>NU1701</NoWarn> <NoWarn>NU1701</NoWarn>
</PackageReference> </PackageReference>
@ -35,10 +38,9 @@
<EmbeddedResource Include="Resource/**"></EmbeddedResource> <EmbeddedResource Include="Resource/**"></EmbeddedResource>
</ItemGroup> </ItemGroup>
<Target Name="CustomActionsAfterPublish" AfterTargets="AfterPublish"> <Target Name="CustomActionsAfterPublish" AfterTargets="Pack">
<Message Text="Actions AfterPublish" Importance="high" /> <Message Text="Actions AfterPublish: $(PackageId).$(PackageVersion).nupkg" Importance="high" />
</Target> <Exec Command="nuget push -Source https://nuget.jacobtech.com/v3/index.json bin/Release/$(PackageId).$(PackageVersion).nupkg" />
</Target>
</Project> </Project>

View File

@ -1,46 +0,0 @@
using System.Text.Json.Serialization;
namespace Updater;
public class UpdaterSettings
{
[JsonInclude]
[JsonPropertyName("self_contained")]
public bool SelfContained { get; set; } = false;
[JsonInclude]
[JsonPropertyName("updater")]
public string? Updater { get; set; } = null;
[JsonInclude]
[JsonPropertyName("branch")]
public Branch Branch { get; set; } = Branch.Beta;
[JsonInclude]
[JsonPropertyName("platform")]
public string Platform { get; set; } = "linux-x64";
[JsonInclude]
[JsonPropertyName("auto_launch")]
public bool AutoLaunch { get; set; } = true;
[JsonInclude]
[JsonPropertyName("update_check")]
public bool AutoUpdateCheck { get; set; } = true;
}
public enum Branch : short
{
Dev,
Beta,
Master,
}
[JsonSerializable(typeof(UpdaterSettings))]
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Default,
WriteIndented = true)]
internal partial class UpdaterSettingsContext : JsonSerializerContext
{
}