Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check for updates menu item #1913

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion UndertaleModLib/UndertaleModLib.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
<GitPath Condition="'$(ErrorCode)'=='1'">$(DevEnvDir)\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd\git</GitPath>
</PropertyGroup>
<!-- Use GitPath and put the git commit name and branch name into gitversion.txt which is an embedded resource-->
<Exec Command="( &quot;$(GitPath)&quot; describe --always --dirty &amp;&amp; &quot;$(GitPath)&quot; rev-parse --abbrev-ref HEAD ) &gt; &quot;$(ProjectDir)/gitversion.txt&quot;" IgnoreExitCode="true" />
<Exec ConsoleToMSBuild="true" IgnoreExitCode="true"
Command="( &quot;$(GitPath)&quot; describe --always --dirty &amp;&amp; &quot;$(GitPath)&quot; rev-parse --abbrev-ref HEAD &amp;&amp; &quot;$(GitPath)&quot; show -s --format=%%cI ) &gt; &quot;$(ProjectDir)/gitversion.txt&quot;"/>
</Target>
</Project>
29 changes: 16 additions & 13 deletions UndertaleModLib/Util/GitVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,24 @@ namespace UndertaleModLib.Util;

/// <summary>
/// Includes miscellaneous git information about the project to compile.
/// <b>Only intended for Debug use!</b>
/// </summary>
public static class GitVersion
{
public record GitVersionData(string Commit, string Branch, DateTimeOffset Time);

/// <summary>
/// Gets and returns the git commit and branch name.
/// </summary>
/// <returns>The git commit and branch name.</returns>
public static string GetGitVersion()
{
string gitOutput;
GitVersionData data = GetGitVersionData();
return data is null ? "unknownGitCommit" : $"{data.Commit} ({data.Branch})";
}

// try to access the embedded resource
public static GitVersionData GetGitVersionData()
{
// Try to access the embedded resource
try
{
var assembly = Assembly.GetExecutingAssembly();
Expand All @@ -28,21 +33,19 @@ public static string GetGitVersion()
using (StreamReader reader = new StreamReader(stream))
{
// \r is getting nuked just in case Windows is weird.
gitOutput = reader.ReadToEnd().Trim().Replace("\r", "");
}
string[] data = reader.ReadToEnd().Trim().Replace("\r", "").Split('\n');

// gets formatted as "<commit> (<branch>)"
var outputAsArray = gitOutput.Split('\n');
gitOutput = $"{outputAsArray[0]} ({outputAsArray[1]})";
return new GitVersionData(
Commit: data[0],
Branch: data[1],
Time: DateTimeOffset.Parse(data[2])
);
}
}
// If accessing it fails, give it a default output
catch
{
gitOutput = "unknownGitCommit";
return null;
}

// return combined commit + branch
if (String.IsNullOrWhiteSpace(gitOutput)) gitOutput = "unknownGitCommit";
return gitOutput;
}
}
11 changes: 11 additions & 0 deletions UndertaleModTool/BuildInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace UndertaleModTool
{
internal static class BuildInfo
{
#if BUILD_SINGLEFILE_true
public static bool IsSingleFile = true;
#else
public static bool IsSingleFile = false;
#endif
}
}
1 change: 1 addition & 0 deletions UndertaleModTool/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@
Click="MenuItem_RunBuiltinScript_Item_Click" CommandParameter="Scripts\Builtin Scripts\SearchLimited.csx"/>
</local:MenuItemDark>
<local:MenuItemDark Header="_Help">
<MenuItem Header="_Check for updates" Click="MenuItem_CheckForUpdates_Click"/>
<MenuItem Header="_GitHub" Click="MenuItem_GitHub_Click"/>
<MenuItem Header="_About" Click="MenuItem_About_Click"/>
</local:MenuItemDark>
Expand Down
183 changes: 155 additions & 28 deletions UndertaleModTool/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,53 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ookii.Dialogs.Wpf;
using UndertaleModLib;
using UndertaleModLib.Decompiler;
using UndertaleModLib.Models;
using UndertaleModLib.ModelsDebug;
using UndertaleModLib.Scripting;
using UndertaleModLib.Util;
using UndertaleModTool.Windows;
using System.IO.Pipes;
using Ookii.Dialogs.Wpf;

