Skip to content

Commit

Permalink
Merge pull request #3178 from marticliment/better-installer-download-…
Browse files Browse the repository at this point in the history
…experience
  • Loading branch information
marticliment authored Jan 17, 2025
2 parents 1e85b85 + 4da64e4 commit b5267a4
Show file tree
Hide file tree
Showing 31 changed files with 636 additions and 534 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"tg": "Tagalog - Tagalog",
"th": "Thai - ภาษาไทย",
"tr": "Turkish - Türkçe",
"ua": "Ukrainian - Yкраї́нська",
"ua": "Ukrainian - Українська",
"ur": "Urdu - اردو",
"vi": "Vietnamese - Tiếng Việt",
"zh_CN": "Simplified Chinese (China)",
Expand Down
22 changes: 22 additions & 0 deletions src/UniGetUI.Core.Tools.Tests/ToolsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,5 +189,27 @@ public void TestEnvVariableYuxtaposition()
info.Environment.TryGetValue(ENV, out string? result);
Assert.Equal(oldpath, result);
}

[Theory]
[InlineData(10, 33, "hello", "[###.......] 33% (hello)")]
[InlineData(20, 37, null, "[#######.............] 37%")]
[InlineData(10, 0, "", "[..........] 0% ()")]
[InlineData(10, 100, "3/3", "[##########] 100% (3/3)")]
public void TestTextProgressbarGenerator(int length, int progress, string? extra, string? expected)
{
Assert.Equal(CoreTools.TextProgressGenerator(length, progress, extra), expected);
}

[Theory]
[InlineData(0, 1, "0 Bytes")]
[InlineData(10, 1, "10 Bytes")]
[InlineData(1024*34, 0, "34 KB")]
[InlineData(65322450, 3, "62.296 MB")]
[InlineData(65322450000, 3, "60.836 GB")]
[InlineData(65322450000000, 3, "59.410 TB")]
public void TestFormatSize(long size, int decPlaces, string expected)
{
Assert.Equal(CoreTools.FormatAsSize(size, decPlaces).Replace(',', '.'), expected);
}
}
}
94 changes: 75 additions & 19 deletions src/UniGetUI.Core.Tools/Tools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@ public static Tuple<bool, string> Which(string command, bool updateEnv = true)
/// <returns>The formatted string</returns>
public static string FormatAsName(string name)
{
name = name.Replace(".install", "").Replace(".portable", "").Replace("-", " ").Replace("_", " ").Split("/")[^1].Split(":")[0];
name =
name.Replace(".install", "").Replace(".portable", "").Replace("-", " ").Replace("_", " ").Split("/")[^1]
.Split(":")[0];
string newName = "";
for (int i = 0; i < name.Length; i++)
{
Expand All @@ -153,6 +155,7 @@ public static string FormatAsName(string name)
newName += name[i];
}
}

newName = newName.Replace(" [", "[").Replace("[", " [");
return newName;
}
Expand Down Expand Up @@ -200,7 +203,8 @@ public static void ReportFatalException(Exception e)

Console.WriteLine(Error_String);

string ErrorBody = "https://www.marticliment.com/error-report/?appName=UniGetUI^&errorBody=" + Uri.EscapeDataString(Error_String.Replace("\n", "{l}"));
string ErrorBody = "https://www.marticliment.com/error-report/?appName=UniGetUI^&errorBody=" +
Uri.EscapeDataString(Error_String.Replace("\n", "{l}"));

Console.WriteLine(ErrorBody);

Expand Down Expand Up @@ -244,7 +248,7 @@ public static bool IsAdministrator()
try
{
return new WindowsPrincipal(WindowsIdentity.GetCurrent())
.IsInRole(WindowsBuiltInRole.Administrator);
.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (Exception e)
{
Expand Down Expand Up @@ -299,6 +303,7 @@ public static async Task<long> GetFileSizeAsyncAsLong(Uri? url)
Logger.Warn($"Could not load file size for url={url}");
Logger.Warn(e);
}

return 0;
}

Expand Down Expand Up @@ -328,6 +333,7 @@ public static double GetVersionStringAsFloat(string Version)
}
}
}

