Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Fix recent email refresh duplicate calls (#167)
Leendert de Borst1de7f831b511
diff --git a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razorindex e41d885cf..10960df34 100644--- a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor+++ b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor@@ -113,71 +113,77 @@private const int ACTIVE_TAB_REFRESH_INTERVAL = 2000; // 2 seconds- private PeriodicTimer? _refreshTimer;- private CancellationTokenSource _cancellationTokenSource = new();+ private CancellationTokenSource? _pollingCts;+ private DotNetObjectReference<RecentEmails>? _dotNetRef;+ private bool _isPageVisible = true;/// <summary>/// Callback invoked by JavaScript when the page visibility changes. This is used to start/stop the polling for new emails./// </summary>/// <param name="isVisible">Indicates whether the page is visible or not.</param>[JSInvokable]- public async Task OnVisibilityChange(bool isVisible)+ public void OnVisibilityChange(bool isVisible){+ _isPageVisible = isVisible;+if (isVisible && DbService.Settings.AutoEmailRefresh){- await StartPolling();+ // Start polling if visible and auto-refresh is enabled+ StartPolling();}else{- await StopPolling();+ // Stop polling if hidden+ StopPolling();}-- // Refresh immediately when tab becomes visible++ // If becoming visible, do an immediate refreshif (isVisible){- await ManualRefresh();+ _ = ManualRefresh();}}- private async Task StartPolling()+ private void StartPolling()+ {+ // If already polling, no need to start again+ if (_pollingCts != null) {+ return;+ }++ _pollingCts = new CancellationTokenSource();++ // Start polling task+ _ = PollForEmails(_pollingCts.Token);+ }++ private void StopPolling()+ {+ if (_pollingCts != null)+ {+ _pollingCts.Cancel();+ _pollingCts.Dispose();+ _pollingCts = null;+ }+ }++ private async Task PollForEmails(CancellationToken cancellationToken){- await StopPolling();-- // Create a new CancellationTokenSource since the old one might have been cancelled- _cancellationTokenSource = new CancellationTokenSource();- _refreshTimer = new PeriodicTimer(TimeSpan.FromMilliseconds(ACTIVE_TAB_REFRESH_INTERVAL));-try{- while (await _refreshTimer.WaitForNextTickAsync(_cancellationTokenSource.Token))+ while (!cancellationToken.IsCancellationRequested){await LoadRecentEmailsAsync();+ await Task.Delay(ACTIVE_TAB_REFRESH_INTERVAL, cancellationToken);}}catch (OperationCanceledException){- // Normal cancellation, ignore- }- }-- private async Task StopPolling()- {- if (_refreshTimer is not null)- {- await _cancellationTokenSource.CancelAsync();- await Task.Delay(100); // Give time for the polling loop to complete- _refreshTimer.Dispose();- _refreshTimer = null;+ // Normal cancellation, ignore.}- }-- /// <inheritdoc />- public async ValueTask DisposeAsync()- {- if (_refreshTimer is not null)+ catch (Exception ex){- await StopPolling();- _cancellationTokenSource.Dispose();+ Logger.LogError(ex, "Error in email refresh polling");}}@@ -195,11 +201,28 @@ShowComponent = IsSpamOkDomain(EmailAddress) || IsAliasVaultDomain(EmailAddress);IsSpamOk = IsSpamOkDomain(EmailAddress);- await JsInteropService.RegisterVisibilityCallback(DotNetObjectReference.Create(this));+ // Create a single object reference for JS interop+ _dotNetRef = DotNetObjectReference.Create(this);+ await JsInteropService.RegisterVisibilityCallback(_dotNetRef);- if (DbService.Settings.AutoEmailRefresh)+ // Only start polling if auto-refresh is enabled and page is visible+ if (DbService.Settings.AutoEmailRefresh && _isPageVisible)+ {+ StartPolling();+ }+ }++ /// <inheritdoc />+ public async ValueTask DisposeAsync()+ {+ // Stop polling+ StopPolling();++ // Unregister the visibility callback using the same reference+ if (_dotNetRef != null){- await StartPolling();+ await JsInteropService.UnregisterVisibilityCallback(_dotNetRef);+ _dotNetRef.Dispose();}}diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.csindex bb3c0c081..2992c6def 100644--- a/src/AliasVault.Client/Services/JsInteropService.cs+++ b/src/AliasVault.Client/Services/JsInteropService.cs@@ -248,6 +248,16 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)where TComponent : class =>await jsRuntime.InvokeVoidAsync("window.registerVisibilityCallback", objRef);+ /// <summary>+ /// Unregisters the visibility callback to prevent memory leaks.+ /// </summary>+ /// <typeparam name="TComponent">Component type.</typeparam>+ /// <param name="objRef">DotNetObjectReference.</param>+ /// <returns>Task.</returns>+ public async Task UnregisterVisibilityCallback<TComponent>(DotNetObjectReference<TComponent> objRef)+ where TComponent : class =>+ await jsRuntime.InvokeVoidAsync("window.unregisterVisibilityCallback", objRef);+/// <summary>/// Symmetrically decrypts a byte array using the provided encryption key./// </summary>diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.jsindex e9ee0d83b..1c1d8f10e 100644--- a/src/AliasVault.Client/wwwroot/js/utilities.js+++ b/src/AliasVault.Client/wwwroot/js/utilities.js@@ -299,8 +299,39 @@ async function createWebAuthnCredentialAndDeriveKey(username) {}}+// Store the event listener references.+const visibilityChangeHandlers = new Map();++/**+ * Registers visibility callback that is invoked when the visibility state of the current page/tab changes.+ *+ * @param {any} dotnetHelper+ */window.registerVisibilityCallback = function (dotnetHelper) {- document.addEventListener("visibilitychange", function () {+ // Create a named function so we can reference it later for removal.+ const handler = function() {dotnetHelper.invokeMethodAsync('OnVisibilityChange', !document.hidden);- });+ };++ visibilityChangeHandlers.set(dotnetHelper, handler);+ document.addEventListener("visibilitychange", handler);++ // Initial call to set the correct initial state.+ dotnetHelper.invokeMethodAsync('OnVisibilityChange', !document.hidden);+};++/**+ * Unregisters any previously registered visibility callbacks to prevent memory leaks.+ *+ * @param {any} dotnetHelper+ */+window.unregisterVisibilityCallback = function (dotnetHelper) {+ // Get the stored handler.+ const handler = visibilityChangeHandlers.get(dotnetHelper);++ if (handler) {+ // Remove the event listener with the same function reference.+ document.removeEventListener("visibilitychange", handler);+ visibilityChangeHandlers.delete(dotnetHelper);+ }};