using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Security.Cryptography;
using System.Collections.Concurrent;
using System.Runtime;
using SystemJson = System.Text.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Globalization;
using System.Windows.Controls.Primitives;
using System.Runtime.CompilerServices;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace UndertaleModTool
{
Expand Down Expand Up @@ -198,13 +199,14 @@
private Task scriptSetupTask;

// Version info
public static string VersionNumber = Assembly.GetExecutingAssembly().GetName().Version.ToString();
public static string Edition = "(Git: " + GitVersion.GetGitVersion().Substring(0, 7) + ")";

// On debug, build with git versions and provided release version. Otherwise, use the provided release version only.
#if DEBUG || SHOW_COMMIT_HASH
public static string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString() + (Edition != "" ? " - " + Edition : "");
public static string Version = VersionNumber + (Edition != "" ? " - " + Edition : "");
#else
public static string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
public static string Version = VersionNumber;
#endif

private static readonly Color darkColor = Color.FromArgb(255, 32, 32, 32);
Expand Down Expand Up @@ -501,6 +503,11 @@

RunGMSDebuggerItem.Visibility = Settings.Instance.ShowDebuggerOption
? Visibility.Visible : Visibility.Collapsed;

if (Settings.Instance.CheckForUpdatesAtStartup)
{
_ = CheckForUpdates(isStartup: true);
}
}

public Dictionary<string, NamedPipeServerStream> childFiles = new Dictionary<string, NamedPipeServerStream>();
Expand Down Expand Up @@ -2877,6 +2884,127 @@
OpenBrowser("https://github.com/UnderminersTeam/UndertaleModTool");
}

private void MenuItem_CheckForUpdates_Click(object sender, RoutedEventArgs e)
{
_ = CheckForUpdates();
}

async Task CheckForUpdates(bool isStartup = false)
{
LoaderDialog loaderDialog = new("Check for updates", "Checking for updates...");
loaderDialog.Owner = this;
loaderDialog.PreventClose = true;
loaderDialog.Show();

try
{
httpClient ??= new();

JsonNode jsonResponse;

using (var request = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/repos/UnderminersTeam/UndertaleModTool/releases/latest"))
{
request.Headers.Add("Accept", "application/vnd.github+json");
request.Headers.Add("X-GitHub-Api-Version", "2022-11-28");
request.Headers.Add("User-Agent", new Regex(@"Git:|[ (),/:;<=>?@[\]{}]").Replace(Version, ""));

using var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();

jsonResponse = await response.Content.ReadFromJsonAsync<JsonNode>();
}

string latestVersion = (string)jsonResponse["tag_name"];

DateTimeOffset latestDateTime = ((DateTimeOffset)jsonResponse["created_at"]); // This is the commit time, not release time
DateTimeOffset currentDateTime = GitVersion.GetGitVersionData().Time;

// Uncomment for testing
//VersionNumber = "0.0.0.0";
//currentDateTime = new(1970, 1, 1, 0, 0, 0, new());
//latestVersion = "0.0.0.0";
//latestDateTime = new(1970, 1, 1, 0, 0, 0, new());
//BuildInfo.IsSingleFile = true;

if (latestVersion == VersionNumber)
{
if (latestDateTime != currentDateTime)
{
if (!isStartup)
loaderDialog.ShowError("Error: Latest version is the same as current version, but their commit times are different. Probably custom build." +
$"\nVersion: {VersionNumber}" +
$"\nLatest version time: {latestDateTime.ToLocalTime()}" +
$"\nCurrent version time: {currentDateTime.ToLocalTime()}");
return;
}

if (!isStartup)
loaderDialog.ShowMessage("UndertaleModTool is up to date." +
$"\nVersion: {latestVersion} ({currentDateTime.ToLocalTime()})");
return;
}

if (latestDateTime < currentDateTime)
{
if (!isStartup)
loaderDialog.ShowError("Error: Latest version is older then current version. Probably in different branch or custom build." +
$"\nLatest version: {latestVersion} ({latestDateTime.ToLocalTime()})" +
$"\nCurrent version: {VersionNumber} ({currentDateTime.ToLocalTime()})");
return;
}

// Version is different and newer, continue

string expectedAssetName = $"UndertaleModTool_v{latestVersion}{(BuildInfo.IsSingleFile ? "-SingleFile" : "")}.zip";

JsonNode asset = jsonResponse["assets"].AsArray()
.FirstOrDefault((JsonNode asset) => (string)asset["name"] == expectedAssetName, null);

string questionText = "A new version of UndertaleModTool is avaliable!" +
"\n" +
$"\nCurrent version: {VersionNumber} ({currentDateTime.ToLocalTime()})" +
$"\nLatest version: {latestVersion} ({latestDateTime.ToLocalTime()})" +
"\n" +
(isStartup ?
"\nYou can disable checking for updates at startup in the settings." +
"\n" : "") +
(asset != null ?
"\nDo you want to download the latest version?" :
"\nHowever, an asset fitting your build was not found. Do you want to visit the release page?");

if (loaderDialog.ShowQuestion(questionText) == MessageBoxResult.Yes)
{
if (asset != null)
{
OpenBrowser((string)asset["browser_download_url"]);
}
else
{
OpenBrowser((string)jsonResponse["html_url"]);
}

// TODO: Auto update
}
}
catch (Exception e) when (e is HttpRequestException || e is TaskCanceledException)
{
if (!isStartup)
{
string errText = "Check your internet connection.";
if (e is HttpRequestException e2 && e2.StatusCode != null)
{
errText = $"HTTP error {e2.StatusCode}.";
}
loaderDialog.ShowError($"Failed to check for updates! {errText}");
}
}
finally
{
loaderDialog.PreventClose = false;
loaderDialog.Close();
}
}

private void MenuItem_About_Click(object sender, RoutedEventArgs e)
{
this.ShowMessage("UndertaleModTool by krzys_h and the Underminers team\nVersion " + Version, "About");
Expand Down Expand Up @@ -2938,14 +3066,13 @@
}
}