double res = -1;
if (_ver is not "" and not ".")
{
Expand Down Expand Up @@ -359,18 +365,18 @@ public static double GetVersionStringAsFloat(string Version)
public static string EnsureSafeQueryString(string query)
{
return query.Replace(";", string.Empty)
.Replace("&", string.Empty)
.Replace("|", string.Empty)
.Replace(">", string.Empty)
.Replace("<", string.Empty)
.Replace("%", string.Empty)
.Replace("\"", string.Empty)
.Replace("~", string.Empty)
.Replace("?", string.Empty)
.Replace("/", string.Empty)
.Replace("'", string.Empty)
.Replace("\\", string.Empty)
.Replace("`", string.Empty);
.Replace("&", string.Empty)
.Replace("|", string.Empty)
.Replace(">", string.Empty)
.Replace("<", string.Empty)
.Replace("%", string.Empty)
.Replace("\"", string.Empty)
.Replace("~", string.Empty)
.Replace("?", string.Empty)
.Replace("/", string.Empty)
.Replace("'", string.Empty)
.Replace("\\", string.Empty)
.Replace("`", string.Empty);
}

/// <summary>
Expand Down Expand Up @@ -525,11 +531,13 @@ public static ProcessStartInfo UpdateEnvironmentVariables(ProcessStartInfo info)
{
info.Environment[env.Key?.ToString() ?? "UNKNOWN"] = env.Value?.ToString();
}

foreach (DictionaryEntry env in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User))
{
string key = env.Key.ToString() ?? "";
string newValue = env.Value?.ToString() ?? "";
if (info.Environment.TryGetValue(key, out string? oldValue) && oldValue is not null && oldValue.Contains(';') && newValue != "")
if (info.Environment.TryGetValue(key, out string? oldValue) && oldValue is not null &&
oldValue.Contains(';') && newValue != "")
{
info.Environment[key] = oldValue + ";" + newValue;
}
Expand All @@ -538,6 +546,7 @@ public static ProcessStartInfo UpdateEnvironmentVariables(ProcessStartInfo info)
info.Environment[key] = newValue;
}
}

return info;
}

Expand All @@ -549,7 +558,8 @@ public static async Task WaitForInternetConnection()

public static async Task _waitForInternetConnection()
{
Logger.Debug("Checking for internet connectivity. Pinging google.com, microsoft.com, couldflare.com and marticliment.com");
Logger.Debug(
"Checking for internet connectivity. Pinging google.com, microsoft.com, couldflare.com and marticliment.com");
string[] hosts = ["google.com", "microsoft.com", "cloudflare.com", "marticliment.com"];
while (true)
{
Expand All @@ -562,20 +572,66 @@ public static async Task _waitForInternetConnection()
PingReply reply = await pinger.SendPingAsync(host, 10);
if (reply.Status is IPStatus.Success)
{
Logger.Debug($"{host} responded successfully to ping, internet connection was validated.");
Logger.Debug(
$"{host} responded successfully to ping, internet connection was validated.");
return;
}

Logger.Debug($"Could not ping {host}!");
}
catch (Exception ex)
{
Logger.Debug($"Could not ping {host} with error {ex.Message}. Are you connected to the internet?");
Logger.Debug(
$"Could not ping {host} with error {ex.Message}. Are you connected to the internet?");
}
}
}

await Task.Delay(TimeSpan.FromSeconds(5));
}
}

public static string TextProgressGenerator(int length, int progressPercent, string? extra)
{
int done = (int)((progressPercent / 100.0) * (length));
int rest = length - done;

return new StringBuilder()
.Append('[')
.Append(new string('#', done))
.Append(new string('.', rest))
.Append($"] {progressPercent}%")
.Append(extra is null ? "" : $" ({extra})")
.ToString();
}

