more reliable

This commit is contained in:
Paul Schneider 2026-08-23 18:34:34 +01:00
commit 426bc68d61
Signed by: notazof
GPG key ID: 1DD5D838E5343B06
26 changed files with 172 additions and 191 deletions

View file

@ -1,20 +1,36 @@
<Project>
<!-- Pull in shared package versions from the repository root. -->
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />
<Import
Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />
<!-- PostIt-product-specific versions -->
<ItemGroup>
<ItemGroup> <!-- Avalonia packages -->
<!-- Important: keep version in sync! -->
<PackageVersion Include="Avalonia" Version="12.1.1" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.1" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.1.1" />
<PackageVersion Include="Avalonia.Desktop" Version="12.1.1" />
<PackageVersion Include="Avalonia.Browser" Version="12.1.1" />
<PackageVersion Include="Avalonia.Android" Version="12.1.1" />
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="Xamarin.AndroidX.Core.SplashScreen" Version="1.0.1.15" />
<PackageVersion Include="Xamarin.AndroidX.Core.Core.KtX" Version="1.19.0.1" />
<PackageVersion Include="Xamarin.AndroidX.Compose.Runtime.Annotation.Jvm" Version="1.11.4" />
<PackageVersion Include="Xamarin.AndroidX.Core" Version="1.19.0.1" />
<PackageVersion Include="Xamarin.AndroidX.AppCompat" Version="1.7.1.4" />
<PackageVersion Include="Xamarin.AndroidX.Browser" Version="1.10.0.1" />
<PackageVersion Include="Xamarin.UITest.Core" Version="4.4.2" />
<PackageVersion Include="Xamarin.UITest.AndroidX" Version="4.4.2" />
<PackageVersion Include="Xamarin.UITest.Queries" Version="4.4.2" />
<PackageVersion Include="Xamarin.UITest" Version="4.4.2" />
<PackageVersion Include="Avalonia" Version="12.1.1" />
<PackageVersion Include="Avalonia.Headless" Version="12.1.1" />
<PackageVersion Include="Avalonia.Headless.Xunit" Version="12.1.1" />
<PackageVersion Include="Avalonia.Android" Version="12.1.1" />
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="12.0.0" />
<PackageVersion Include="Avalonia.Browser" Version="12.1.1" />
<PackageVersion Include="Avalonia.Desktop" Version="12.1.1" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.1.1" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.1" />
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="Material.Avalonia" Version="3.19.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
<PackageVersion Include="Microsoft.Maui.Essentials" Version="10.0.100" />

View file

