Files
Libation/Source/LibationWinForms/Form1._NonUI.cs
T
Cursor Agentandrmcrackan 813b5eeb6e Guard BackgroundWorker e.Result behind e.Error/e.Cancelled to prevent startup crashes
Reading RunWorkerCompletedEventArgs.Result rethrows any exception from the
count DoWork. In the Avalonia async void handler this became an unhandled
exception that killed the app during library load (issue #1931). Check
e.Cancelled/e.Error first, log once, and degrade to empty stats in both the
Avalonia and WinForms backup-count completion handlers.

Co-authored-by: rmcrackan <rmcrackan@gmail.com>
2026-08-12 18:05:36 +00:00

115 lines
3.7 KiB
C#

using ApplicationServices;
using AudibleUtilities;
using Dinah.Core.Threading;
using Dinah.Core.WindowsDesktop.Drawing;
using FileManager;
using LibationFileManager;
using LibationUiBase;
using System.Windows.Forms;
namespace LibationWinForms;
public partial class Form1
{
private void Configure_NonUI()
{
AudibleApiStorage.LoadError += AudibleApiStorage_LoadError;
// init default/placeholder cover art
var format = System.Drawing.Imaging.ImageFormat.Jpeg;
PictureStorage.SetDefaultImage(PictureSize._80x80, Properties.Resources.default_cover_80x80.ToBytes(format));
PictureStorage.SetDefaultImage(PictureSize._300x300, Properties.Resources.default_cover_300x300.ToBytes(format));
PictureStorage.SetDefaultImage(PictureSize._500x500, Properties.Resources.default_cover_500x500.ToBytes(format));
PictureStorage.SetDefaultImage(PictureSize.Native, Properties.Resources.default_cover_500x500.ToBytes(format));
BaseUtil.SetLoadImageDelegate(WinFormsUtil.TryLoadImageOrDefault);
BaseUtil.SetLoadResourceImageDelegate(LoadResourceImage);
// wire-up event to automatically download after scan.
// winforms only. this should NOT be allowed in cli
updateCountsBw.RunWorkerCompleted += (_, e) => tryAutoDownloadAfterCounts(e);
}
private void tryAutoDownloadAfterCounts(System.ComponentModel.RunWorkerCompletedEventArgs e)
{
// Guard e.Cancelled/e.Error before reading e.Result: e.Result rethrows a faulted count,
// which here (a RunWorkerCompleted handler) would become an unhandled exception.
if (!Configuration.Instance.AutoDownloadEpisodes || e.Cancelled || e.Error is not null)
return;
if (e.Result is not LibraryCommands.LibraryStats libraryStats)
return;
if (libraryStats.PendingBooks + libraryStats.pdfsNotDownloaded <= 0)
return;
// RunWorkerCompleted has no SynchronizationContext; queue items require the UI thread.
this.UIThreadAsync(() => _ = BackupAllBooksAsync(libraryStats.LibraryBooks));
}
private static object? LoadResourceImage(string resourceName)
{
if (Application.IsDarkModeEnabled)
resourceName += "_dark";
return Properties.Resources.ResourceManager.GetObject(resourceName);
}
private void AudibleApiStorage_LoadError(object? sender, AccountSettingsLoadErrorEventArgs e)
{
try
{
//Backup AccountSettings.json and create a new, empty file.
var backupFile =
FileUtility.SaferMoveToValidPath(
e.SettingsFilePath,
e.SettingsFilePath,
Configuration.Instance.ReplacementCharacters,
"bak");
AudibleApiStorage.EnsureAccountsSettingsFileExists();
e.Handled = true;
showAccountSettingsRecoveredMessage(backupFile);
}
catch
{
showAccountSettingsUnrecoveredMessage();
}
void showAccountSettingsRecoveredMessage(LongPath backupFile)
{
var ex = e.GetException();
var body = AccountSettingsDecryptFailure.TryFindInTree(ex, out _)
? AccountSettingsDecryptFailure.GetRecoveredDialogBody(ex, backupFile.PathWithoutPrefix)
: $"""
Libation could not load your account settings, so it had created a new, empty account settings file.
You will need to re-add you Audible account(s) before scanning or downloading.
The old account settings file has been archived at '{backupFile.PathWithoutPrefix}'
{ex}
""";
MessageBox.Show(
this,
body,
AccountSettingsDecryptFailure.LoadErrorCaption,
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
void showAccountSettingsUnrecoveredMessage()
=> MessageBox.Show(this, $"""
Libation could not load your account settings. The file may be corrupted, but Libation is unable to delete it.
Please move or delete the account settings file '{e.SettingsFilePath}'
{e.GetException().ToString()}
""",
"Error Loading Account Settings",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}