Files
replicate.maui/Test.Replicate/Services/AppSettings.cs
2025-12-10 21:59:12 -05:00

117 lines
3.2 KiB
C#

namespace Test.Replicate.Services
{
/// <summary>
/// Shared application settings service for storing API configuration.
/// Uses SecureStorage for sensitive data like API tokens.
/// </summary>
public class AppSettings
{
private const string ApiTokenKey = "replicate_api_token";
private string _apiToken = string.Empty;
private bool _isLoaded;
/// <summary>
/// The Replicate API token.
/// </summary>
public string ApiToken
{
get => _apiToken;
set
{
if (_apiToken != value)
{
_apiToken = value;
_ = SaveTokenAsync(value);
}
}
}
/// <summary>
/// Whether the API token has been configured.
/// </summary>
public bool IsConfigured => !string.IsNullOrEmpty(ApiToken);
/// <summary>
/// Raised when settings change.
/// </summary>
public event Action? SettingsChanged;
/// <summary>
/// Notify listeners that settings have changed.
/// </summary>
public void NotifySettingsChanged() => SettingsChanged?.Invoke();
/// <summary>
/// Load the API token from secure storage.
/// Call this on app startup.
/// </summary>
public async Task LoadAsync()
{
if (_isLoaded)
return;
try
{
var token = await SecureStorage.Default.GetAsync(ApiTokenKey);
if (!string.IsNullOrEmpty(token))
{
_apiToken = token;
}
}
catch (Exception)
{
// SecureStorage may not be available on all platforms/emulators
// Fall back to preferences
_apiToken = Preferences.Default.Get(ApiTokenKey, string.Empty);
}
_isLoaded = true;
}
private async Task SaveTokenAsync(string token)
{
try
{
if (string.IsNullOrEmpty(token))
{
SecureStorage.Default.Remove(ApiTokenKey);
}
else
{
await SecureStorage.Default.SetAsync(ApiTokenKey, token);
}
}
catch (Exception)
{
// SecureStorage may not be available on all platforms/emulators
// Fall back to preferences
if (string.IsNullOrEmpty(token))
{
Preferences.Default.Remove(ApiTokenKey);
}
else
{
Preferences.Default.Set(ApiTokenKey, token);
}
}
}
/// <summary>
/// Clear the stored API token.
/// </summary>
public async Task ClearTokenAsync()
{
_apiToken = string.Empty;
try
{
SecureStorage.Default.Remove(ApiTokenKey);
}
catch
{
Preferences.Default.Remove(ApiTokenKey);
}
NotifySettingsChanged();
}
}
}