@ -3,6 +3,9 @@ using Android.Content.PM;
using Android.Content;
using Avalonia.Android;
using AndroidX.Emoji2.Text;
using AndroidX.Core.Provider;
using Android;
using Android.Graphics;
namespace PostIt.Android;
@ -26,7 +29,6 @@ public class MainActivity : AvaloniaMainActivity
protected override void OnCreate(global::Android.OS.Bundle? savedInstanceState)
{
EmojiCompat.Init(this);
base.OnCreate(savedInstanceState);
PlatformBootstrap.EnsureInitialized();
Current = this;

View file

@ -1,34 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0-android</TargetFramework>
<!-- FORCE LES ARCHITECTURES ANDROID VALIDES -->
<RuntimeIdentifiers>android-arm64;android-x64</RuntimeIdentifiers>
<SupportedOSPlatformVersion>24.0.0</SupportedOSPlatformVersion>
<TargetFramework>net10.0-android</TargetFramework>
<SupportedOSPlatformVersion>23</SupportedOSPlatformVersion>
<Nullable>enable</Nullable>
<ApplicationId>fr.pschneider.PostIt</ApplicationId>
<ApplicationVersion>1</ApplicationVersion>
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<AndroidPackageFormat>apk</AndroidPackageFormat>
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
<RuntimeIdentifiers Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">android-arm;android-arm64;android-x64</RuntimeIdentifiers>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-beta.1+1.Branch.release-1.0.8-rc1.Sha.1167169aa89e1bf25290e9a152d27b357a500ab3</InformationalVersion>
<Version>1.1.0-beta.1</Version>
</PropertyGroup>
<ItemGroup>
<AndroidResource Include="Icon.png">
<Link>Resources\drawable\Icon.png</Link>
</AndroidResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Android" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Maui.Essentials" />
<PackageReference Include="Avalonia.Android" />
<PackageReference Include="Xamarin.AndroidX.Core.SplashScreen" />
<PackageReference Include="Avalonia.Browser" />
<PackageReference Include="Xamarin.AndroidX.Browser" />
<PackageReference Include="IdentityModel.OidcClient" />
</ItemGroup>
</Project>

View file

@ -5,6 +5,7 @@
</style>
<style name="MyTheme.NoActionBar" parent="@style/Theme.AppCompat.DayNight.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>

View file

@ -1,84 +0,0 @@
#if ANDROID || IOS
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Maui.ApplicationModel.Communication;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Devices;
using PostIt.Services;
using System.Linq;
namespace PostIt.Android.Services;
/// <summary>
/// Mobile implementation backed by MAUI Essentials
/// <c>Contacts.Default</c>.
///
/// <para>Compiled only for ANDROID and IOS. On desktop targets,
/// see <c>ContactService.Desktop.cs</c> (the stub that wins at
/// compile time).</para>
///
/// <para>Note: at runtime, this class throws
/// <c>NotImplementedInReferenceAssemblyException</c> unless
/// the host application project also references the
/// platform-specific Microsoft.Maui.Essentials implementation
/// (typically <c>PostIt.Android</c>). On iOS the same is
/// required via <c>PostIt.iOS</c>. On desktop the stub is used
/// and this file is excluded.</para>
/// </summary>
public sealed class ContactService : IContactService
{
public async Task<IReadOnlyList<ContactDto>> GetDeviceContactsAsync(CancellationToken ct = default)
{
if (DeviceInfo.Current.Platform == DevicePlatform.Unknown)
return Array.Empty<ContactDto>();
try
{
var status = await Permissions.RequestAsync<Permissions.ContactsRead>();
if (status != PermissionStatus.Granted)
return Array.Empty<ContactDto>();
var contacts = await Contacts.Default.GetAllAsync();
if (contacts is null) return Array.Empty<ContactDto>();
// Carry the per-contact email list as-is. A real
// device contact can carry several addresses (home /
// work / other); the UI use case ("invite / add to a
// circle") can then decide which address to use, or
// let the user pick. The platform-neutral ContactDto
// shape is intentionally richer than the Yavsc
// directory's single-Email shape — the two flows
// answer different questions.
var result = new List<ContactDto>(contacts.Count());
foreach (var c in contacts)
{
var emails = ExtractEmails(c.Emails);
result.Add(new ContactDto(
c.Id,
c.DisplayName ?? string.Empty,
emails));
}
return result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"ContactService: {ex.Message}");
return Array.Empty<ContactDto>();
}
}
private static IReadOnlyList<string> ExtractEmails(IEnumerable<ContactEmail>? emails)
{
if (emails is null) return Array.Empty<string>();
var list = new List<string>();
foreach (var e in emails)
{
if (!string.IsNullOrEmpty(e.EmailAddress))
list.Add(e.EmailAddress);
}
return list;
}
}
#endif

View file

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.WebAssembly">
<PropertyGroup>
<TargetFramework>net11.0-browser</TargetFramework>
<TargetFramework>net10.0-browser</TargetFramework>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>

View file

@ -3,7 +3,7 @@
<OutputType>WinExe</OutputType>
<!--If you are willing to use platform-specific APIs, use conditional compilation.
See https://docs.avaloniaui.net/docs/guides/platforms/platform-specific-code/dotnet for more details.-->
<TargetFramework>net11.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>

View file

