mirror of
https://github.com/chylex/Discord-History-Tracker.git
synced 2025-04-12 06:50:01 +03:00
Fix exception handling in progress dialogs
This commit is contained in:
parent
5741fad528
commit
fa17d0e224
@ -2,7 +2,6 @@ using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using DHT.Desktop.Dialogs.Message;
|
||||
using DHT.Utils.Logging;
|
||||
|
||||
namespace DHT.Desktop.Dialogs.Progress;
|
||||
@ -12,57 +11,37 @@ public sealed partial class ProgressDialog : Window {
|
||||
private static readonly Log Log = Log.ForType<ProgressDialog>();
|
||||
|
||||
internal static async Task Show(Window owner, string title, Func<ProgressDialog, IProgressCallback, Task> action) {
|
||||
var taskCompletionSource = new TaskCompletionSource();
|
||||
var dialog = new ProgressDialog();
|
||||
|
||||
dialog.DataContext = new ProgressDialogModel(title, async callbacks => {
|
||||
try {
|
||||
await action(dialog, callbacks[0]);
|
||||
taskCompletionSource.SetResult();
|
||||
} catch (Exception e) {
|
||||
taskCompletionSource.SetException(e);
|
||||
}
|
||||
});
|
||||
|
||||
dialog.DataContext = new ProgressDialogModel(title, async callbacks => await action(dialog, callbacks[0]));
|
||||
await dialog.ShowProgressDialog(owner);
|
||||
await taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
internal static async Task ShowIndeterminate(Window owner, string title, string message, Func<ProgressDialog, Task> action) {
|
||||
var taskCompletionSource = new TaskCompletionSource();
|
||||
var dialog = new ProgressDialog();
|
||||
|
||||
dialog.DataContext = new ProgressDialogModel(title, async callbacks => {
|
||||
await callbacks[0].UpdateIndeterminate(message);
|
||||
try {
|
||||
await action(dialog);
|
||||
taskCompletionSource.SetResult();
|
||||
} catch (Exception e) {
|
||||
taskCompletionSource.SetException(e);
|
||||
}
|
||||
});
|
||||
|
||||
await dialog.ShowProgressDialog(owner);
|
||||
await taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
internal static async Task<T> ShowIndeterminate<T>(Window owner, string title, string message, Func<ProgressDialog, Task<T>> action) {
|
||||
internal static async Task<T> Show<T>(Window owner, string title, Func<ProgressDialog, IProgressCallback, Task<T>> action) {
|
||||
var taskCompletionSource = new TaskCompletionSource<T>();
|
||||
var dialog = new ProgressDialog();
|
||||
|
||||
dialog.DataContext = new ProgressDialogModel(title, async callbacks => {
|
||||
await callbacks[0].UpdateIndeterminate(message);
|
||||
try {
|
||||
taskCompletionSource.SetResult(await action(dialog));
|
||||
} catch (Exception e) {
|
||||
taskCompletionSource.SetException(e);
|
||||
}
|
||||
taskCompletionSource.SetResult(await action(dialog, callbacks[0]));
|
||||
});
|
||||
|
||||
await dialog.ShowProgressDialog(owner);
|
||||
return await taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
internal static Task ShowIndeterminate(Window owner, string title, string message, Func<ProgressDialog, Task> action) {
|
||||
return Show(owner, title, async (dialog, callback) => {
|
||||
await callback.UpdateIndeterminate(message);
|
||||
await action(dialog);
|
||||
});
|
||||
}
|
||||
|
||||
internal static Task<T> ShowIndeterminate<T>(Window owner, string title, string message, Func<ProgressDialog, Task<T>> action) {
|
||||
return Show<T>(owner, title, async (dialog, callback) => {
|
||||
await callback.UpdateIndeterminate(message);
|
||||
return await action(dialog);
|
||||
});
|
||||
}
|
||||
|
||||
private bool isFinished = false;
|
||||
private Task progressTask = Task.CompletedTask;
|
||||
|
||||
@ -88,11 +67,6 @@ public sealed partial class ProgressDialog : Window {
|
||||
|
||||
public async Task ShowProgressDialog(Window owner) {
|
||||
await ShowDialog(owner);
|
||||
try {
|
||||
await progressTask;
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(owner, "Unexpected Error", e.Message);
|
||||
}
|
||||
await progressTask;
|
||||
}
|
||||
}
|
||||
|
@ -74,15 +74,28 @@ sealed class DatabasePageModel {
|
||||
|
||||
public async Task MergeWithDatabase() {
|
||||
string[] paths = await DatabaseGui.NewOpenDatabaseFilesDialog(window, Path.GetDirectoryName(Db.Path));
|
||||
if (paths.Length > 0) {
|
||||
await ProgressDialog.Show(window, "Database Merge", async (dialog, callback) => await MergeWithDatabaseFromPaths(Db, paths, dialog, callback));
|
||||
if (paths.Length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const string Title = "Database Merge";
|
||||
|
||||
ImportResult? result;
|
||||
try {
|
||||
result = await ProgressDialog.Show(window, Title, async (dialog, callback) => await MergeWithDatabaseFromPaths(Db, paths, dialog, callback));
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(window, Title, "Could not merge databases: " + e.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
await Dialog.ShowOk(window, Title, GetImportDialogMessage(result, "database file"));
|
||||
}
|
||||
|
||||
private static async Task MergeWithDatabaseFromPaths(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback) {
|
||||
private static async Task<ImportResult?> MergeWithDatabaseFromPaths(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback) {
|
||||
var schemaUpgradeCallbacks = new SchemaUpgradeCallbacks(dialog, paths.Length);
|
||||
|
||||
await PerformImport(target, paths, dialog, callback, "Database Merge", "Database Error", "database file", async path => {
|
||||
return await PerformImport(target, paths, dialog, callback, "Database Merge", async path => {
|
||||
IDatabaseFile? db = await DatabaseGui.TryOpenOrCreateDatabaseFromPath(path, dialog, schemaUpgradeCallbacks);
|
||||
|
||||
if (db == null) {
|
||||
@ -137,15 +150,28 @@ sealed class DatabasePageModel {
|
||||
AllowMultiple = true,
|
||||
});
|
||||
|
||||
if (paths.Length > 0) {
|
||||
await ProgressDialog.Show(window, "Legacy Archive Import", async (dialog, callback) => await ImportLegacyArchiveFromPaths(Db, paths, dialog, callback));
|
||||
if (paths.Length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const string Title = "Legacy Archive Import";
|
||||
|
||||
ImportResult? result;
|
||||
try {
|
||||
result = await ProgressDialog.Show(window, Title, async (dialog, callback) => await ImportLegacyArchiveFromPaths(Db, paths, dialog, callback));
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(window, Title, "Could not import legacy archives: " + e.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
await Dialog.ShowOk(window, Title, GetImportDialogMessage(result, "archive file"));
|
||||
}
|
||||
|
||||
private static async Task ImportLegacyArchiveFromPaths(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback) {
|
||||
private static async Task<ImportResult?> ImportLegacyArchiveFromPaths(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback) {
|
||||
var fakeSnowflake = new FakeSnowflake();
|
||||
|
||||
await PerformImport(target, paths, dialog, callback, "Legacy Archive Import", "Legacy Archive Error", "archive file", async path => {
|
||||
return await PerformImport(target, paths, dialog, callback, "Legacy Archive Import", async path => {
|
||||
await using var jsonStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
|
||||
return await LegacyArchiveImport.Read(jsonStream, target, fakeSnowflake, async servers => {
|
||||
@ -189,7 +215,7 @@ sealed class DatabasePageModel {
|
||||
.ToDictionary(static item => item.Item, static item => ulong.Parse(item.Value));
|
||||
}
|
||||
|
||||
private static async Task PerformImport(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback, string neutralDialogTitle, string errorDialogTitle, string itemName, Func<string, Task<bool>> performImport) {
|
||||
private static async Task<ImportResult?> PerformImport(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback, string dialogTitle, Func<string, Task<bool>> performImport) {
|
||||
int total = paths.Length;
|
||||
DatabaseStatistics oldStatistics = await DatabaseStatistics.Take(target);
|
||||
|
||||
@ -201,7 +227,7 @@ sealed class DatabasePageModel {
|
||||
++finished;
|
||||
|
||||
if (!File.Exists(path)) {
|
||||
await Dialog.ShowOk(dialog, errorDialogTitle, "File '" + Path.GetFileName(path) + "' no longer exists.");
|
||||
await Dialog.ShowOk(dialog, dialogTitle, "File '" + Path.GetFileName(path) + "' no longer exists.");
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -211,19 +237,18 @@ sealed class DatabasePageModel {
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Log.Error(ex);
|
||||
await Dialog.ShowOk(dialog, errorDialogTitle, "File '" + Path.GetFileName(path) + "' could not be imported: " + ex.Message);
|
||||
await Dialog.ShowOk(dialog, dialogTitle, "File '" + Path.GetFileName(path) + "' could not be imported: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
await callback.Update("Done", finished, total);
|
||||
|
||||
if (successful == 0) {
|
||||
await Dialog.ShowOk(dialog, neutralDialogTitle, "Nothing was imported.");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
DatabaseStatistics newStatistics = await DatabaseStatistics.Take(target);
|
||||
await Dialog.ShowOk(dialog, neutralDialogTitle, GetImportDialogMessage(oldStatistics, newStatistics, successful, total, itemName));
|
||||
return new ImportResult(oldStatistics, newStatistics, successful, total);
|
||||
}
|
||||
|
||||
private sealed record DatabaseStatistics(long ServerCount, long ChannelCount, long UserCount, long MessageCount) {
|
||||
@ -237,7 +262,16 @@ sealed class DatabasePageModel {
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetImportDialogMessage(DatabaseStatistics oldStatistics, DatabaseStatistics newStatistics, int successfulItems, int totalItems, string itemName) {
|
||||
private sealed record ImportResult(DatabaseStatistics OldStatistics, DatabaseStatistics NewStatistics, int SuccessfulItems, int TotalItems);
|
||||
|
||||
private static string GetImportDialogMessage(ImportResult? result, string itemName) {
|
||||
if (result == null) {
|
||||
return "Nothing was imported.";
|
||||
}
|
||||
|
||||
var oldStatistics = result.OldStatistics;
|
||||
var newStatistics = result.NewStatistics;
|
||||
|
||||
long newServers = newStatistics.ServerCount - oldStatistics.ServerCount;
|
||||
long newChannels = newStatistics.ChannelCount - oldStatistics.ChannelCount;
|
||||
long newUsers = newStatistics.UserCount - oldStatistics.UserCount;
|
||||
@ -246,11 +280,11 @@ sealed class DatabasePageModel {
|
||||
var message = new StringBuilder();
|
||||
message.Append("Processed ");
|
||||
|
||||
if (successfulItems == totalItems) {
|
||||
message.Append(successfulItems.Pluralize(itemName));
|
||||
if (result.SuccessfulItems == result.TotalItems) {
|
||||
message.Append(result.SuccessfulItems.Pluralize(itemName));
|
||||
}
|
||||
else {
|
||||
message.Append(successfulItems.Format()).Append(" out of ").Append(totalItems.Pluralize(itemName));
|
||||
message.Append(result.SuccessfulItems.Format()).Append(" out of ").Append(result.TotalItems.Pluralize(itemName));
|
||||
}
|
||||
|
||||
message.Append(" and added:\n\n \u2022 ");
|
||||
@ -264,7 +298,15 @@ sealed class DatabasePageModel {
|
||||
|
||||
public async Task VacuumDatabase() {
|
||||
const string Title = "Vacuum Database";
|
||||
await ProgressDialog.ShowIndeterminate(window, Title, "Vacuuming database...", _ => Db.Vacuum());
|
||||
|
||||
try {
|
||||
await ProgressDialog.ShowIndeterminate(window, Title, "Vacuuming database...", _ => Db.Vacuum());
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(window, Title, "Could not vacuum database: " + e.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
await Dialog.ShowOk(window, Title, "Done.");
|
||||
}
|
||||
}
|
||||
|
@ -168,43 +168,48 @@ sealed partial class DownloadsPageModel : ObservableObject, IAsyncDisposable {
|
||||
public async Task OnClickDeleteOrphanedDownloads() {
|
||||
const string Title = "Delete Orphaned Downloads";
|
||||
|
||||
await ProgressDialog.Show(window, Title, async (_, callback) => {
|
||||
await callback.UpdateIndeterminate("Searching for orphaned downloads...");
|
||||
|
||||
HashSet<string> reachableNormalizedUrls = [];
|
||||
HashSet<string> orphanedNormalizedUrls = [];
|
||||
|
||||
await foreach (Download download in state.Db.Downloads.FindAllDownloadableUrls()) {
|
||||
reachableNormalizedUrls.Add(download.NormalizedUrl);
|
||||
}
|
||||
|
||||
await foreach (Download download in state.Db.Downloads.Get()) {
|
||||
string normalizedUrl = download.NormalizedUrl;
|
||||
if (!reachableNormalizedUrls.Contains(normalizedUrl)) {
|
||||
orphanedNormalizedUrls.Add(normalizedUrl);
|
||||
try {
|
||||
await ProgressDialog.Show(window, Title, async (_, callback) => {
|
||||
await callback.UpdateIndeterminate("Searching for orphaned downloads...");
|
||||
|
||||
HashSet<string> reachableNormalizedUrls = [];
|
||||
HashSet<string> orphanedNormalizedUrls = [];
|
||||
|
||||
await foreach (Download download in state.Db.Downloads.FindAllDownloadableUrls()) {
|
||||
reachableNormalizedUrls.Add(download.NormalizedUrl);
|
||||
}
|
||||
}
|
||||
|
||||
if (orphanedNormalizedUrls.Count == 0) {
|
||||
await Dialog.ShowOk(window, Title, "No orphaned downloads found.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (await Dialog.ShowYesNo(window, Title, orphanedNormalizedUrls.Count + " orphaned download(s) will be removed from this database. This action cannot be undone. Proceed?") != DialogResult.YesNo.Yes) {
|
||||
return;
|
||||
}
|
||||
|
||||
await callback.UpdateIndeterminate("Deleting orphaned downloads...");
|
||||
await state.Db.Downloads.Remove(orphanedNormalizedUrls);
|
||||
RecomputeDownloadStatistics();
|
||||
|
||||
if (await Dialog.ShowYesNo(window, Title, "Orphaned downloads deleted. Vacuum database now to reclaim space?") != DialogResult.YesNo.Yes) {
|
||||
return;
|
||||
}
|
||||
|
||||
await callback.UpdateIndeterminate("Vacuuming database...");
|
||||
await state.Db.Vacuum();
|
||||
});
|
||||
|
||||
await foreach (Download download in state.Db.Downloads.Get()) {
|
||||
string normalizedUrl = download.NormalizedUrl;
|
||||
if (!reachableNormalizedUrls.Contains(normalizedUrl)) {
|
||||
orphanedNormalizedUrls.Add(normalizedUrl);
|
||||
}
|
||||
}
|
||||
|
||||
if (orphanedNormalizedUrls.Count == 0) {
|
||||
await Dialog.ShowOk(window, Title, "No orphaned downloads found.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (await Dialog.ShowYesNo(window, Title, orphanedNormalizedUrls.Count + " orphaned download(s) will be removed from this database. This action cannot be undone. Proceed?") != DialogResult.YesNo.Yes) {
|
||||
return;
|
||||
}
|
||||
|
||||
await callback.UpdateIndeterminate("Deleting orphaned downloads...");
|
||||
await state.Db.Downloads.Remove(orphanedNormalizedUrls);
|
||||
RecomputeDownloadStatistics();
|
||||
|
||||
if (await Dialog.ShowYesNo(window, Title, "Orphaned downloads deleted. Vacuum database now to reclaim space?") != DialogResult.YesNo.Yes) {
|
||||
return;
|
||||
}
|
||||
|
||||
await callback.UpdateIndeterminate("Vacuuming database...");
|
||||
await state.Db.Vacuum();
|
||||
});
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(window, Title, "Could not delete orphaned downloads: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateStatistics(DownloadStatusStatistics statusStatistics) {
|
||||
|
@ -61,18 +61,23 @@ sealed partial class ViewerPageModel : ObservableObject, IDisposable {
|
||||
}
|
||||
|
||||
public async Task OnClickApplyFiltersToDatabase() {
|
||||
MessageFilter filter = FilterModel.CreateFilter();
|
||||
long messageCount = await ProgressDialog.ShowIndeterminate(window, "Apply Filters", "Counting matching messages...", _ => state.Db.Messages.Count(filter));
|
||||
|
||||
if (DatabaseToolFilterModeKeep) {
|
||||
if (DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Keep Matching Messages in This Database", messageCount.Pluralize("message") + " will be kept, and the rest will be removed from this database. This action cannot be undone. Proceed?")) {
|
||||
await ApplyFilterToDatabase(filter, FilterRemovalMode.KeepMatching);
|
||||
try {
|
||||
MessageFilter filter = FilterModel.CreateFilter();
|
||||
long messageCount = await ProgressDialog.ShowIndeterminate(window, "Apply Filters", "Counting matching messages...", _ => state.Db.Messages.Count(filter));
|
||||
|
||||
if (DatabaseToolFilterModeKeep) {
|
||||
if (DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Keep Matching Messages in This Database", messageCount.Pluralize("message") + " will be kept, and the rest will be removed from this database. This action cannot be undone. Proceed?")) {
|
||||
await ApplyFilterToDatabase(filter, FilterRemovalMode.KeepMatching);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (DatabaseToolFilterModeRemove) {
|
||||
if (DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Remove Matching Messages in This Database", messageCount.Pluralize("message") + " will be removed from this database. This action cannot be undone. Proceed?")) {
|
||||
await ApplyFilterToDatabase(filter, FilterRemovalMode.RemoveMatching);
|
||||
else if (DatabaseToolFilterModeRemove) {
|
||||
if (DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Remove Matching Messages in This Database", messageCount.Pluralize("message") + " will be removed from this database. This action cannot be undone. Proceed?")) {
|
||||
await ApplyFilterToDatabase(filter, FilterRemovalMode.RemoveMatching);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(window, "Apply Filters", "Could not apply filters: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -112,38 +112,32 @@ sealed partial class WelcomeScreenModel : ObservableObject {
|
||||
}
|
||||
|
||||
public async Task CheckUpdates() {
|
||||
var 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,
|
||||
string response;
|
||||
try {
|
||||
response = await ProgressDialog.ShowIndeterminate<string>(window, "Check Updates", "Checking for updates...", static 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);
|
||||
|
||||
return await client.GetStringAsync(Program.Website + "/version");
|
||||
});
|
||||
|
||||
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 Version? latestVersion)) {
|
||||
await Dialog.ShowOk(window, "Check Updates", "Server returned an invalid response.");
|
||||
return null;
|
||||
}
|
||||
|
||||
return latestVersion;
|
||||
});
|
||||
} catch (TaskCanceledException e) when (e.InnerException is TimeoutException) {
|
||||
await Dialog.ShowOk(window, "Check Updates", "Request timed out.");
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
await Dialog.ShowOk(window, "Check Updates", "Error checking for updates: " + e.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (latestVersion == null) {
|
||||
if (!System.Version.TryParse(response, out Version? latestVersion)) {
|
||||
await Dialog.ShowOk(window, "Check Updates", "Server returned an invalid response.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user