Skip to content

Commit

Permalink
Add main menu button to check for updates
Browse files Browse the repository at this point in the history
Closes #165
  • Loading branch information
chylex committed Dec 31, 2024
1 parent 86adda6 commit 4215dc7
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 58 deletions.
9 changes: 9 additions & 0 deletions app/Desktop/Common/SystemUtils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Diagnostics;

namespace DHT.Desktop.Common;

static class SystemUtils {
public static void OpenUrl(string url) {
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
}
24 changes: 10 additions & 14 deletions app/Desktop/Main/AboutWindowModel.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,41 @@
using System.Diagnostics;
using DHT.Desktop.Common;

namespace DHT.Desktop.Main;

sealed class AboutWindowModel {
public void ShowOfficialWebsite() {
OpenUrl("https://dht.chylex.com");
SystemUtils.OpenUrl(Program.Website);
}

public void ShowIssueTracker() {
OpenUrl("https://github.com/chylex/Discord-History-Tracker/issues");
SystemUtils.OpenUrl("https://github.com/chylex/Discord-History-Tracker/issues");
}

public void ShowSourceCode() {
OpenUrl("https://github.com/chylex/Discord-History-Tracker");
SystemUtils.OpenUrl("https://github.com/chylex/Discord-History-Tracker");
}

public void ShowLibraryNetCore() {
OpenUrl("https://github.com/dotnet/core");
SystemUtils.OpenUrl("https://github.com/dotnet/core");
}

public void ShowLibraryAvalonia() {
OpenUrl("https://www.nuget.org/packages/Avalonia");
SystemUtils.OpenUrl("https://www.nuget.org/packages/Avalonia");
}

public void ShowLibraryCommunityToolkit() {
OpenUrl("https://github.com/CommunityToolkit/dotnet");
SystemUtils.OpenUrl("https://github.com/CommunityToolkit/dotnet");
}

public void ShowLibrarySqlite() {
OpenUrl("https://www.sqlite.org");
SystemUtils.OpenUrl("https://www.sqlite.org");
}

public void ShowLibrarySqliteAdoNet() {
OpenUrl("https://www.nuget.org/packages/Microsoft.Data.Sqlite");
SystemUtils.OpenUrl("https://www.nuget.org/packages/Microsoft.Data.Sqlite");
}

public void ShowLibraryRxNet() {
OpenUrl("https://github.com/dotnet/reactive");
}

private static void OpenUrl(string url) {
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
SystemUtils.OpenUrl("https://github.com/dotnet/reactive");
}
}
6 changes: 1 addition & 5 deletions app/Desktop/Main/Pages/ViewerPageModel.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Web;
using Avalonia.Controls;
Expand Down Expand Up @@ -52,10 +51,7 @@ public async void OnClickOpenViewer() {
string serverUrl = "http://127.0.0.1:" + ServerConfiguration.Port;
string serverToken = ServerConfiguration.Token;
string sessionId = state.ViewerSessions.Register(new ViewerSession(FilterModel.CreateFilter())).ToString();

Process.Start(new ProcessStartInfo(serverUrl + "/viewer/?token=" + HttpUtility.UrlEncode(serverToken) + "&session=" + HttpUtility.UrlEncode(sessionId)) {
UseShellExecute = true
});
SystemUtils.OpenUrl(serverUrl + "/viewer/?token=" + HttpUtility.UrlEncode(serverToken) + "&session=" + HttpUtility.UrlEncode(sessionId));
} catch (Exception e) {
await Dialog.ShowOk(window, "Open Viewer", "Could not open viewer: " + e.Message);
}
Expand Down
21 changes: 11 additions & 10 deletions app/Desktop/Main/Screens/WelcomeScreen.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,21 @@
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style Selector="Button">
<Setter Property="Margin" Value="5 0" />
<Style Selector="Grid#ButtonPanel > Button">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</UserControl.Styles>

<Panel Name="RootPanel">
<StackPanel Margin="42">
<TextBlock Text="{Binding Version, StringFormat=Discord History Tracker v{0}}" FontSize="25" Margin="0 0 0 30" HorizontalAlignment="Center" />

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Command="{Binding OpenOrCreateDatabase}" IsEnabled="{Binding IsOpenOrCreateDatabaseButtonEnabled}">Open or Create Database</Button>
<Button Command="{Binding ShowAboutDialog}">About</Button>
<Button Command="{Binding Exit}">Exit</Button>
</StackPanel>
<StackPanel Margin="42 30">
<TextBlock Text="{Binding Version, StringFormat=Discord History Tracker v{0}}" FontSize="25" Margin="0 0 0 25" HorizontalAlignment="Center" />

<Grid Name="ButtonPanel" RowDefinitions="Auto,12,Auto,12,Auto" ColumnDefinitions="*,12,*" Margin="12 0" HorizontalAlignment="Stretch">
<Button Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Command="{Binding OpenOrCreateDatabase}" IsEnabled="{Binding IsOpenOrCreateDatabaseButtonEnabled}">Open or Create Database</Button>
<Button Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Command="{Binding CheckUpdates}">Check For Updates</Button>
<Button Grid.Row="4" Grid.Column="0" Command="{Binding ShowAboutDialog}">About</Button>
<Button Grid.Row="4" Grid.Column="2" Command="{Binding Exit}">Exit</Button>
</Grid>
</StackPanel>
</Panel>
</UserControl>
88 changes: 63 additions & 25 deletions app/Desktop/Main/Screens/WelcomeScreenModel.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
Expand All @@ -10,17 +12,20 @@
using DHT.Server.Data.Settings;
using DHT.Server.Database;
using DHT.Server.Database.Sqlite.Schema;
using DHT.Utils.Logging;

namespace DHT.Desktop.Main.Screens;

sealed partial class WelcomeScreenModel : ObservableObject {
private static readonly Log Log = Log.ForType<WelcomeScreenModel>();

public string Version => Program.Version;

[ObservableProperty(Setter = Access.Private)]
private bool isOpenOrCreateDatabaseButtonEnabled = true;
public event EventHandler<IDatabaseFile>? DatabaseSelected;

public event EventHandler<IDatabaseFile>? DatabaseSelected;

private readonly Window window;

private string? dbFilePath;
Expand All @@ -46,28 +51,22 @@ public async Task OpenOrCreateDatabase() {

public async Task OpenOrCreateDatabaseFromPath(string path) {
dbFilePath = path;

bool isNew = !File.Exists(path);

var db = await DatabaseGui.TryOpenOrCreateDatabaseFromPath(path, window, new SchemaUpgradeCallbacks(window));
if (db == null) {
return;
}

if (isNew && await Dialog.ShowYesNo(window, "Automatic Downloads", "Do you want to automatically download files hosted on Discord? You can change this later in the Downloads tab.") == DialogResult.YesNo.Yes) {
await db.Settings.Set(SettingsKey.DownloadsAutoStart, true);
}

DatabaseSelected?.Invoke(this, db);
}

private sealed class SchemaUpgradeCallbacks : ISchemaUpgradeCallbacks {
private readonly Window window;

public SchemaUpgradeCallbacks(Window window) {
this.window = window;
}

private sealed class SchemaUpgradeCallbacks(Window window) : ISchemaUpgradeCallbacks {
public async Task<bool> CanUpgrade() {
return DialogResult.YesNo.Yes == await DatabaseGui.ShowCanUpgradeDatabaseDialog(window);
}
Expand All @@ -80,20 +79,12 @@ async Task StartUpgrade(IReadOnlyList<IProgressCallback> callbacks) {
await doUpgrade(reporter);
await Task.Delay(TimeSpan.FromMilliseconds(600));
}

await new ProgressDialog { DataContext = new ProgressDialogModel("Upgrading Database", StartUpgrade, progressItems: 3) }.ShowProgressDialog(window);
}

private sealed class ProgressReporter : ISchemaUpgradeCallbacks.IProgressReporter {
private readonly IReadOnlyList<IProgressCallback> callbacks;

private readonly int versionSteps;
private sealed class ProgressReporter(int versionSteps, IReadOnlyList<IProgressCallback> callbacks) : ISchemaUpgradeCallbacks.IProgressReporter {
private int versionProgress = 0;

public ProgressReporter(int versionSteps, IReadOnlyList<IProgressCallback> callbacks) {
this.callbacks = callbacks;
this.versionSteps = versionSteps;
}

public async Task NextVersion() {
await callbacks[0].Update("Upgrading schema version...", versionProgress++, versionSteps);
Expand All @@ -118,6 +109,53 @@ private async Task HideChildren(int parentIndex) {
}
}

public async Task CheckUpdates() {
Version? latestVersion = await ProgressDialog.ShowIndeterminate<Version?>(window, "Check Updates", "Checking for updates...", async _ => {
var client = new HttpClient(new SocketsHttpHandler {
AutomaticDecompression = DecompressionMethods.None,
AllowAutoRedirect = false,
UseCookies = false
});

client.Timeout = TimeSpan.FromSeconds(30);
client.MaxResponseContentBufferSize = 1024;
client.DefaultRequestHeaders.UserAgent.ParseAdd("DiscordHistoryTracker/" + Program.Version);

string response;
try {
response = await client.GetStringAsync(Program.Website + "/version");
} catch (TaskCanceledException e) when (e.InnerException is TimeoutException) {
await Dialog.ShowOk(window, "Check Updates", "Request timed out.");
return null;
} catch (Exception e) {
Log.Error(e);
await Dialog.ShowOk(window, "Check Updates", "Error checking for updates: " + e.Message);
return null;
}

if (!System.Version.TryParse(response, out var latestVersion)) {
await Dialog.ShowOk(window, "Check Updates", "Server returned an invalid response.");
return null;
}

return latestVersion;
});

if (latestVersion == null) {
return;
}

if (Program.AssemblyVersion >= latestVersion) {
await Dialog.ShowOk(window, "Check Updates", "You are using the latest version.");
return;
}

if (await Dialog.ShowYesNo(window, "Check Updates", "A newer version is available: v" + Program.VersionToString(latestVersion) + "\nVisit the official website and close the app?") == DialogResult.YesNo.Yes) {
SystemUtils.OpenUrl(Program.Website);
Exit();
}
}

public async Task ShowAboutDialog() {
await new AboutWindow { DataContext = new AboutWindowModel() }.ShowDialog(window);
}
Expand Down
19 changes: 15 additions & 4 deletions app/Desktop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@ namespace DHT.Desktop;

static class Program {
public static string Version { get; }
public static Version AssemblyVersion { get; }
public static CultureInfo Culture { get; }
public static ResourceLoader Resources { get; }
public static Arguments Arguments { get; }

public const string Website = "https://dht.chylex.com";

static Program() {
var assembly = Assembly.GetExecutingAssembly();

Version = assembly.GetName().Version?.ToString() ?? "";
while (Version.EndsWith(".0")) {
Version = Version[..^2];
}
AssemblyVersion = assembly.GetName().Version ?? new Version(0, 0, 0, 0);
Version = VersionToString(AssemblyVersion);

Culture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Expand All @@ -30,6 +31,16 @@ static Program() {
Resources = new ResourceLoader(assembly);
Arguments = new Arguments(Environment.GetCommandLineArgs());
}

public static string VersionToString(Version version) {
string versionStr = version.ToString();

while (versionStr.EndsWith(".0")) {
versionStr = versionStr[..^2];
}

return versionStr;
}

public static void Main(string[] args) {
if (Arguments.Console && OperatingSystem.IsWindows()) {
Expand Down

0 comments on commit 4215dc7

Please sign in to comment.