@ -27,7 +27,7 @@ public partial class App : Application
/// <c>DataValidationErrors.SetErrors</c>.
/// </summary>
public IServiceProvider? ServiceProvider { get; private set; }
private MainWindow window;
public App()
{
}
@ -35,6 +35,9 @@ public partial class App : Application
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
#if DEBUG
this.AttachDeveloperTools();
#endif
}
public override void OnFrameworkInitializationCompleted()
@ -52,8 +55,6 @@ public partial class App : Application
this.ServiceProvider = BuildServices(new ServiceCollection());
AttachServiceProvider(ServiceProvider);
var settings = ServiceProvider.GetRequiredService<Settings>();
var sessionStatus = ServiceProvider.GetRequiredService<SessionStatusViewModel>();
var api = ServiceProvider.GetRequiredService<YavscApiClient>();
DataTemplates.Clear();
DataTemplates.Add(new ViewLocator(ServiceProvider));
@ -85,47 +86,44 @@ public partial class App : Application
}
};
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var homeVm = ServiceProvider.GetRequiredService<HomePageViewModel>();
window = new MainWindow();
window.SessionBanner.DataContext = sessionStatus;
// Build the navigation stack from scratch: HomePage is the
// root in both cases. App.BootAsync will push MainPage on
// top if the silent refresh succeeds.
desktop.MainWindow = window;
_ = PushPageAsync(homeVm);
// When the user logs out, route back to HomePage. We
// ReplaceAsync the current top so we don't grow the stack
// on every logout — otherwise repeated login/logout would
// eventually balloon the back history.
sessionStatus.LogoutCompleted += () =>
{
var w = (MainWindow)((IClassicDesktopStyleApplicationLifetime)ApplicationLifetime!).MainWindow!;
var nav = w.NavRoot;
_ = nav.PopToRootAsync();
};
// When the user signs in interactively (Login button on
// the session banner), push MainPage on top of HomePage.
sessionStatus.LoginSucceeded += () =>
{
var w = (MainWindow)((IClassicDesktopStyleApplicationLifetime)ApplicationLifetime!).MainWindow!;
_ = PushMainPageAsync();
};
window.Opened += async (_, _) => await BootAsync(this.ServiceProvider, api);
desktop.MainWindow = CreateMainWindow();
}
else if (ApplicationLifetime is ISingleViewApplicationLifetime singleView)
else if (ApplicationLifetime is IActivityApplicationLifetime singleViewFactoryApplicationLifetime)
{
singleView.MainView = new MainWindow
{
DataContext = ServiceProvider.GetRequiredService<HomePageViewModel>()
};
singleViewFactoryApplicationLifetime.MainViewFactory = () => CreateMainWindow();
}
else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
{
singleViewPlatform.MainView = CreateMainWindow();
}
base.OnFrameworkInitializationCompleted();
}
MainWindow window;
private MainWindow CreateMainWindow()
{
window = new MainWindow();
var api = ServiceProvider!.GetRequiredService<YavscApiClient>();
window.Opened += async (_, _) => await BootAsync(this.ServiceProvider!, api);
var sessionStatus = ServiceProvider!.GetRequiredService<SessionStatusViewModel>();
sessionStatus.LogoutCompleted += () =>
{
window.NavRoot.PopToRootAsync();
};
sessionStatus.LoginSucceeded += () =>
{
PushMainPageAsync();
};
var homeVm = ServiceProvider!.GetRequiredService<HomePageViewModel>();
this.PushPageAsync(homeVm).Wait();
window.SessionBanner.DataContext = sessionStatus;
return window;
}
/// <summary>
@ -156,7 +154,6 @@ public partial class App : Application
var contactService = new ContactService();
var userDirectory = new UserDirectory(userSearchClient);
// Vues
services.AddTransient<MainPage>();
// SettingsPage is a singleton: there must be one and only one
@ -268,8 +265,8 @@ public partial class App : Application
/// </summary>
public static Task PushMainPageAsync()
{
var app = (App)Current;
var mainVm = app.ServiceProvider.GetRequiredService<MainPageViewModel>();
var app = (App)Current!;
var mainVm = app.ServiceProvider!.GetRequiredService<MainPageViewModel>();
return app.PushPageAsync(mainVm);
}
@ -310,7 +307,7 @@ public partial class App : Application
_ = PushPageAsync(vm);
}
internal Task PushPageAsync(ViewModelBase vm)
internal async Task PushPageAsync(ViewModelBase vm)
{
if (window is null)
{
@ -344,10 +341,10 @@ public partial class App : Application
var stack = window.NavRoot.NavigationStack;
if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], page))
{
return Task.CompletedTask;
return;
}
return window.NavRoot.PushAsync(page);
await window.NavRoot.PushAsync(page);
}
internal async Task GoBackAsync()

View file

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>

View file

@ -21,6 +21,9 @@ public partial class AuthenticationSettings : ObservableObject
public static string DefaultAuthority { get; internal set; } = "https://yavsc.pschneider.fr";
public static string DefaultClientId { get; internal set; } = "postit";
public static string[] DefaultScopes { get; set; } = { "blogs"} ;
[ObservableProperty]
public partial string Authority { get; set; }

View file

