Files
Heimdall/src/Heimdall.Web/Components/Pages/Profile.razor
T
arnaud.dartois 89c4c43922
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 14m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 4m27s
Heimdall Gitea / Build and scan agent image (push) Successful in 15m42s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m27s
Heimdall Gitea / CI policy (push) Successful in 2s
fix(identity): harden user lifecycle and permissions (#136)
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-04 13:33:30 +01:00

739 lines
30 KiB
Plaintext

@page "/profile"
@attribute [Authorize]
@layout MainLayout
@implements IDisposable
@using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse
@using Complete2faSetupResponse = Heimdall.Application.DTOs.Complete2faSetupResponse
@inject HeimdallApiClient Api
@inject AuthState Auth
@inject UiLanguageService Language
@inject UiText Text
@inject ISnackbar Snackbar
@inject HeimdallAuthStateProvider AuthProvider
@inject IJSRuntime JS
<MudText Typo="Typo.h1" Class="mb-6">
<i class="fas fa-user-circle mr-2"></i>
@Text["Profile"]
</MudText>
@if (_loading)
{
<MudProgressCircular Indeterminate="true" />
}
else if (_error)
{
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
<MudText>@Text["ProfileLoadFailed"]</MudText>
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadProfile" Class="mt-2">
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> @Text["Retry"]
</MudButton>
</MudAlert>
}
else if (_profile is not null)
{
@* ─── Section 1: Informations personnelles ─── *@
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
<MudText Typo="Typo.h5" Class="mb-4">
<MudIcon Icon="@Icons.Material.Filled.Person" Class="mr-1" Size="Size.Small" />
@Text["PersonalInformation"]
</MudText>
@if (!string.IsNullOrEmpty(_profileError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_profileError</MudAlert>
}
<form @onsubmit="SaveProfile">
<MudTextField @bind-Value="_displayName" Label="@Text["DisplayName"]" Variant="Variant.Outlined"
Class="mb-4" Required="true" Immediate="true" />
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-1">@Text["Email"]</MudText>
<MudText Typo="Typo.body1" Class="mb-4">@_profile.Email</MudText>
<MudText Typo="Typo.body2" Class="mb-2">@Text["Theme"]</MudText>
<MudSelect @bind-Value="_theme" Label="@Text["Theme"]" Variant="Variant.Outlined" Class="mb-4">
<MudSelectItem Value="@("Auto")">@Text["Auto"]</MudSelectItem>
<MudSelectItem Value="@("Light")">@Text["Light"]</MudSelectItem>
<MudSelectItem Value="@("Dark")">@Text["Dark"]</MudSelectItem>
</MudSelect>
<MudText Typo="Typo.body2" Class="mb-2">@Text["Language"]</MudText>
<MudSelect @bind-Value="_language" Label="@Text["Language"]" Variant="Variant.Outlined" Class="mb-4">
<MudSelectItem Value="@("fr")">@Text["French"]</MudSelectItem>
<MudSelectItem Value="@("en")">@Text["English"]</MudSelectItem>
</MudSelect>
<MudButton Variant="Variant.Filled" Color="Color.Primary" ButtonType="ButtonType.Submit"
Disabled="@_saving" FullWidth="true">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
<MudIcon Icon="@Icons.Material.Filled.Save" Class="mr-1" /> @Text["Save"]
</MudButton>
</form>
</MudPaper>
@* ─── Section 2: Statistiques du compte ─── *@
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
<MudText Typo="Typo.h5" Class="mb-4">
<MudIcon Icon="@Icons.Material.Filled.BarChart" Class="mr-1" Size="Size.Small" />
@Text["Profile_AccountStatistics"]
</MudText>
<MudGrid>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["RegisteredAt"]</MudText>
<MudText Typo="Typo.body1" Class="mb-3">@_profile.CreatedAt.ToString("g", Language.Culture)</MudText>
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["EmailConfirmed"]</MudText>
<MudText Typo="Typo.body1" Class="mb-3">
<MudIcon Icon="@(_profile.EmailConfirmed ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
Color="@(_profile.EmailConfirmed ? Color.Success : Color.Default)" Size="Size.Small" />
@(_profile.EmailConfirmed ? Text["Yes"] : Text["No"])
</MudText>
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["TwoFactor"]</MudText>
<MudText Typo="Typo.body1" Class="mb-1">
<MudIcon Icon="@(_profile.TwoFactorEnabled ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
Color="@(_profile.TwoFactorEnabled ? Color.Success : Color.Default)" Size="Size.Small" />
@(_profile.TwoFactorEnabled ? Text["TwoFactorEnabled"] : Text["TwoFactorDisabled"])
</MudText>
@if (_profile.TwoFactorEnabled)
{
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" Class="mt-1"
OnClick="Disable2fa" Disabled="@_toggling2fa">
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
@Text["DisableTwoFactor"]
</MudButton>
@if (_confirmDisable2fa)
{
<MudTextField @bind-Value="_disable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
<MudButton Color="Color.Error" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmDisable2fa">@Text["ConfirmDisableTwoFactor"]</MudButton>
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelDisable2fa">@Text["Cancel"]</MudButton>
}
}
else
{
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small" Class="mt-1"
OnClick="Enable2fa" Disabled="@_toggling2fa">
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
@Text["EnableTwoFactor"]
</MudButton>
@if (_confirmEnable2fa)
{
<MudTextField @bind-Value="_enable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="StartEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelEnable2fa">@Text["Cancel"]</MudButton>
}
}
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["Roles"]</MudText>
<MudText Typo="Typo.body1" Class="mb-3">
@if (_profile.Roles is not null && _profile.Roles.Count > 0)
{
foreach (var r in _profile.Roles)
{
<MudText Typo="Typo.body2" Class="d-inline mr-1"
Color="@(r=="Admin"?Color.Tertiary:r=="Supervisor"?Color.Secondary:Color.Primary)">
@r
</MudText>
}
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["NoRoles"]</MudText>
}
</MudText>
</MudItem>
</MudGrid>
</MudPaper>
@* ─── Section 3: Changer le mot de passe ─── *@
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
<MudText Typo="Typo.h5" Class="mb-4">
<MudIcon Icon="@Icons.Material.Filled.Lock" Class="mr-1" Size="Size.Small" />
@Text["ChangePassword"]
</MudText>
@if (!string.IsNullOrEmpty(_passwordError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_passwordError</MudAlert>
}
<form @onsubmit="ChangePassword">
<MudTextField @bind-Value="_currentPassword" Label="@Text["CurrentPassword"]" Variant="Variant.Outlined"
InputType="InputType.Password" Class="mb-4" Required="true" Immediate="true"
Autocomplete="current-password" />
<MudTextField @bind-Value="_newPassword" Label="@Text["NewPassword"]" Variant="Variant.Outlined"
InputType="InputType.Password" Class="mb-4" Required="true" Immediate="true"
HelperText="@Text["PasswordMinimum"]"
Autocomplete="new-password" />
<MudTextField @bind-Value="_confirmPassword" Label="@Text["ConfirmPassword"]" Variant="Variant.Outlined"
InputType="InputType.Password" Class="mb-4" Required="true" Immediate="true"
Autocomplete="new-password" />
<MudButton Variant="Variant.Filled" Color="Color.Warning" ButtonType="ButtonType.Submit"
Disabled="@_changingPassword" FullWidth="true">
@if (_changingPassword) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
<MudIcon Icon="@Icons.Material.Filled.LockReset" Class="mr-1" /> @Text["ChangePassword"]
</MudButton>
</form>
</MudPaper>
@* ─── Section 4: Notifications ─── *@
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
<MudText Typo="Typo.h5" Class="mb-4">
<MudIcon Icon="@Icons.Material.Filled.Notifications" Class="mr-1" Size="Size.Small" />
@Text["Notifications"]
</MudText>
@if (!string.IsNullOrEmpty(_notifError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_notifError</MudAlert>
}
<MudAlert Severity="Severity.Info" Class="mb-4" Variant="Variant.Outlined">
<MudText Typo="Typo.body2" Class="mb-1">
@Text["PushSetupInstructions"]
</MudText>
<MudText Typo="Typo.body2" Class="mb-1">
<strong>@Text["YourTopic"]</strong> <code>@(!string.IsNullOrWhiteSpace(_ntfyTopic) ? _ntfyTopic : $"heimdall_{_profile?.Id}")</code>
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">
@Text["CustomizeTopic"]
</MudText>
</MudAlert>
<MudForm @ref="_notifForm">
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-4">@Text["EmailChannel"]</MudText>
<MudSwitch @bind-Value="_emailEnabled" Label="@Text["EmailNotifications"]" Color="Color.Primary" Class="mb-2" />
<MudTextField @bind-Value="_emailAddress" Label="@Text["NotificationEmailAddress"]"
Variant="Variant.Outlined" Class="mb-4" Disabled="@(!_emailEnabled)"
Placeholder="@Text["NotificationEmailPlaceholder"]" />
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-4">@Text["PushChannel"]</MudText>
<MudSwitch @bind-Value="_ntfyEnabled" Label="@Text["PushNotifications"]" Color="Color.Secondary" Class="mb-2" />
<MudTextField @bind-Value="_ntfyUrl" Label="@Text["NtfyServerUrl"]"
Variant="Variant.Outlined" Class="mb-4" Disabled="@(!_ntfyEnabled)"
Placeholder="@Text["DefaultNtfyUrl"]" HelperText="@Text["UseGlobalServer"]" />
<MudTextField @bind-Value="_ntfyTopic" Label="@Text["NtfyTopicOptional"]"
Variant="Variant.Outlined" Class="mb-4" Disabled="@(!_ntfyEnabled)"
Placeholder="@($"heimdall_{_profile?.Id}")"
HelperText="@Text["CustomizeTopicHelper"]" />
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-4">@Text["Summaries"]</MudText>
<MudSwitch @bind-Value="_dailyDigest" Label="@Text["DailySummary"]" Color="Color.Tertiary" Class="mb-2" />
<MudSwitch @bind-Value="_weeklyDigest" Label="@Text["WeeklySummary"]" Color="Color.Tertiary" Class="mb-4" />
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-4">@Text["EventTypes"]</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">
@Text["SelectNotificationEventTypes"] @Text["AllEventsIfNone"]
</MudText>
<MudGrid Class="mb-4">
@foreach (var et in EventTypes)
{
<MudItem xs="12" sm="6">
<MudCheckBox T="bool"
Value="@_subscribedEvents.Contains(et.Value)"
ValueChanged="@((bool val) => ToggleEventType(et.Value, val))"
Label="@et.Label"
Color="Color.Primary"
Dense="true" />
</MudItem>
}
</MudGrid>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@SaveNotificationConfig"
Disabled="@_savingNotif" FullWidth="true">
@if (_savingNotif) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
<MudIcon Icon="@Icons.Material.Filled.Save" Class="mr-1" /> @Text["Save"]
</MudButton>
<div class="d-flex align-center mt-3">
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Send"
OnClick="TestNtfyForUserAsync" Disabled="@(_testingNtfy || !_ntfyEnabled)">
@(_testingNtfy ? Text["TestRunning"] : Text["TestNtfy"])
</MudButton>
</div>
@if (_ntfyTestResult is not null)
{
<MudAlert Severity="@(_ntfyTestResult.Success ? Severity.Success : Severity.Error)" Class="mt-3" Variant="Variant.Outlined">
@_ntfyTestResult.Message
</MudAlert>
}
</MudForm>
</MudPaper>
}
@* ─── Dialog d'enrôlement 2FA (QR + codes de récupération) ─── *@
<MudOverlay Visible="@_show2faDialog" OnClick="@(() => _show2faDialog = false)" />
<MudDialog @bind-Visible="_show2faDialog" Options="new DialogOptions { MaxWidth = MaxWidth.Medium, FullWidth = true }">
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Security" Class="mr-1" Size="Size.Small" />
@Text["EnableTwoFactor"]
</MudText>
</TitleContent>
<DialogContent>
@if (_2faError is not null)
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_2faError</MudAlert>
}
else if (_2faSetup is not null)
{
<MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
<MudText Typo="Typo.body2" Class="mb-1">
@Text["ScanQrInstructions"]
</MudText>
<MudText Typo="Typo.body2" Class="mb-1">
<strong>@Text["TwoFactorKey"]</strong> <code>@_2faSetup.SharedKey</code>
</MudText>
@if (!string.IsNullOrEmpty(_2faSetup.QrCodeUri))
{
<MudText Typo="Typo.caption" Color="Color.Secondary">
@Text["SetupLink"] <a href="@_2faSetup.QrCodeUri" target="_blank">@Text["OpenInApp"]</a>
</MudText>
}
</MudAlert>
@if (_completed2faSetup is { RecoveryCodes.Count: > 0 })
{
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mb-2">
<MudText Typo="Typo.body2" Class="mb-1">
<strong>@Text["RecoveryCodes"]</strong> — @Text["KeepRecoveryCodes"]
@Text["RecoveryCodesInstructions"] @Text["RecoveryCodeOneUse"]
</MudText>
</MudAlert>
<MudPaper Elevation="0" Class="pa-3 mb-4" Style="border: 1px dashed #f0ad4e; border-radius: 8px;">
<div class="d-flex flex-wrap">
@foreach (var rc in _completed2faSetup.RecoveryCodes)
{
<MudText Typo="Typo.subtitle1" Class="d-inline mr-4 mb-2" Style="font-family: monospace;">
@rc
</MudText>
}
</div>
</MudPaper>
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label='@Text["RecoveryCodesSaved"]' Class="mb-2" />
}
else
{
<MudTextField @bind-Value="_authenticatorCode" Label='@Text["AuthenticatorCode"]' Variant="Variant.Outlined" />
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
}
}
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="Close2faDialog" Disabled="@(_completed2faSetup is not null && !_recoveryCodesConfirmed)">@Text["Close"]</MudButton>
</DialogActions>
</MudDialog>
@code {
private UserItem? _profile;
private bool _loading = true;
private bool _error;
private bool _saving;
private bool _changingPassword;
// Section 1 — Informations personnelles
private string _displayName = "";
private string _theme = "Auto";
private string _language = "fr";
private string _profileError = "";
// Section 3 — Changer le mot de passe
private string _currentPassword = "";
private string _newPassword = "";
private string _confirmPassword = "";
private string _passwordError = "";
// Section 2FA
private bool _toggling2fa;
private bool _confirmDisable2fa;
private string _disable2faPassword = "";
private bool _confirmEnable2fa;
private string _enable2faPassword = "";
private bool _show2faDialog;
private Enable2faResponse? _2faSetup;
private Complete2faSetupResponse? _completed2faSetup;
private string _authenticatorCode = "";
private string? _2faError;
private bool _recoveryCodesConfirmed;
protected override async Task OnInitializedAsync()
{
Language.LanguageChanged += OnLanguageChanged;
await LoadProfile();
await LoadNotificationConfig();
}
private async Task LoadProfile()
{
_loading = true;
_error = false;
try
{
var result = await Api.GetMyProfileAsync();
if (result is not null)
{
_profile = result;
_displayName = result.DisplayName;
_theme = result.Theme ?? "Auto";
_language = UiLanguageService.Normalize(result.Language);
Language.SetLanguage(_language);
}
}
catch {
_error = true;
Snackbar.Add(Text["OperationFailed"], Severity.Error);
}
finally { _loading = false; }
}
// ─── Section 1: Enregistrer le profil ─────────────────────────
private async Task SaveProfile()
{
if (string.IsNullOrWhiteSpace(_displayName))
{
_profileError = Text["DisplayNameRequired"];
return;
}
_saving = true;
_profileError = "";
try
{
var success = await Api.UpdateMyProfileAsync(_displayName.Trim(), _theme, _language);
if (success)
{
_language = UiLanguageService.Normalize(_language);
Language.SetLanguage(_language);
try { await JS.InvokeVoidAsync("heimdallLocalization.setLanguage", _language); }
catch (JSException) { /* The saved preference still applies to this circuit. */ }
Snackbar.Add(Text["ProfileUpdated"], Severity.Success);
}
else
{
_profileError = Text["ProfileUpdateFailed"];
}
}
catch {
_profileError = Text["OperationFailed"];
}
finally { _saving = false; }
}
// ─── Section 3: Changer le mot de passe ───────────────────────
private Task Enable2fa()
{
_confirmEnable2fa = true;
return Task.CompletedTask;
}
private void CancelEnable2fa()
{
_confirmEnable2fa = false;
_enable2faPassword = "";
}
private async Task StartEnable2fa()
{
_toggling2fa = true;
_2faError = null;
_2faSetup = null;
_completed2faSetup = null;
_authenticatorCode = "";
_recoveryCodesConfirmed = false;
var currentPassword = _enable2faPassword;
_confirmEnable2fa = false;
try
{
var setup = await Api.Enable2faAsync(currentPassword);
if (setup is null)
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
return;
}
// ResetAuthenticatorKeyAsync rotates the security stamp. Reissue both
// the Blazor token state and middleware cookie before confirming setup.
var renewedSession = await Api.LoginAsync(_profile!.Email, currentPassword);
if (renewedSession is null || string.IsNullOrEmpty(renewedSession.AccessToken))
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
return;
}
await AuthProvider.NotifyLoginAsync(renewedSession);
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
return;
}
_2faSetup = setup;
_show2faDialog = true;
}
catch
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
}
finally
{
_enable2faPassword = "";
_toggling2fa = false;
await LoadProfile();
}
}
private void Close2faDialog()
{
_show2faDialog = false;
_2faSetup = null;
_completed2faSetup = null;
_authenticatorCode = "";
_recoveryCodesConfirmed = false;
}
private async Task ConfirmEnable2fa()
{
_toggling2fa = true;
try
{
var completed = await Api.ConfirmEnable2faAsync(_authenticatorCode);
if (completed is null)
{
_2faError = "Code invalide ou activation impossible";
return;
}
_completed2faSetup = completed;
_2faError = null;
}
catch { _2faError = Text["OperationFailed"]; }
finally { _toggling2fa = false; await LoadProfile(); }
}
private Task Disable2fa()
{
_confirmDisable2fa = true;
return Task.CompletedTask;
}
private void CancelDisable2fa()
{
_confirmDisable2fa = false;
_disable2faPassword = "";
}
private async Task ConfirmDisable2fa()
{
_toggling2fa = true;
var disabled = false;
try
{
var ok = await Api.Disable2faAsync(_disable2faPassword);
disabled = ok;
if (ok)
{
Snackbar.Add(Text["TwoFactorDisabled"], Severity.Success);
}
else
{
Snackbar.Add(Text["TwoFactorDisableFailed"], Severity.Error);
}
}
catch
{
Snackbar.Add(Text["OperationFailed"], Severity.Error);
}
finally
{
_toggling2fa = false;
if (disabled) CancelDisable2fa();
await LoadProfile();
}
}
private async Task ChangePassword()
{
if (string.IsNullOrWhiteSpace(_currentPassword))
{
_passwordError = Text["CurrentPasswordRequired"];
return;
}
if (string.IsNullOrWhiteSpace(_newPassword))
{
_passwordError = Text["NewPasswordRequired"];
return;
}
if (_newPassword.Length < 12)
{
_passwordError = Text["PasswordTooShort"];
return;
}
if (_newPassword != _confirmPassword)
{
_passwordError = Text["PasswordsMismatch"];
return;
}
_changingPassword = true;
_passwordError = "";
try
{
var success = await Api.ChangePasswordAsync(_currentPassword, _newPassword);
if (success)
{
_currentPassword = "";
_newPassword = "";
_confirmPassword = "";
Snackbar.Add(Text["PasswordChanged"], Severity.Success);
}
else
{
_passwordError = Text["PasswordChangeFailed"];
}
}
catch {
_passwordError = Text["OperationFailed"];
}
finally { _changingPassword = false; }
}
// ─── Section 4: Notifications ─────────────────────────────────
private NotificationConfigItem? _notifConfig;
private MudForm? _notifForm;
private bool _emailEnabled;
private string? _emailAddress;
private bool _ntfyEnabled;
private string? _ntfyUrl;
private string? _ntfyTopic;
private bool _dailyDigest;
private bool _weeklyDigest;
private bool _savingNotif;
private string _notifError = "";
private bool _testingNtfy;
private TestActionResult? _ntfyTestResult;
// Event type subscription checkboxes
private IReadOnlyList<EventTypeOption> EventTypes =>
[
new("MotionDetected", Text["MotionDetected"], Icons.Material.Filled.NearMe),
new("PersonDetected", Text["PersonDetected"], Icons.Material.Filled.Person),
new("VehicleDetected", Text["VehicleDetected"], Icons.Material.Filled.DirectionsCar),
new("UnknownPerson", Text["UnknownPerson"], Icons.Material.Filled.HelpOutline),
new("FaceRecognized", Text["FaceRecognized"], Icons.Material.Filled.Face),
new("LicensePlateDetected", Text["LicensePlateDetected"], Icons.Material.Filled.Pin),
new("CameraOffline", Text["CameraOffline"], Icons.Material.Filled.VideocamOff),
new("CameraOnline", Text["CameraOnline"], Icons.Material.Filled.Videocam),
];
private HashSet<string> _subscribedEvents = new();
private sealed record EventTypeOption(string Value, string Label, string Icon);
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
public void Dispose() => Language.LanguageChanged -= OnLanguageChanged;
private void ToggleEventType(string value, bool selected)
{
if (selected)
_subscribedEvents.Add(value);
else
_subscribedEvents.Remove(value);
}
private async Task LoadNotificationConfig()
{
try
{
_notifConfig = await Api.GetNotificationConfigAsync();
if (_notifConfig is not null)
{
_emailEnabled = _notifConfig.EmailEnabled;
_emailAddress = _notifConfig.EmailAddress;
_ntfyEnabled = _notifConfig.NtfyEnabled;
_ntfyUrl = _notifConfig.NtfyUrl;
_ntfyTopic = _notifConfig.NtfyTopic;
_dailyDigest = _notifConfig.DailyDigest;
_weeklyDigest = _notifConfig.WeeklyDigest;
_subscribedEvents = _notifConfig.SubscribedEvents is not null
? new HashSet<string>(_notifConfig.SubscribedEvents)
: new HashSet<string>();
}
}
catch (Exception)
{
_notifError = Text["NotificationConfigLoadFailed"];
}
}
private async Task SaveNotificationConfig()
{
_savingNotif = true;
_notifError = "";
try
{
var request = new UpdateNotificationConfigRequest(
_emailEnabled,
string.IsNullOrWhiteSpace(_emailAddress) ? null : _emailAddress.Trim(),
_ntfyEnabled,
string.IsNullOrWhiteSpace(_ntfyUrl) ? null : _ntfyUrl.Trim(),
string.IsNullOrWhiteSpace(_ntfyTopic) ? null : _ntfyTopic.Trim(),
_dailyDigest,
_weeklyDigest,
_subscribedEvents.Count > 0 ? _subscribedEvents.ToList() : null,
Language: UiLanguageService.Normalize(_language)
);
var success = await Api.UpdateNotificationConfigAsync(request);
if (success)
{
Snackbar.Add(Text["NotificationConfigUpdated"], Severity.Success);
}
else
{
_notifError = Text["NotificationConfigUpdateFailed"];
}
}
catch {
_notifError = Text["OperationFailed"];
}
finally { _savingNotif = false; }
}
private string? ResolveNtfyTopic()
{
if (!string.IsNullOrWhiteSpace(_ntfyTopic))
return _ntfyTopic.Trim();
return _profile is not null ? $"heimdall_{_profile.Id}" : null;
}
private async Task TestNtfyForUserAsync()
{
_testingNtfy = true;
_ntfyTestResult = null;
try
{
var topic = ResolveNtfyTopic();
var baseUrl = string.IsNullOrWhiteSpace(_ntfyUrl) ? null : _ntfyUrl.Trim();
_ntfyTestResult = await Api.TestNtfyAsync(topic, baseUrl)
?? new TestActionResult(false, Text["TestUnavailable"]);
}
catch (Exception)
{
_ntfyTestResult = new TestActionResult(false, Text["OperationFailed"]);
}
finally
{
_testingNtfy = false;
}
}
}