Skip to content

Commit

Permalink
Updater refactor and update variable standard?! ayo?
Browse files Browse the repository at this point in the history
  • Loading branch information
LucHeart committed Apr 25, 2024
1 parent 142a935 commit aa6fb7a
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 25 deletions.
61 changes: 40 additions & 21 deletions ShockOsc/Services/Updater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,31 @@
using Microsoft.Extensions.Logging;
using OpenShock.ShockOsc.Config;
using OpenShock.ShockOsc.Models;
using OpenShock.ShockOsc.Ui.Utils;

namespace OpenShock.ShockOsc.Services;

public sealed class Updater
{
private const string GithubLatest = "https://api.github.com/repos/OpenShock/ShockOsc/releases/latest";
private const string SetupFileName = "ShockOSC_Setup.exe"; // OpenShock.ShockOsc.exe

private static readonly HttpClient HttpClient = new();

private readonly string _setupFilePath = Path.Combine(Environment.CurrentDirectory, SetupFileName);
private readonly Version _currentVersion = Assembly.GetEntryAssembly()?.GetName().Version ?? throw new Exception("Could not determine ShockOsc version");

private readonly Version _currentVersion = Assembly.GetEntryAssembly()?.GetName().Version ??
throw new Exception("Could not determine ShockOsc version");

private Uri? LatestDownloadUrl { get; set; }

private readonly ILogger<Updater> _logger;
private readonly ConfigManager _configManager;

public bool UpdateAvailable { get; private set; }

public UpdateableVariable<bool> UpdateAvailable { get; } = new(false);
public Version? LatestVersion { get; private set; }


public Updater(ILogger<Updater> logger, ConfigManager configManager)
{
Expand All @@ -45,7 +50,7 @@ private static bool TryDeleteFile(string fileName)
return false;
}
}

private async Task<(Version, GithubReleaseResponse.Asset)?> GetLatestRelease()
{
_logger.LogInformation("Checking GitHub for updates...");
Expand All @@ -55,18 +60,24 @@ private static bool TryDeleteFile(string fileName)
var res = await HttpClient.GetAsync(GithubLatest);
if (!res.IsSuccessStatusCode)
{
_logger.LogWarning("Failed to get latest version information from GitHub. {StatusCode}", res.StatusCode);
_logger.LogWarning("Failed to get latest version information from GitHub. {StatusCode}",
res.StatusCode);
return null;
}

var json = await JsonSerializer.DeserializeAsync<GithubReleaseResponse>(await res.Content.ReadAsStreamAsync());
var json =
await JsonSerializer.DeserializeAsync<GithubReleaseResponse>(await res.Content.ReadAsStreamAsync());
if (json == null)
{
_logger.LogWarning("Could not deserialize json");
return null;
}

if (!Version.TryParse(json.TagName[1..], out var version))
var tagName = json.TagName;
if (!string.IsNullOrEmpty(tagName) && tagName[0] == 'v')
tagName = tagName[1..];

if (!Version.TryParse(tagName, out var version))
{
_logger.LogWarning("Failed to parse version. Value: {Version}", json.TagName);
return null;
Expand All @@ -75,7 +86,8 @@ private static bool TryDeleteFile(string fileName)
var asset = json.Assets.FirstOrDefault(x => x.Name == SetupFileName);
if (asset == null)
{
_logger.LogWarning("Could not find asset with {@SetupName}. Assets found: {@Assets}", SetupFileName, json.Assets);
_logger.LogWarning("Could not find asset with {@SetupName}. Assets found: {@Assets}", SetupFileName,
json.Assets);
return null;
}

Expand All @@ -88,32 +100,39 @@ private static bool TryDeleteFile(string fileName)
}
}

public async Task<bool> CheckUpdate()
public async Task CheckUpdate()
{
var latestVersion = await GetLatestRelease();
if (latestVersion is null) return false;
if (latestVersion == null)
{
UpdateAvailable.Value = false;
return;
}
if (latestVersion.Value.Item1 <= _currentVersion)
{
_logger.LogInformation("ShockOsc is up to date ([{Version}] >= [{LatestVersion}])", _currentVersion, latestVersion.Value.Item1);
UpdateAvailable = false;
return false;
_logger.LogInformation("ShockOsc is up to date ([{Version}] >= [{LatestVersion}])", _currentVersion,
latestVersion.Value.Item1);
UpdateAvailable.Value = false;
return;
}

UpdateAvailable = true;
UpdateAvailable.Value = true;
LatestVersion = latestVersion.Value.Item1;
LatestDownloadUrl = latestVersion.Value.Item2.BrowserDownloadUrl;
if (_configManager.Config.LastIgnoredVersion != null &&
_configManager.Config.LastIgnoredVersion >= latestVersion.Value.Item1)
{
_logger.LogInformation("ShockOsc is not up to date. Skipping update due to previous postpone. You can reenable the updater by setting 'LastIgnoredVersion' to null");
return false;
_logger.LogInformation(
"ShockOsc is not up to date. Skipping update due to previous postpone. You can reenable the updater by setting 'LastIgnoredVersion' to null");
UpdateAvailable.Value = false;
return;
}

_logger.LogWarning(
"ShockOsc is not up to date. Newest version is [{NewVersion}] but you are on [{CurrentVersion}]!",
latestVersion.Value.Item1, _currentVersion);

return true;
UpdateAvailable.Value = true;
}

public async Task DoUpdate()
Expand Down
14 changes: 10 additions & 4 deletions ShockOsc/Ui/Components/UpdateLogout.razor
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@

protected override async Task OnInitializedAsync()
{
if (await Updater.CheckUpdate()) OpenUpdateDialog();
Updater.UpdateAvailable.OnValueChanged += v =>
{
InvokeAsync(StateHasChanged);
OpenUpdateDialog();
};

await Updater.CheckUpdate();
}

private async Task Logout()
Expand All @@ -37,9 +43,9 @@
</MudTooltip>


<MudTooltip Text="@(Updater.UpdateAvailable ? "Update" : "You are up-to-date!")">
<MudButton Disabled="!Updater.UpdateAvailable" Color="Color.Primary" @onclick="OpenUpdateDialog" Size="Size.Small" Variant="Variant.Filled" Class="mud-button-full-width">
<MudIcon Icon="@(Updater.UpdateAvailable ? Icons.Material.Filled.Update : Icons.Material.Filled.UpdateDisabled)"/>
<MudTooltip Text="@(Updater.UpdateAvailable.Value ? "Update" : "You are up-to-date!")">
<MudButton Disabled="!Updater.UpdateAvailable.Value" Color="Color.Primary" @onclick="OpenUpdateDialog" Size="Size.Small" Variant="Variant.Filled" Class="mud-button-full-width">
<MudIcon Icon="@(Updater.UpdateAvailable.Value ? Icons.Material.Filled.Update : Icons.Material.Filled.UpdateDisabled)"/>
</MudButton>
</MudTooltip>

Expand Down
22 changes: 22 additions & 0 deletions ShockOsc/Ui/Utils/UpdateableVariable.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace OpenShock.ShockOsc.Ui.Utils;

public sealed class UpdateableVariable<T>(T internalValue)
{
public T Value
{
get => internalValue;
set
{
if (internalValue!.Equals(value)) return;
internalValue = value;
OnValueChanged?.Invoke(value);
}
}

public event Action<T>? OnValueChanged;

public void UpdateWithoutNotify(T newValue)
{
internalValue = newValue;
}
}

0 comments on commit aa6fb7a

Please sign in to comment.