@ -122,8 +122,8 @@ public partial class MainPageViewModel : ViewModelBase
public MainPageViewModel()
{
Init(null);
SettingsModel = new Settings();
Init(SettingsModel);
BlogClient = null;
}
@ -135,6 +135,11 @@ public partial class MainPageViewModel : ViewModelBase
SelectedPost = null;
IsBusy = false;
StatusMessage = "Ready";
Settings = settings ?? new Settings();
WindowTitle = "PostIt";
DraftTitle = string.Empty;
DraftArticle = string.Empty;
DraftIsPublished = false;
// Production path: DI injects the canonical Settings singleton
// and we use it as-is. Test path: tests call this constructor
// without a Settings argument; we fall back to a fresh
@ -145,11 +150,7 @@ public partial class MainPageViewModel : ViewModelBase
// sink; that crash is fixed in Settings.OnPropertyChanged
// (thread-safe dispatcher marshalling) so the duplicate
// instance is now merely wasteful, not dangerous.
Settings = settings ?? new Settings();
WindowTitle = "PostIt";
DraftTitle = string.Empty;
DraftArticle = string.Empty;
DraftIsPublished = false;
}
/// <summary>Save is enabled as soon as the user has typed
@ -174,7 +175,6 @@ public partial class MainPageViewModel : ViewModelBase
SettingsModel = new Settings();
BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient)); ;
Services = services;
Init(settings);
}
@ -210,7 +210,7 @@ public partial class MainPageViewModel : ViewModelBase
{
await ExecuteAsync(async () =>
{
var posts = await BlogClient.GetPostsAsync();
var posts = await BlogClient!.GetPostsAsync();
Posts.Clear();
foreach (var post in posts.OrderByDescending(p => p.DateModified))
{
@ -259,7 +259,7 @@ public partial class MainPageViewModel : ViewModelBase
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
};
var created = await BlogClient.CreatePostAsync(draft);
var created = await BlogClient!.CreatePostAsync(draft);
if (created is not null)
{
SelectedPost = created;
@ -278,7 +278,7 @@ public partial class MainPageViewModel : ViewModelBase
DateCreated = SelectedPost.DateCreated,
DateModified = DateTime.UtcNow,
};
await BlogClient.UpdatePostAsync(SelectedPost.Id, update);
await BlogClient!.UpdatePostAsync(SelectedPost.Id, update);
StatusMessage = $"Saved post {SelectedPost.Id}.";
}
@ -297,7 +297,7 @@ public partial class MainPageViewModel : ViewModelBase
await ExecuteAsync(async () =>
{
await BlogClient.DeletePostAsync(SelectedPost.Id);
await BlogClient!.DeletePostAsync(SelectedPost.Id);
StatusMessage = $"Deleted post {SelectedPost.Id}.";
SelectedPost = null;
await RefreshPostsAsync();
@ -331,7 +331,7 @@ public partial class MainPageViewModel : ViewModelBase
await ExecuteAsync(async () =>
{
var desired = !DraftIsPublished;
await BlogClient.SetPublishAsync(SelectedPost.Id, desired);
await BlogClient!.SetPublishAsync(SelectedPost.Id, desired);
DraftIsPublished = desired;
// Mirror into the selected post so a subsequent
// RefreshPostsAsync() doesn't blow away the
@ -372,7 +372,7 @@ public partial class MainPageViewModel : ViewModelBase
private async Task RefreshPostsAsync()
{
var posts = await BlogClient.GetPostsAsync();
var posts = await BlogClient!.GetPostsAsync();
Posts.Clear();
foreach (var post in posts.OrderByDescending(p => p.DateModified))
{

View file

@ -350,15 +350,14 @@ public partial class Settings : ViewModelBase
var settings = JsonSerializer.Deserialize<Settings>(json);
if (settings is null)
{
Console.Error.WriteLine($"🩎 Settings payload is invalid (source: {source}).");
return;
UseDefaultSettings();
}
// Apply under the gate so concurrent Load() callers cannot
// see half the new values / half the old ones. The actual
// PropertyChanged fan-out is handled by [ObservableProperty]'s
// setters which we route through SetProperty → OnPropertyChanged
// → our overridden dispatcher-safe marshaller below.
lock (_mutationGate)
else lock (_mutationGate)
{
this.Authentication = settings.Authentication;
this.DarkMode = settings.DarkMode;
@ -371,6 +370,11 @@ public partial class Settings : ViewModelBase
AuthenticationSettings.DefaultClientId : settings.Authentication.ClientId;
this.Authentication.RedirectUri = string.IsNullOrWhiteSpace(settings.Authentication.RedirectUri) ?
AuthenticationSettings.DefaultDesktopRedirectUri : settings.Authentication.RedirectUri;
if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0)
{
settings.Authentication.Scopes = AuthenticationSettings.DefaultScopes;
}
else
this.Authentication.Scopes = settings.Authentication.Scopes;
}
}
@ -400,6 +404,18 @@ public partial class Settings : ViewModelBase
}
}
private void UseDefaultSettings()
{
this.Authentication = new AuthenticationSettings
{
Authority = AuthenticationSettings.DefaultAuthority,
ClientId = AuthenticationSettings.DefaultClientId,
RedirectUri = AuthenticationSettings.DefaultDesktopRedirectUri,
Scopes = AuthenticationSettings.DefaultScopes
};
this.DarkMode = false;
}
/// <summary>
/// Persist the current in-memory state to
/// <c>~/.config/PostIt/postit-settings.json</c> (Linux) /