private async Task<HttpResponseMessage> HttpGetAsync(string uri)
{
try
{
return await httpClient.GetAsync(uri);
}
catch (Exception exp) when (exp is not NullReferenceException)
catch (Exception exp) when (exp is HttpRequestException || exp is TaskCanceledException)
{
return null;
}
Expand All @@ -2956,7 +3083,7 @@

window.UpdateButtonEnabled = false;

httpClient = new();
httpClient ??= new();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

Expand Down Expand Up @@ -3093,7 +3220,7 @@
};
SetProgressBar();

using (WebClient webClient = new())

Check warning on line 3223 in UndertaleModTool/MainWindow.xaml.cs

View workflow job for this annotation

GitHub Actions / build_gui (windows-latest, Debug, false, false)

'WebClient.WebClient()' is obsolete: 'WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.' (https://aka.ms/dotnet-warnings/SYSLIB0014)

Check warning on line 3223 in UndertaleModTool/MainWindow.xaml.cs

View workflow job for this annotation

GitHub Actions / build_gui (windows-latest, Debug, false, false)

'WebClient.WebClient()' is obsolete: 'WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.' (https://aka.ms/dotnet-warnings/SYSLIB0014)

Check warning on line 3223 in UndertaleModTool/MainWindow.xaml.cs

View workflow job for this annotation

GitHub Actions / build_gui (windows-latest, Debug, false, true)

'WebClient.WebClient()' is obsolete: 'WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.' (https://aka.ms/dotnet-warnings/SYSLIB0014)

Check warning on line 3223 in UndertaleModTool/MainWindow.xaml.cs

View workflow job for this annotation

GitHub Actions / build_gui (windows-latest, Debug, false, true)

'WebClient.WebClient()' is obsolete: 'WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.' (https://aka.ms/dotnet-warnings/SYSLIB0014)
{
bool end = false;
bool ended = false;
Expand Down
6 changes: 2 additions & 4 deletions UndertaleModTool/Settings.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;

namespace UndertaleModTool
Expand Down Expand Up @@ -54,6 +50,8 @@ public class Settings
public bool EnableDarkMode { get; set; } = false;
public bool ShowDebuggerOption { get; set; } = false;

public bool CheckForUpdatesAtStartup { get; set; } = true;

public static Settings Instance;

public static JsonSerializerOptions JsonOptions = new JsonSerializerOptions
Expand Down
3 changes: 3 additions & 0 deletions UndertaleModTool/UndertaleModTool.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
<!-- Suppress all missing XML comment warnings -->
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
<DefineConstants>$(DefineConstants);BUILD_SINGLEFILE_$(PublishSingleFile)</DefineConstants>
</PropertyGroup>
<ItemGroup>
<None Remove="Resources\tabs_left_button.png" />
<None Remove="Resources\tabs_right_button.png" />
Expand Down
Loading
Loading