public static string FormatAsSize(long number, int decimals = 1)
{
const double KiloByte = 1024d;
const double MegaByte = 1024d * 1024d;
const double GigaByte = 1024d * 1024d * 1024d;
const double TeraByte = 1024d * 1024d * 1024d * 1024d;

if (number >= TeraByte)
{
return $"{(number / TeraByte).ToString($"F{decimals}")} TB";
}
else if (number >= GigaByte)
{
return $"{(number / GigaByte).ToString($"F{decimals}")} GB";
}
else if (number >= MegaByte)
{
return $"{(number / MegaByte).ToString($"F{decimals}")} MB";
}
else if (number >= KiloByte)
{
return $"{(number / KiloByte).ToString($"F{decimals}")} KB";
}
else
{
return $"{number} Bytes";
}
}
}
}
1 change: 1 addition & 0 deletions src/UniGetUI.PackageEngine.Enums/ManagerCapabilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public struct ManagerCapabilities
public bool CanSkipIntegrityChecks = false;
public bool CanRunInteractively = false;
public bool CanRemoveDataOnUninstall = false;
public bool CanDownloadInstaller = false;
public bool SupportsCustomVersions = false;
public bool SupportsCustomArchitectures = false;
public Architecture[] SupportedCustomArchitectures = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public Chocolatey()
Capabilities = new ManagerCapabilities
{
CanRunAsAdmin = true,
CanDownloadInstaller = true,
CanSkipIntegrityChecks = true,
CanRunInteractively = true,
SupportsCustomVersions = true,
Expand Down
1 change: 1 addition & 0 deletions src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public DotNet()
Capabilities = new ManagerCapabilities
{
CanRunAsAdmin = true,
CanDownloadInstaller = true,
SupportsCustomScopes = true,
SupportsCustomArchitectures = true,
SupportedCustomArchitectures = [Architecture.X86, Architecture.X64, Architecture.Arm64, Architecture.Arm],
Expand Down
7 changes: 5 additions & 2 deletions src/UniGetUI.PackageEngine.Managers.Npm/Npm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public Npm()
{
CanRunAsAdmin = true,
SupportsCustomVersions = true,
CanDownloadInstaller = true,
SupportsCustomScopes = true,
SupportsPreRelease = true,
};
Expand Down Expand Up @@ -119,7 +120,8 @@ protected override IEnumerable<Package> GetAvailableUpdates_UnSafe()

string strContents = p.StandardOutput.ReadToEnd();
logger.AddToStdOut(strContents);
JsonObject? contents = JsonNode.Parse(strContents) as JsonObject;
JsonObject? contents = null;
if(strContents.Any()) contents = JsonNode.Parse(strContents) as JsonObject;
foreach (var (packageId, packageData) in contents?.ToDictionary() ?? new())
{
string? version = packageData?["current"]?.ToString();
Expand Down Expand Up @@ -164,7 +166,8 @@ protected override IEnumerable<Package> GetInstalledPackages_UnSafe()

string strContents = p.StandardOutput.ReadToEnd();
logger.AddToStdOut(strContents);
JsonObject? contents = (JsonNode.Parse(strContents) as JsonObject)?["dependencies"] as JsonObject;
JsonObject? contents = null;
if(strContents.Any()) contents = (JsonNode.Parse(strContents) as JsonObject)?["dependencies"] as JsonObject;
foreach (var (packageId, packageData) in contents?.ToDictionary() ?? new())
{
string? version = packageData?["version"]?.ToString();
Expand Down
1 change: 1 addition & 0 deletions src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public Pip()
CanRunAsAdmin = true,
SupportsCustomVersions = true,
SupportsCustomScopes = true,
CanDownloadInstaller = true,
SupportsPreRelease = true,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public PowerShell()
CanRunAsAdmin = true,
CanSkipIntegrityChecks = true,
SupportsCustomVersions = true,
CanDownloadInstaller = true,
SupportsCustomScopes = true,
SupportsCustomSources = true,
SupportsPreRelease = true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public PowerShell7()
SupportsCustomScopes = true,
SupportsCustomSources = true,
SupportsPreRelease = true,
CanDownloadInstaller = true,
SupportsCustomPackageIcons = true,
Sources = new SourceCapabilities
{
Expand Down
1 change: 1 addition & 0 deletions src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public Scoop()
{
CanRunAsAdmin = true,
CanSkipIntegrityChecks = true,
CanDownloadInstaller = true,
CanRemoveDataOnUninstall = true,
SupportsCustomArchitectures = true,
SupportedCustomArchitectures = [Architecture.X86, Architecture.X64, Architecture.Arm64],
Expand Down
1 change: 1 addition & 0 deletions src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public WinGet()
CanSkipIntegrityChecks = true,
CanRunInteractively = true,
SupportsCustomVersions = true,
CanDownloadInstaller = true,
SupportsCustomArchitectures = true,
SupportedCustomArchitectures = [Architecture.X86, Architecture.X64, Architecture.Arm64],
SupportsCustomScopes = true,
Expand Down
Loading

0 comments on commit b5267a4

Please sign in to comment.