diff --git a/Directory.Packages.props b/Directory.Packages.props
index 84380e44..e4b09159 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -18,7 +18,6 @@
-
diff --git a/contrib/Makefile b/contrib/Makefile
index 151045db..62e1e22d 100644
--- a/contrib/Makefile
+++ b/contrib/Makefile
@@ -1,4 +1,4 @@
-APP_PROJECT_NAMES=Org Blogs
+APP_PROJECT_NAMES=Api Org Blogs
SLNDIR=..
include $(SLNDIR)/.env
@@ -7,6 +7,7 @@ include .env
generated/:
@mkdir -p $@
+generated/yavscApi.service:
generated/yavscOrg.service:
generated/yavscBlogs.service:
@@ -33,11 +34,12 @@ generated/yavsc%.service: generated/ template.service $(SLNDIR)/.env
@echo Created service file: $@
-copy-services: copy-service-Org copy-service-Blogs
+copy-services: copy-service-Org copy-service-Api copy-service-Blogs
copy-service-Org: /etc/systemd/system/yavscOrg.service
+copy-service-Api: /etc/systemd/system/yavscApi.service
copy-service-Blogs: /etc/systemd/system/yavscBlogs.service
-copy-binaries: build_publish_Org build_publish_Blogs stop-services
+copy-binaries: build_publish_Org build_publish_Api build_publish_Blogs stop-services
@for project in $(APP_PROJECT_NAMES); \
do LCAPI=$$(echo $${project}|tr [:upper:] [:lower:]) ; \
echo "$${project} -> $${LCAPI}" ; \
@@ -53,7 +55,7 @@ copy-binaries: build_publish_Org build_publish_Blogs stop-services
done
@sudo chown -R $(USER_AND_GROUP) $(BASEAPPDIR)
-/etc/systemd/system/yavsc%.service: generated/yavsc%.service
+/etc/systemd/system/yavsc%.service: generated/yavsc%.service
sudo cp $^ $@
sudo chown root:root $@
@@ -63,14 +65,14 @@ build_publish_%: clean_publish_dir_%
clean_publish_dir_%:
@rm -rf $(SLNDIR)/src/Yavsc.$*/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish
-install: build_publish copy-binaries copy-services
+install: build_publish copy-binaries copy-services
@sudo systemctl daemon-reload
@for project in $(APP_PROJECT_NAMES); \
do \
sudo systemctl enable yavsc$${project} ; \
sudo systemctl start yavsc$${project} ; \
done
-
+
reinstall: copy-binaries
@sync
@for project in $(APP_PROJECT_NAMES); do \
@@ -84,12 +86,13 @@ stop-services:
$(SLNDIR)/src/Yavsc.Org/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish
$(SLNDIR)/src/Yavsc.Blogs/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish
+$(SLNDIR)/src/Yavsc.Api/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish
-showConfig:
+showConfig:
@echo CONFIGURATION: $(CONFIGURATION)
@echo BASEAPPDIR: $(BASEAPPDIR)
clean:
@rm -rf generated
-.PHONY: build_publish mep showConfig copy-service-Org copy-service-Blogs reinstall clean
+.PHONY: build_publish mep showConfig copy-service-Api copy-service-Org copy-service-Blogs reinstall clean
diff --git a/src/PostIt.Tests/Auth/BearerScopeTests.cs b/src/PostIt.Tests/BearerScopeTests.cs
similarity index 100%
rename from src/PostIt.Tests/Auth/BearerScopeTests.cs
rename to src/PostIt.Tests/BearerScopeTests.cs
diff --git a/src/PostIt.Tests/Blogs/BlogApiTestFakes.cs b/src/PostIt.Tests/BlogApiTestFakes.cs
similarity index 72%
rename from src/PostIt.Tests/Blogs/BlogApiTestFakes.cs
rename to src/PostIt.Tests/BlogApiTestFakes.cs
index 755d56ae..4b541e42 100644
--- a/src/PostIt.Tests/Blogs/BlogApiTestFakes.cs
+++ b/src/PostIt.Tests/BlogApiTestFakes.cs
@@ -64,29 +64,3 @@ internal sealed class RecordingYavscApiClient : YavscApiClient
return Task.FromResult(default(T)!);
}
}
-
-///
-/// stand-in whose constructor
-/// points at https://stub.invalid so any HTTP traffic
-/// that escapes a test (misconfigured command, missing fake
-/// handler) raises a clear
-/// instead of silently hitting a real endpoint. Used by tests
-/// that don't actually exercise the API client (they click a
-/// button, assert on the nav stack, end of story) but whose
-/// VMs require one in their constructor.
-///
-internal sealed class ThrowingApi : YavscApiClient
-{
- public ThrowingApi() : base(
- new Settings
- {
- Authentication = new AuthenticationSettings
- {
- Authority = "https://stub.invalid",
- ClientId = "stub",
- Scopes = new[] { "openid" },
- },
- },
- new TokenStore(System.IO.Path.GetTempFileName()))
- { }
-}
diff --git a/src/PostIt.Tests/Blogs/BlogPostAuthorDtoTests.cs b/src/PostIt.Tests/BlogPostAuthorDtoTests.cs
similarity index 100%
rename from src/PostIt.Tests/Blogs/BlogPostAuthorDtoTests.cs
rename to src/PostIt.Tests/BlogPostAuthorDtoTests.cs
diff --git a/src/PostIt.Tests/Blogs/AddCircleMemberDialogTests.cs b/src/PostIt.Tests/Blogs/AddCircleMemberDialogTests.cs
deleted file mode 100644
index 71b21278..00000000
--- a/src/PostIt.Tests/Blogs/AddCircleMemberDialogTests.cs
+++ /dev/null
@@ -1,145 +0,0 @@
-
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Headless.XUnit;
-using Microsoft.Extensions.DependencyInjection;
-using PostIt.Services;
-using PostIt.ViewModels;
-using PostIt.Views;
-using Yavsc.Api.Client;
-
-namespace PostIt.Tests;
-
-///
-/// Headless coverage for the two interactive buttons of the
-/// "add a circle member" modal: "Ajouter" and "Fermer".
-///
-/// The dialog is pushed on top of
-/// via the canonical App.PushPageAsync pipeline (the
-/// same path CirclesPageViewModel.OpenAddMemberAsync
-/// uses). The test asserts on NavRoot.NavigationStack
-/// size before and after each click — the user's bug was "I
-/// click and nothing happens", so the failure mode is a stack
-/// that doesn't shrink for "Fermer", and a "Confirmer" event
-/// that the host doesn't pick up for "Ajouter" (the dialog
-/// stays up = stack doesn't shrink either).
-///
-/// Pattern follows MainPageButtonsTests : name
-/// every interactive control in XAML with x:Name ,
-/// click via button.Command?.Execute(...) + flush
-/// any async command before asserting.
-///
-[Collection("PostIt Headless")]
-public class AddCircleMemberDialogTests
-{
- private PostItHeadlessCollection fixture;
-
- public AddCircleMemberDialogTests(PostItHeadlessCollection fixture, ITestOutputHelper output)
- {
- this.fixture = fixture;
- }
- ///
- /// Stand-in that returns an
- /// empty list. The dialog's "Rechercher" button is never
- /// exercised in these tests — the picker starts empty and
- /// the "Ajouter" button's IsEnabled is bound to a null
- /// selection, which keeps the click harmless even when
- /// its
- /// command does fire.
- ///
- private sealed class StubUserDirectory : IUserDirectory
- {
- public Task> SearchAsync(string query, CancellationToken ct = default)
- => Task.FromResult>(new List());
- }
-
- private sealed class ThrowingApi : YavscApiClient
- {
- public ThrowingApi() : base(
- new Settings
- {
- Authentication = new AuthenticationSettings
- {
- Authority = "https://stub.invalid",
- ClientId = "stub",
- Scopes = new[] { "openid" },
- },
- },
- new TokenStore(System.IO.Path.GetTempFileName()))
- { }
- }
-
- ///
- /// Mount a real , build a minimal
- /// DI graph, push then the
- /// on top of it.
- /// Returns the stack size so the test can pin the delta.
- /// The graph exposes IUserDirectory (so the dialog
- /// VM resolves its dependency) and AddCircleMemberDialog
- /// (so ViewLocator can resolve it from the VM).
- ///
- private static (MainWindow window,
- CirclesPage page,
- AddCircleMemberDialog dialog)
- Mount()
- {
- var api = new ThrowingApi();
- var circleClient = new CircleApiClient(api, "http://localhost/");
-
- var services = new ServiceCollection();
- services.AddSingleton(new Settings());
- services.AddSingleton(new StubUserDirectory());
- services.AddSingleton(circleClient);
- services.AddTransient();
- services.AddTransient();
- services.AddTransient();
- services.AddTransient();
- var sp = services.BuildServiceProvider();
-
- var window = new MainWindow();
- var app = (PostIt.App)Application.Current!;
- app.DataTemplates.Clear();
- app.DataTemplates.Add(new ViewLocator(sp));
- app.AttachMainWindow(window);
- window.Show();
-
- var circlesPage = sp.GetRequiredService();
- window.NavRoot.PushAsync(circlesPage).GetAwaiter().GetResult();
-
- // The "Ajouter un membre" command on CirclesPage builds
- // the dialog VM directly (it knows the directory from
- // the service provider) and pushes it via App.PushPage.
- var dialogVm = new AddCircleMemberDialogViewModel(sp.GetRequiredService());
- ((App)Application.Current!).PushPageAsync(dialogVm).GetAwaiter().GetResult();
-
- var dialog = window.NavRoot.NavigationStack[^1] as AddCircleMemberDialog
- ?? throw new System.InvalidOperationException("Dialog page not at top of stack.");
- return (window, circlesPage, dialog);
- }
-
- ///
- /// Click the "Fermer" button on the dialog and assert the
- /// nav stack shrinks by exactly one.
- ///
- [AvaloniaFact]
- public void Close_button_pops_dialog_off_nav_stack()
- {
- // Arrange: stack starts at 2 (CirclesPage + dialog).
- var window = fixture.Window;
- var stackBefore = window.NavRoot.NavigationStack.Count;
- Assert.Equal(2, stackBefore);
-
- // Act
- var dialog = window.NavRoot.NavigationStack[^1] as AddCircleMemberDialog ?? throw new System.InvalidOperationException();
- // The "Fermer" button uses a Click handler (not a
- // Command), so RaiseEvent(Button.ClickEvent) is the
- // right way to fire it from headless code. Executing
- // Command would no-op because no Command is bound.
- dialog.CloseButton.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
-
- // Assert: stack -1, the top is the CirclesPage again.
- Assert.True(window.NavRoot.NavigationStack.Count == stackBefore - 1,
- $"Click on 'Fermer' must shrink the nav stack by one. Before: {stackBefore}, after: {window.NavRoot.NavigationStack.Count}.");
- Assert.IsType(window.NavRoot.NavigationStack[^1]);
- }
-}
diff --git a/src/PostIt.Tests/Blogs/PostAclDialogTests.cs b/src/PostIt.Tests/Blogs/PostAclDialogTests.cs
deleted file mode 100644
index 03ed7825..00000000
--- a/src/PostIt.Tests/Blogs/PostAclDialogTests.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-
-using System.Net;
-using System.Text;
-using System.Text.Json;
-using Avalonia.Headless.XUnit;
-using Microsoft.Extensions.DependencyInjection;
-using PostIt.Services;
-using PostIt.ViewModels;
-using PostIt.Views;
-using Yavsc.Api.Client;
-using Yavsc.Blogspot;
-
-namespace PostIt.Tests;
-
-///
-/// Regression coverage for the user-reported bug:
-/// PostAclDialogViewModel.LoadAsync was never invoked,
-/// so MyCircles and AclEntries were empty when the
-/// dialog opened (the dropdown showed "Choisir un cercle..." and
-/// the list was blank, with no error to hint at why).
-///
-/// The fix wires 's constructor
-/// to trigger LoadAsync on the first
-/// DataContextChanged , and the VM guards re-entry via
-/// _loaded . Two tests pin that contract:
-///
-/// LoadAsync_runs_once_on_DataContext_changed : HTTP
-/// traffic shows up after the dialog is mounted.
-/// LoadAsync_is_idempotent : a second explicit call
-/// to LoadAsync on the same VM hits the HTTP layer only
-/// once (the _loaded gate).
-///
-///
-/// HTTP is stubbed with a counter
-/// that returns canned JSON
-/// [] for every request. The handler counts calls so the
-/// tests can assert "exactly one round-trip on mount" and
-/// "exactly one round-trip after two calls to LoadAsync". This
-/// is the same shape used by BearerScopeTests : real
-/// subclass, real
-/// with an injected handler, real
-/// /
-/// talking to it.
-///
-/// Lifecycle: shared
-/// provides the already wired to
-/// . Each test builds its own DI graph with
-/// the counting HTTP handler and swaps it in via
-/// . The
-/// graph exposes PostAclDialog so the
-/// resolves it from
-/// .
-///
-[Collection("PostIt Headless")]
-public sealed class PostAclDialogTests
-{
- private readonly PostItHeadlessCollection _host;
-
- public PostAclDialogTests(PostItHeadlessCollection host)
- {
- _host = host;
- }
-
- ///
- /// that replies 200 with
- /// [] (a valid JSON empty array, which both
- /// GetMyAclAsync and GetMyCirclesAsync can
- /// deserialize) and counts the number of requests.
- ///
- private sealed class CountingHttpHandler : HttpMessageHandler
- {
- public int RequestCount { get; private set; }
-
- protected override Task SendAsync(
- HttpRequestMessage request, CancellationToken cancellationToken)
- {
- RequestCount++;
- var response = new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = new StringContent("[]", Encoding.UTF8, "application/json"),
- };
- return Task.FromResult(response);
- }
- }
-
- ///
- /// Subclass of that routes HTTP
- /// traffic through a caller-supplied
- /// . Same recipe as
- /// BearerScopeTests.TestableYavscApiClient — we
- /// override CallAsync{T} to talk to our own
- /// and skip the OIDC refresh path,
- /// because the load-on-attach bug has nothing to do with
- /// token refresh.
- ///
- private sealed class TestableYavscApiClient : YavscApiClient
- {
- private readonly HttpClient _http;
-
- public TestableYavscApiClient(
- Settings settings,
- TokenStore store,
- HttpMessageHandler handler)
- : base(settings, store, oidc: null!)
- {
- _http = new HttpClient(handler, disposeHandler: false);
- }
-
- public override Task CallAsync(
- HttpMethod method, string path, object? body = null,
- CancellationToken ct = default)
- {
- var absolute = new Uri(new Uri(Settings.BusinessApiUrl), path);
- using var req = new HttpRequestMessage(method, absolute);
- using var resp = _http.SendAsync(req, ct).GetAwaiter().GetResult();
- resp.EnsureSuccessStatusCode();
- using var stream = resp.Content.ReadAsStream();
- var dto = JsonSerializer.Deserialize(stream,
- new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
- return Task.FromResult(dto!);
- }
- }
-
-}
diff --git a/src/PostIt.Tests/Auth/FakeAuthorizingBrowser.cs b/src/PostIt.Tests/FakeAuthorizingBrowser.cs
similarity index 100%
rename from src/PostIt.Tests/Auth/FakeAuthorizingBrowser.cs
rename to src/PostIt.Tests/FakeAuthorizingBrowser.cs
diff --git a/src/PostIt.Tests/Blogs/MainPageButtonsTests.cs b/src/PostIt.Tests/MainPageButtonsTests.cs
similarity index 57%
rename from src/PostIt.Tests/Blogs/MainPageButtonsTests.cs
rename to src/PostIt.Tests/MainPageButtonsTests.cs
index 90e5b6fb..767f9c2e 100644
--- a/src/PostIt.Tests/Blogs/MainPageButtonsTests.cs
+++ b/src/PostIt.Tests/MainPageButtonsTests.cs
@@ -1,4 +1,6 @@
+using Avalonia;
using Avalonia.Controls;
+using Avalonia.Headless;
using Avalonia.Headless.XUnit;
using Avalonia.Input;
using Avalonia.Interactivity;
@@ -48,43 +50,43 @@ namespace PostIt.Tests;
/// - "[DEV] Signature" — click pushes a page onto the
/// stack.
///
-///
-/// Lifecycle: shared
-/// owns the and the production DI graph.
-/// Each test builds a local with
-/// the fake + the page VMs and
-/// registers the destination pages, then swaps it in via
-/// . The
-/// fixture re-attaches the ViewLocator and the MainWindow so
-/// subsequent calls route through
-/// the overridden graph.
///
-[Collection("PostIt Headless")]
-public sealed class MainPageButtonsTests
+public class MainPageButtonsTests
{
- private readonly PostItHeadlessCollection _host;
-
- public MainPageButtonsTests(PostItHeadlessCollection host)
+ ///
+ /// Fake that throws on any
+ /// wire call. These tests never invoke a command that hits
+ /// the API — only the click → nav side of the pipeline is
+ /// asserted.
+ ///
+ private sealed class ThrowingApi : YavscApiClient
{
- _host = host;
+ public ThrowingApi() : base(
+ new Settings
+ {
+ Authentication = new AuthenticationSettings
+ {
+ Authority = "https://stub.invalid",
+ ClientId = "stub",
+ Scopes = new[] { "openid" },
+ },
+ },
+ new TokenStore(System.IO.Path.GetTempFileName()))
+ { }
}
- ///
- /// Build the test DI graph: for
- /// the API clients (the click tests never hit the wire;
- /// any traffic would be a wiring bug), the real
- /// /
- /// / that the page VM
- /// resolves, and the page + dialog + VM registrations the
- /// needs to resolve the three
- /// push targets.
- ///
- private MainPageViewModel BuildViewModel(BlogPostDto? selectedPost = null)
+ private static MainPageViewModel MakeViewModel(BlogPostDto? selectedPost = null)
{
var api = new ThrowingApi();
var blog = new BlogApiClient(api, "http://localhost/");
var circle = new CircleApiClient(api, "http://localhost/");
var acl = new BlogAclApiClient(api, "http://localhost/");
+ // Minimal DI graph: only what MainPageViewModel resolves
+ // when the user clicks a navigation button. Today that's
+ // SignaturePageViewModel / CirclesPageViewModel / ACL
+ // dependencies. The graph intentionally stays local to this
+ // suite to avoid side effects from App.BuildServices() (real
+ // token-store wiring).
var services = new ServiceCollection();
services.AddSingleton(new Settings());
services.AddSingleton(circle);
@@ -94,31 +96,51 @@ public sealed class MainPageButtonsTests
services.AddTransient();
services.AddTransient();
services.AddTransient();
- var sp = services.BuildServiceProvider();
-
- var vm = new MainPageViewModel(blog, services: sp);
+ var vm = new MainPageViewModel(blog, services: services.BuildServiceProvider());
if (selectedPost is not null) vm.SelectedPost = selectedPost;
return vm;
}
///
- /// Push a with the given VM onto
- /// the shared 's nav stack. Clears
- /// any pages the previous test left behind (the fixture's
- /// MainWindow is shared across every test class). Returns
- /// the live page so the test can access its named buttons.
+ /// Mount a real (as
+ /// SessionStatusBannerTests does), push a
+ /// with the given VM onto
+ /// NavRoot . PushAsync is awaited (via
+ /// GetAwaiter().GetResult() ) so the page is on the
+ /// nav stack before the test tries to interact with its
+ /// named buttons. The window is shown so the visual tree is
+ /// realised and KeyPressQwerty has a real
+ /// to dispatch against.
///
- private MainPage MountAsync(MainPageViewModel vm)
+ private static (MainWindow window, MainPage page) MountMainPage(MainPageViewModel vm)
{
+ var window = new MainWindow();
var page = new MainPage { DataContext = vm };
- _host.PushAsync(page);
- return page;
+ var app = (PostIt.App)Application.Current!;
+ if (vm.Services is not null)
+ {
+ app.DataTemplates.Clear();
+ app.DataTemplates.Add(new ViewLocator(vm.Services));
+ }
+ app.AttachMainWindow(window);
+ window.Show();
+ window.NavRoot.PushAsync(page).GetAwaiter().GetResult();
+ return (window, page);
}
///
- /// Click a button by executing its
- /// and draining any so the
- /// caller can assert on the resulting nav stack immediately.
+ /// Click a button by focusing it and pressing Enter — the
+ /// supported headless pattern (cf. CalculatorTests in the
+ /// Avalonia.Samples repo). Returns the nav-stack count
+ /// before the click so the caller can assert on the delta.
+ /// KeyPressQwerty is dispatched on the
+ /// itself — it is the that owns the
+ /// headless implementation, and routing the key through any
+ /// descendant TopLevel (e.g. one obtained via
+ /// TopLevel.GetTopLevel(button) ) fails with a
+ /// NullReferenceException from the headless impl
+ /// because the descendant does not carry the
+ /// PlatformHandle the harness expects.
///
private static int ClickAndCapture(MainWindow window, Button button)
{
@@ -143,8 +165,8 @@ public sealed class MainPageButtonsTests
Title = "An existing post",
AuthorId = "u-alice"
};
- var vm = BuildViewModel(post);
- var page = MountAsync(vm);
+ var vm = MakeViewModel(post);
+ var (window, page) = MountMainPage(vm);
// Sanity: the button's command is bound and CanExecute
// is true. If this fails, the bug is upstream (XAML
@@ -154,12 +176,12 @@ public sealed class MainPageButtonsTests
Assert.True(aclButton.Command.CanExecute(null));
// Act
- var stackBefore = ClickAndCapture(_host.Window, aclButton);
+ var stackBefore = ClickAndCapture(window, aclButton);
// Assert γ + sniff léger: stack grew, new top is a Page.
- Assert.True(_host.Window.NavRoot.NavigationStack.Count > stackBefore,
- $"Click on ACL must push a new page onto the nav stack. Stack size before: {stackBefore}, after: {_host.Window.NavRoot.NavigationStack.Count}.");
- var pushed = _host.Window.NavRoot.NavigationStack[^1];
+ Assert.True(window.NavRoot.NavigationStack.Count > stackBefore,
+ $"Click on ACL must push a new page onto the nav stack. Stack size before: {stackBefore}, after: {window.NavRoot.NavigationStack.Count}.");
+ var pushed = window.NavRoot.NavigationStack.Last();
Assert.NotNull(pushed);
Assert.IsAssignableFrom(pushed);
}
@@ -169,19 +191,19 @@ public sealed class MainPageButtonsTests
{
// Arrange: OpenCircles has no CanExecute guard today —
// any click should fire it and push the page.
- var vm = BuildViewModel();
- var page = MountAsync(vm);
+ var vm = MakeViewModel();
+ var (window, page) = MountMainPage(vm);
var circlesButton = page.OpenCirclesButton;
Assert.NotNull(circlesButton.Command);
// Act
- var stackBefore = ClickAndCapture(_host.Window, circlesButton);
+ var stackBefore = ClickAndCapture(window, circlesButton);
// Assert
- Assert.True(_host.Window.NavRoot.NavigationStack.Count > stackBefore,
+ Assert.True(window.NavRoot.NavigationStack.Count > stackBefore,
"Click on 'Mes cercles' must push a new page onto the nav stack.");
- var pushed = _host.Window.NavRoot.NavigationStack[^1];
+ var pushed = window.NavRoot.NavigationStack.Last();
Assert.NotNull(pushed);
Assert.IsAssignableFrom(pushed);
}
@@ -192,25 +214,25 @@ public sealed class MainPageButtonsTests
// Arrange: the "[DEV] Signature" button is bound to the
// MainPageViewModel.OpenSignatureDevCommand [RelayCommand].
// The click must push SignaturePage on top of NavRoot.
- // The ServiceCollection registered in BuildViewModel
- // provides SignaturePageViewModel so the command can
- // resolve it via DI and call App.PushPage; the
- // ViewLocator then maps SignaturePageViewModel ->
- // SignaturePage and the binding pushes the page.
- var vm = BuildViewModel();
- var page = MountAsync(vm);
+ // The ServiceCollection registered in MakeViewModel provides
+ // SignaturePageViewModel so the command can resolve it via
+ // DI and call App.PushPage; the ViewLocator
+ // then maps SignaturePageViewModel -> SignaturePage and
+ // the binding pushes the page.
+ var vm = MakeViewModel();
+ var (window, page) = MountMainPage(vm);
var signatureButton = page.OpenSignatureDevButton;
Assert.NotNull(signatureButton.Command);
Assert.True(signatureButton.Command.CanExecute(null));
// Act
- var stackBefore = ClickAndCapture(_host.Window, signatureButton);
+ var stackBefore = ClickAndCapture(window, signatureButton);
// Assert
- Assert.True(_host.Window.NavRoot.NavigationStack.Count > stackBefore,
+ Assert.True(window.NavRoot.NavigationStack.Count > stackBefore,
"Click on '[DEV] Signature' must push a new page onto the nav stack.");
- var pushed = _host.Window.NavRoot.NavigationStack[^1];
+ var pushed = window.NavRoot.NavigationStack.Last();
Assert.NotNull(pushed);
Assert.IsAssignableFrom(pushed);
}
diff --git a/src/PostIt.Tests/Blogs/MainPageSaveTests.cs b/src/PostIt.Tests/MainPageSaveTests.cs
similarity index 62%
rename from src/PostIt.Tests/Blogs/MainPageSaveTests.cs
rename to src/PostIt.Tests/MainPageSaveTests.cs
index 918b40de..b6bf963a 100644
--- a/src/PostIt.Tests/Blogs/MainPageSaveTests.cs
+++ b/src/PostIt.Tests/MainPageSaveTests.cs
@@ -1,22 +1,22 @@
+using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.VisualTree;
-using Microsoft.Extensions.DependencyInjection;
+using Yavsc.Blogspot;
+using Yavsc.Api.Client;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
-using Yavsc.Api.Client;
-using Yavsc.Blogspot;
-
namespace PostIt.Tests;
///
/// Headless UI tests for the "Save" flow in .
-/// Uses the shared (a real
-/// with the production DI graph attached
-/// to ) plus a local
-/// that swaps
-/// for the recording fake.
+/// The pattern is the one SessionStatusBannerTests
+/// established: [AvaloniaFact] , a
+/// hosting the page (via a because
+/// MainPage is a ContentPage ), then drive the
+/// controls through their public surface and assert on what
+/// saw go on the wire.
///
/// The bug we are pinning: the title TextBox is
/// currently {Binding SelectedPost.Title, Mode=TwoWay} .
@@ -31,38 +31,41 @@ namespace PostIt.Tests;
/// pass once the VM owns a dedicated Title /Article
/// buffer that the XAML binds to and the Save command consumes.
///
-[Collection("PostIt Headless")]
-public sealed class MainPageSaveTests
+public class MainPageSaveTests
{
- private readonly PostItHeadlessCollection _host;
-
- public MainPageSaveTests(PostItHeadlessCollection host)
- {
- _host = host;
- }
-
[AvaloniaFact]
- public void Typing_a_title_then_clicking_Save_sends_that_title_in_the_post_body()
+ public async Task Typing_a_title_then_clicking_Save_sends_that_title_in_the_post_body()
{
- // Arrange: VM with a recording API client, mounted on
- // the shared MainWindow's nav stack.
+ // Arrange: VM with a recording API client, mounted in a
+ // headless window via a Frame (MainPage is a ContentPage,
+ // not a Control, so it needs a navigation host).
var recorder = new CallRecorder();
-
- var blog = _host.Services.GetRequiredService();
+ var api = new RecordingYavscApiClient(recorder);
+ var blog = new BlogApiClient(api, "http://localhost/");
var viewModel = new MainPageViewModel(blog);
+
var page = new MainPage { DataContext = viewModel };
- _host.PushAsync(page);
+ // MainPage is a ContentPage (a Page, not a Control), so it
+ // must be hosted in a navigation surface. The production
+ // MainWindow.axaml uses NavigationPage, and the API is the
+ // same one App.axaml.cs drives at boot (PushAsync, fire-
+ // and-forget in prod because the page is the top of the
+ // stack immediately).
+ var nav = new NavigationPage();
+ _ = nav.PushAsync(page);
+ var window = new Window { Content = nav };
+ window.Show();
// Act: type a title into the editor's TextBox without
- // first selecting a post in the list — the only state
- // in which a new post can be created. Then click Save.
- var titleBox = _host.Window.GetVisualDescendants()
+ // first selecting a post in the list — the only state in
+ // which a new post can be created. Then click Save.
+ var titleBox = window.GetVisualDescendants()
.OfType()
.First(t => t.PlaceholderText == "Title");
const string typed = "Mon premier billet";
titleBox.Text = typed;
- var saveButton = _host.Window.GetVisualDescendants()
+ var saveButton = window.GetVisualDescendants()
.OfType()
.Single(b => b.Content as string == "Save");
saveButton.Command!.Execute(null);
@@ -72,11 +75,7 @@ public sealed class MainPageSaveTests
// task on the dispatcher. Give the dispatcher a chance to
// run so the awaited CallAsync has actually fired before
// we inspect the recorder.
- var deadline = DateTime.UtcNow.AddSeconds(2);
- while (recorder.Calls.Count == 0 && DateTime.UtcNow < deadline)
- {
- Task.Delay(20).GetAwaiter().GetResult();
- }
+ await Task.Delay(200);
// Assert: the first POST to "blog" carried a BlogPostDto
// whose Title is exactly what the user typed. The bug
diff --git a/src/PostIt.Tests/Auth/OidcStubAuthority.cs b/src/PostIt.Tests/OidcStubAuthority.cs
similarity index 100%
rename from src/PostIt.Tests/Auth/OidcStubAuthority.cs
rename to src/PostIt.Tests/OidcStubAuthority.cs
diff --git a/src/PostIt.Tests/PostItHeadlessCollection.cs b/src/PostIt.Tests/PostItHeadlessCollection.cs
deleted file mode 100644
index c99b07cc..00000000
--- a/src/PostIt.Tests/PostItHeadlessCollection.cs
+++ /dev/null
@@ -1,177 +0,0 @@
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Threading;
-using Microsoft.Extensions.DependencyInjection;
-using PostIt.ViewModels;
-using PostIt.Views;
-using Yavsc.Api.Client;
-
-namespace PostIt.Tests;
-
-///
-/// xUnit collection grouping every headless UI test in
-/// PostIt.Tests . The Avalonia headless harness instantiates
-/// a single per test class
-/// (IClassFixture<PostItHeadlessFixture> ); the
-/// collection marker here exists for two reasons:
-///
-///
-/// It documents the shared lifecycle
-/// contract: every test class that opts in gets the same
-/// , the same DI service provider,
-/// the same on
-/// , and the same
-/// attachment that
-/// App.PushPageAsync relies on.
-/// It disables parallelisation across the
-/// whole collection. The Avalonia headless platform is
-/// process-global (one per
-/// process, one dispatcher per thread), so two collection
-/// members running in parallel would race on the same
-/// static state and produce flaky failures with no useful
-/// diagnostic. Same rationale as
-/// JwtClaimMappingCollection .
-///
-///
-/// Mirrors the convention used by
-/// Yavsc.Org.Tests.WebServerFixture (collection
-/// "Yavsc Server" ) and
-/// Yavsc.Blogs.Tests.JwtClaimMappingCollection .
-///
-[CollectionDefinition("PostIt Headless")]
-public sealed class PostItHeadlessCollection: IDisposable
-{
-
- /// The DI service provider the fixture booted
- /// (production graph from ).
- /// Identical across every
- /// instance — see class remarks.
- public IServiceProvider Services { get; private set; }
-
- /// The headless for this
- /// fixture instance. Already n,
- /// so its visual tree is realised and
- /// bindings have been
- /// evaluated. The window is per-instance, not
- /// process-shared, so each test class gets a clean nav
- /// stack out of the box.
- public MainWindow Window { get; private set; }
-
- /// The instance the Avalonia
- /// headless harness set as .
- /// Convenience accessor for tests that need to call
- /// App.PushPageAsync directly.
- public App App { get; private set; }
-
- /// The navigation surface the
- /// hosts. Tests can read
- /// NavigationStack directly or call
- /// to push onto it.
- public NavigationPage NavRoot { get; private set; }
-
- public PostItHeadlessCollection()
- {
-
- // First fixture to construct in this process:
- // build the production DI container and attach
- // it to the App.
- App = (App)Application.Current!;
-
- var testingServices = new ServiceCollection();
- var api = new RecordingYavscApiClient(new CallRecorder());
- var blog = new BlogApiClient(api, "http://localhost/");
-
- // The recording fake is sufficient on its own — no
- // production wiring needed. Swap it in via the fixture
- // so the App.PushPageAsync path resolves the same way
- // it would in production (minus the token store).
-
- testingServices.AddSingleton(api);
- testingServices.AddSingleton(blog);
-
- Services = App.BuildServices(testingServices);
-
- App.AttachServiceProvider(Services);
-
- // The ViewLocator is the single entry point
- // App.PushPageAsync uses to map a VM to a Page.
- App.DataTemplates.Clear();
- App.DataTemplates.Add(new ViewLocator(Services));
-
- // Per-instance window: each test class gets its own.
- Window = new MainWindow();
- App.AttachMainWindow(Window);
- Window.Show();
- }
-
-
-
- ///
- /// Push a view model or page onto .
- /// Awaits the push asynchronously so the headless
- /// dispatcher can pump frames while the push is in flight;
- /// the caller can then assert on the resulting stack
- /// (NavRoot.NavigationStack[^1] ).
- ///
- ///
- /// Tests that want a clean stack (most of them, since
- /// the fixture's is shared
- /// across every test class) should call
- /// before pushing, or
- /// use which clears by default.
- ///
- /// The page that was pushed, so the caller can
- /// assert on its type or bind a DataContext .
- public Page PushAsync(object vmOrPage)
- {
- if (vmOrPage is null) throw new ArgumentNullException(nameof(vmOrPage));
-
-
- // Synchronous push: the Avalonia headless
- // NavigationPage.PushAsync returns a Task that
- // completes once the transition animation finishes,
- // and in headless that animation is driven by the
- // dispatcher pump. We block on the Task with
- // GetAwaiter().GetResult() rather than awaiting it
- // because the test body is itself running on the
- // dispatcher thread (the [AvaloniaFact] attribute
- // schedules the test there); an await would capture
- // the dispatcher as the continuation target and
- // deadlock waiting for the push to complete on a
- // thread that's already busy running the test.
- if (vmOrPage is Page page)
- {
- Window.NavRoot.PushAsync(page).GetAwaiter().GetResult();
- // Pump the dispatcher once so the pushed page
- // is actually on NavigationStack (the Awaiter
- // above unblocks before the stack is updated).
- Dispatcher.UIThread.RunJobs();
- return page;
- }
-
- // VM push: route through the production
- // App.PushPageAsync pipeline.
- var app = (App)Application.Current!;
- var vm = (ViewModelBase)vmOrPage;
- app.PushPageAsync(vm).GetAwaiter().GetResult();
- Dispatcher.UIThread.RunJobs();
- return Window.NavRoot.NavigationStack[^1];
- }
-
- public void Dispose()
- {
- // Last fixture out: tear the shared state down so
- // the next test run starts clean. We don't shut
- // down the Avalonia headless platform — that's
- // owned by the [AvaloniaTestApplication] attribute
- // on TestAppBuilder and gets torn down when the
- // process exits.
- try
- {
- var app = (App)Application.Current!;
- app.DataTemplates.Clear();
- }
- catch { /* best effort */ }
- Services = null;
- }
-}
diff --git a/src/PostIt.Tests/SessionStatusBannerTests.cs b/src/PostIt.Tests/SessionStatusBannerTests.cs
index b947ea70..d35529db 100644
--- a/src/PostIt.Tests/SessionStatusBannerTests.cs
+++ b/src/PostIt.Tests/SessionStatusBannerTests.cs
@@ -1,54 +1,46 @@
+using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using Avalonia.Styling;
using Avalonia.VisualTree;
using PostIt.ViewModels;
+using PostIt.Views;
namespace PostIt.Tests;
///
-/// UI tests for . The shared
-/// provides the headless
-/// already attached to
-/// and shown, so each test only has to wire its
-/// onto
-/// MainWindow.SessionBanner and assert on the rendered
-/// tree.
+/// UI tests for . Mounted inside
+/// a real via the headless Avalonia
+/// platform declared in TestApp.cs .
///
-/// The session banner's DataContext is not wired
-/// by in
-/// these tests: production wires it at composition time, but a
-/// unit test runs against a freshly-built so
-/// we set the DataContext on the banner directly. The
-/// production code path is exercised end-to-end by the manual
-/// launch, not here.
-///
-/// Pattern: [AvaloniaFact] (from
-/// Avalonia.Headless.XUnit ) instead of plain
-/// [Fact] because the AvaloniaFact attribute schedules
-/// the test body inside a dispatcher, which is the precondition
-/// for the headless Window's
+/// The pattern is the one that UnitTest1.MainPage_Should_Load
+/// established: a test attribute [AvaloniaFact] (from
+/// Avalonia.Headless.XUnit ) instead of plain [Fact] ,
+/// new MainWindow() , window.Show() . The AvaloniaFact
+/// attribute schedules the test body inside a dispatcher, which
+/// is the precondition for the headless Window's
/// PlatformManager.CreateWindow() to find a registered
/// service. A plain [Fact] test that calls
-/// new Window().Show() throws because the harness has
-/// not been initialised for that thread.
+/// new Window().Show() throws because the harness has not
+/// been initialised for that thread.
+///
+/// The session banner's DataContext is not wired in
+/// these tests: App.OnFrameworkInitializationCompleted is
+/// not called in a unit test, so we set the DataContext on the
+/// banner directly. The production code path is exercised
+/// end-to-end by the manual launch, not here.
///
-[Collection("PostIt Headless")]
-public sealed class SessionStatusBannerTests
+public class SessionStatusBannerTests
{
- private readonly PostItHeadlessCollection _host;
-
- public SessionStatusBannerTests(PostItHeadlessCollection host)
- {
- _host = host;
- }
-
[AvaloniaFact]
public void Banner_renders_three_buttons_in_the_visual_tree()
{
- var banner = _host.Window.SessionBanner;
- banner.DataContext = new SessionStatusViewModel();
+ var window = new MainWindow();
+ window.SessionBanner.DataContext = new SessionStatusViewModel();
+ window.Show();
- var buttons = banner.GetVisualDescendants()
+ var buttons = window.SessionBanner.GetVisualDescendants()
.OfType()
.ToList();
@@ -65,30 +57,31 @@ public sealed class SessionStatusBannerTests
[AvaloniaFact]
public void Banner_login_button_is_visible_when_logged_out()
{
- var banner = _host.Window.SessionBanner;
+ var window = new MainWindow();
var vm = new SessionStatusViewModel();
Assert.True(vm.IsLoggedOut); // VM default
- banner.DataContext = vm;
+ window.SessionBanner.DataContext = vm;
+ window.Show();
- var login = banner.GetVisualDescendants()
+ var login = window.SessionBanner.GetVisualDescendants()
.OfType()
.Single(b => b.Content as string == "Se connecter");
- // The XAML binds IsVisible to IsLoggedOut. After the
- // banner is on the realised visual tree, the binding
- // has been evaluated.
+ // The XAML binds IsVisible to IsLoggedOut. After Show,
+ // the binding has been evaluated.
Assert.True(login.IsVisible);
}
[AvaloniaFact]
public void Banner_logout_button_is_hidden_when_logged_out()
{
- var banner = _host.Window.SessionBanner;
+ var window = new MainWindow();
var vm = new SessionStatusViewModel();
Assert.False(vm.IsLoggedIn); // VM default
- banner.DataContext = vm;
+ window.SessionBanner.DataContext = vm;
+ window.Show();
- var logout = banner.GetVisualDescendants()
+ var logout = window.SessionBanner.GetVisualDescendants()
.OfType()
.Single(b => b.Content as string == "Se déconnecter");
@@ -98,10 +91,11 @@ public sealed class SessionStatusBannerTests
[AvaloniaFact]
public void Banner_settings_button_is_visible_regardless_of_session()
{
- var banner = _host.Window.SessionBanner;
- banner.DataContext = new SessionStatusViewModel();
+ var window = new MainWindow();
+ window.SessionBanner.DataContext = new SessionStatusViewModel();
+ window.Show();
- var settings = banner.GetVisualDescendants()
+ var settings = window.SessionBanner.GetVisualDescendants()
.OfType()
.Single(b => b.Content as string == "Paramètres");
@@ -114,10 +108,11 @@ public sealed class SessionStatusBannerTests
[AvaloniaFact]
public void Banner_session_label_reflects_DataContext()
{
- var banner = _host.Window.SessionBanner;
- banner.DataContext = new SessionStatusViewModel();
+ var window = new MainWindow();
+ window.SessionBanner.DataContext = new SessionStatusViewModel();
+ window.Show();
- var label = banner.GetVisualDescendants()
+ var label = window.SessionBanner.GetVisualDescendants()
.OfType()
.First(t => t.Text == "Déconnecté" || t.Text == "Connecté");
diff --git a/src/PostIt.Tests/UnitTest1.cs b/src/PostIt.Tests/UnitTest1.cs
new file mode 100644
index 00000000..96990865
--- /dev/null
+++ b/src/PostIt.Tests/UnitTest1.cs
@@ -0,0 +1,16 @@
+using Avalonia.Headless.XUnit;
+using Avalonia.Controls;
+using PostIt.Views;
+
+namespace PostIt.Tests;
+
+public class MainPageTests
+{
+ [AvaloniaFact]
+ public void MainPage_Should_Load()
+ {
+ var window = new MainWindow();
+ window.Show();
+ Assert.NotNull(window);
+ }
+}
\ No newline at end of file
diff --git a/src/PostIt.Tests/pslist b/src/PostIt.Tests/pslist
deleted file mode 100644
index 0f1d73da..00000000
--- a/src/PostIt.Tests/pslist
+++ /dev/null
@@ -1,94 +0,0 @@
-UID PID PPID C STIME TTY TIME CMD
-paul 1155 1 0 13:18 ? 00:00:00 /usr/lib/systemd/systemd --user
-paul 1168 1155 0 13:18 ? 00:00:00 (sd-pam)
-paul 1361 1155 0 13:18 ? 00:00:00 /usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
-paul 1364 1155 1 13:18 ? 00:01:19 /home/paul/.nvm/versions/node/v22.23.0/bin/node /home/paul/.nvm/versions/node/v22.23.0/lib/node_modules/openclaw/dist/index.js gateway --port 18789
-paul 1367 1155 0 13:18 ? 00:00:00 /usr/bin/pipewire
-paul 1372 1155 0 13:18 ? 00:00:00 /usr/bin/pipewire -c filter-chain.conf
-paul 1373 1155 0 13:18 ? 00:00:00 /usr/bin/wireplumber
-paul 1374 1155 0 13:18 ? 00:00:00 /usr/bin/pipewire-pulse
-paul 1444 1155 0 13:18 ? 00:00:00 /usr/bin/mpris-proxy
-paul 2593 1155 0 13:19 ? 00:00:00 /usr/bin/gnome-keyring-daemon --foreground --components=pkcs11,secrets --control-directory=/run/user/1000/keyring
-paul 2608 2487 0 13:19 tty2 00:00:00 /usr/libexec/gdm-x-session --run-script /usr/bin/gnome-session
-paul 2617 2608 1 13:19 tty2 00:01:12 /usr/lib/xorg/Xorg vt2 -displayfd 3 -auth /run/user/1000/gdm/Xauthority -nolisten tcp -background none -noreset -keeptty -novtswitch -verbose 3
-paul 2647 2608 0 13:19 tty2 00:00:00 /usr/libexec/gnome-session-binary
-paul 2785 1155 0 13:19 ? 00:00:00 /usr/libexec/at-spi-bus-launcher
-paul 2792 2785 0 13:19 ? 00:00:00 /usr/bin/dbus-daemon --config-file=/usr/share/defaults/at-spi2/accessibility.conf --nofork --print-address 11 --address=unix:path=/run/user/1000/at-spi/bus_1
-paul 2802 1155 0 13:19 ? 00:00:00 /usr/libexec/gcr-ssh-agent --base-dir /run/user/1000/gcr
-paul 2803 1155 0 13:19 ? 00:00:00 /usr/libexec/gnome-session-ctl --monitor
-paul 2804 1155 0 13:19 ? 00:00:00 /usr/bin/ssh-agent -D
-paul 2814 1155 0 13:19 ? 00:00:00 /usr/libexec/gvfsd
-paul 2828 1155 0 13:19 ? 00:00:00 /usr/libexec/gvfsd-fuse /run/user/1000/gvfs -f
-paul 2838 1155 0 13:19 ? 00:00:00 /usr/libexec/gnome-session-binary --systemd-service --session=gnome
-paul 2874 1155 3 13:19 ? 00:02:13 /usr/bin/gnome-shell
-paul 2896 2874 0 13:19 ? 00:00:01 /usr/libexec/mutter-x11-frames
-paul 2902 1155 0 13:19 ? 00:00:00 /usr/libexec/at-spi2-registryd --use-gnome-session
-paul 2918 1155 0 13:19 ? 00:00:00 /usr/libexec/xdg-desktop-portal
-paul 2933 1155 0 13:19 ? 00:00:00 /usr/libexec/xdg-permission-store
-paul 2938 1155 0 13:19 ? 00:00:00 /usr/libexec/xdg-document-portal
-paul 2971 1155 0 13:19 ? 00:00:00 /usr/libexec/gnome-shell-calendar-server
-paul 2976 1155 0 13:19 ? 00:00:00 /usr/libexec/dconf-service
-paul 2992 1155 0 13:19 ? 00:00:00 /usr/libexec/evolution-source-registry
-paul 2994 1155 0 13:19 ? 00:00:00 /usr/bin/gjs -m /usr/share/gnome-shell/org.gnome.Shell.Notifications
-paul 3012 1155 0 13:19 ? 00:00:12 /usr/bin/ibus-daemon --panel disable --xim
-paul 3013 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-a11y-settings
-paul 3014 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-color
-paul 3015 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-datetime
-paul 3016 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-housekeeping
-paul 3018 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-keyboard
-paul 3024 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-media-keys
-paul 3025 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-power
-paul 3027 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-print-notifications
-paul 3029 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-rfkill
-paul 3030 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-screensaver-proxy
-paul 3035 2838 0 13:19 ? 00:00:05 /usr/bin/gnome-software --gapplication-service
-paul 3037 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-sharing
-paul 3042 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-smartcard
-paul 3048 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-sound
-paul 3054 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-usb-protection
-paul 3057 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-wacom
-paul 3058 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-xsettings
-paul 3059 2838 0 13:19 ? 00:00:00 /usr/libexec/evolution-data-server/evolution-alarm-notify
-paul 3064 2838 0 13:19 ? 00:00:00 /usr/bin/kalendarac
-paul 3070 2838 0 13:19 ? 00:00:00 /usr/libexec/gsd-disk-utility-notify
-paul 3088 2838 0 13:19 ? 00:00:00 /usr/bin/kdeconnectd
-paul 3168 1155 0 13:19 ? 00:00:00 /usr/bin/gjs -m /usr/share/gnome-shell/org.gnome.ScreenSaver
-paul 3172 1155 0 13:19 ? 00:00:00 /usr/libexec/gsd-printer
-paul 3207 3012 0 13:19 ? 00:00:00 /usr/libexec/ibus-memconf
-paul 3208 3012 0 13:19 ? 00:00:06 /usr/libexec/ibus-extension-gtk3
-paul 3214 1155 0 13:19 ? 00:00:00 /usr/libexec/ibus-x11 --kill-daemon
-paul 3216 1155 0 13:19 ? 00:00:00 /usr/libexec/ibus-portal
-paul 3218 1155 0 13:19 ? 00:00:00 /usr/libexec/localsearch-3
-paul 3219 1155 0 13:19 ? 00:00:00 /usr/libexec/xdg-desktop-portal-gnome
-paul 3241 1155 0 13:19 ? 00:00:00 /usr/libexec/gvfs-udisks2-volume-monitor
-paul 3251 1155 0 13:19 ? 00:00:00 /usr/libexec/gvfs-mtp-volume-monitor
-paul 3259 1155 0 13:19 ? 00:00:00 /usr/libexec/gvfs-gphoto2-volume-monitor
-paul 3265 1155 0 13:20 ? 00:00:00 /usr/libexec/gvfs-goa-volume-monitor
-paul 3271 1155 0 13:20 ? 00:00:00 /usr/libexec/goa-daemon
-paul 3280 1155 0 13:20 ? 00:00:00 /usr/libexec/goa-identity-service
-paul 3287 1155 0 13:20 ? 00:00:00 /usr/libexec/gvfs-afc-volume-monitor
-paul 3303 3012 0 13:20 ? 00:00:02 /usr/libexec/ibus-engine-simple
-paul 3372 1155 0 13:20 ? 00:00:00 /usr/libexec/xdg-desktop-portal-gtk
-paul 3441 1155 0 13:20 ? 00:00:00 /usr/libexec/gvfsd-metadata
-paul 3453 1155 0 13:20 ? 00:00:00 /usr/libexec/evolution-calendar-factory
-paul 3495 1155 0 13:20 ? 00:00:00 /usr/libexec/evolution-addressbook-factory
-paul 4798 1155 0 13:26 ? 00:00:09 /usr/libexec/gnome-terminal-server
-paul 4810 4798 0 13:26 pts/0 00:00:00 bash
-paul 8614 1155 0 13:29 ? 00:00:01 /usr/bin/speech-dispatcher -s -t 0
-paul 8656 8614 0 13:29 ? 00:00:00 [sd_espeak-ng-mb]
-paul 8709 8614 0 13:29 ? 00:00:00 /usr/lib/speech-dispatcher-modules/sd_espeak-ng /etc/speech-dispatcher/modules/espeak-ng.conf
-paul 8785 8614 0 13:29 ? 00:00:00 /usr/lib/speech-dispatcher-modules/sd_dummy /etc/speech-dispatcher/modules/dummy.conf
-paul 8799 8614 0 13:29 ? 00:00:00 /usr/lib/speech-dispatcher-modules/sd_espeak-ng /etc/speech-dispatcher/modules/
-paul 10028 1155 0 13:31 ? 00:00:00 adb -L tcp:5037 fork-server server --reply-fd 4
-paul 69578 2814 0 13:53 ? 00:00:00 /usr/libexec/gvfsd-http --spawner :1.22 /org/gtk/gvfs/exec_spaw/0
-paul 108341 1155 3 14:06 ? 00:00:48 /home/paul/.nvm/versions/node/v22.23.0/bin/node /home/paul/.nvm/versions/node/v22.23.0/lib/node_modules/acpx/dist/cli.js __queue-owner
-paul 108416 108341 0 14:06 ? 00:00:00 openclaw
-paul 108458 108416 2 14:06 ? 00:00:37 openclaw-acp
-paul 143553 1155 0 14:19 ? 00:00:05 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmpI2JxLw.tmp
-paul 149205 1155 0 14:21 ? 00:00:05 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmpitRyQG.tmp
-paul 151724 1155 0 14:22 ? 00:00:04 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmpJEsOZV.tmp
-paul 157447 1155 1 14:24 ? 00:00:05 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmpyM92DV.tmp
-paul 165231 1155 0 14:26 ? 00:00:01 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmp5CKC19.tmp
-paul 168472 1155 4 14:27 ? 00:00:09 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmpuRJsnQ.tmp
-paul 172147 1155 4 14:29 pts/0 00:00:05 /home/paul/Workspace/yavsc/src/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests @@ /tmp/tmpxT8nje.tmp
-paul 172435 4810 99 14:31 pts/0 00:00:00 ps -fu paul
diff --git a/src/PostIt/PostIt/App.axaml.cs b/src/PostIt/PostIt/App.axaml.cs
index d2399873..1a68f4ac 100644
--- a/src/PostIt/PostIt/App.axaml.cs
+++ b/src/PostIt/PostIt/App.axaml.cs
@@ -49,7 +49,7 @@ public partial class App : Application
// build is ever reconfigured to skip the early check.
if (TryHandOffCustomSchemeUrl()) return;
- this.ServiceProvider = BuildServices(new ServiceCollection());
+ this.ServiceProvider = BuildServices();
AttachServiceProvider(ServiceProvider);
var settings = ServiceProvider.GetRequiredService();
var sessionStatus = ServiceProvider.GetRequiredService();
@@ -139,7 +139,7 @@ public partial class App : Application
/// or service resolves through the same wiring the real app
/// does, and a green test is a green contract for prod.
///
- internal static IServiceProvider BuildServices(ServiceCollection services)
+ internal static IServiceProvider BuildServices()
{
var settings = new Settings();
settings.Load();
@@ -156,6 +156,7 @@ public partial class App : Application
var contactService = new ContactService();
var userDirectory = new UserDirectory(userSearchClient);
+ var services = new ServiceCollection();
// Vues
services.AddTransient();
@@ -349,9 +350,4 @@ public partial class App : Application
return window.NavRoot.PushAsync(page);
}
-
- internal async Task GoBackAsync()
- {
- await window.NavRoot.PopAsync();
- }
}
diff --git a/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs
index 59d6dbed..a721d738 100644
--- a/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs
@@ -5,7 +5,6 @@ using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostIt.Services;
-using PostIt.Views;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
@@ -107,7 +106,7 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase
/// UI from firing an event with a null payload.
///
[RelayCommand]
- public async Task AddAsync()
+ public void Add()
{
if (Selected is null)
{
@@ -115,14 +114,5 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase
return;
}
Confirmed?.Invoke(this, Selected);
- var app = App.Current as App;
- await app.GoBackAsync();
- }
-
- [RelayCommand]
- public async Task CloseAsync()
- {
- var app = App.Current as App;
- await app.GoBackAsync();
}
}
diff --git a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs
index 33a5bd30..bfc431b8 100644
--- a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs
@@ -119,17 +119,6 @@ public partial class CirclesPageViewModel : ViewModelBase
var directory = services.GetRequiredService();
AddCircleMemberDialogViewModel model =
new AddCircleMemberDialogViewModel(directory);
- // Wire the dialog's Confirmed event to OnAddMemberConfirmedAsync.
- // Without this, the dialog's "Ajouter" button fires the event
- // into the void: no subscriber, the picked user is silently
- // dropped, and nothing is added to the circle. The dialog
- // stays open until the user uses the back gesture — which is
- // how the user noticed the button was a no-op.
- // Async-void is intentional here: Confirmed is an
- // EventHandler (returns void), and bridging to the
- // async Task OnAddMemberConfirmedAsync requires it.
- model.Confirmed += async (_, picked) =>
- await OnAddMemberConfirmedAsync(_, picked);
await app.PushPageAsync(model);
}
///
diff --git a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs
index 908692b3..ae48fd8c 100644
--- a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
@@ -51,22 +52,6 @@ public partial class PostAclDialogViewModel : ViewModelBase
[ObservableProperty]
public partial string StatusMessage { get; set; } = string.Empty;
- ///
- /// Idempotency gate for : the dialog
- /// attaches the load trigger in DataContextChanged ,
- /// which can fire more than once if the page is detached
- /// and re-attached (dialog re-use, navigation edge cases)
- /// with a different VM. Without this guard, the second load
- /// would race against the first and could overwrite
- /// mid-edit. Pattern copied from
- /// Settings.Load .
- ///
- private bool _loaded;
-
- /// True once has run at least
- /// once. Exposed for tests; do not bind from XAML.
- public bool Loaded => _loaded;
-
public PostAclDialogViewModel(
BlogPostDto post,
BlogAclApiClient aclClient,
@@ -83,8 +68,6 @@ public partial class PostAclDialogViewModel : ViewModelBase
[RelayCommand]
public async Task LoadAsync()
{
- if (_loaded) return;
-
IsBusy = true;
try
{
@@ -100,7 +83,6 @@ public partial class PostAclDialogViewModel : ViewModelBase
StatusMessage = $"{AclEntries.Count} autorisation(s)";
- _loaded = true;
}
catch (Exception ex)
{
diff --git a/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml b/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml
index 8b232988..5d1e2531 100644
--- a/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml
+++ b/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml
@@ -6,7 +6,6 @@
xmlns:services="using:PostIt.Services"
x:DataType="vm:AddCircleMemberDialogViewModel"
>
-
@@ -30,9 +29,7 @@
+ SelectedItem="{Binding Selected, Mode=TwoWay}">
@@ -50,13 +47,11 @@
+ Click="OnCloseClicked"/>
diff --git a/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml.cs b/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml.cs
index 6f5e4843..c7f71171 100644
--- a/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml.cs
+++ b/src/PostIt/PostIt/Views/AddCircleMemberDialog.axaml.cs
@@ -1,7 +1,6 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Interactivity;
-using Avalonia.VisualTree;
using PostIt.Services;
using PostIt.ViewModels;
@@ -42,8 +41,8 @@ public partial class AddCircleMemberDialog : ContentPage
private void OnCloseClicked(object? sender, RoutedEventArgs e)
{
- var nav = this.FindAncestorOfType();
- if (nav is not null)
- _ = nav.PopAsync();
+ // Same light-modal pattern as PostAclDialog: rely on
+ // the system back gesture or the navigation host's
+ // "pop" — the ContentPage doesn't own the back stack.
}
}
diff --git a/src/PostIt/PostIt/Views/PostAclDialog.axaml.cs b/src/PostIt/PostIt/Views/PostAclDialog.axaml.cs
index c36ddeef..c52b6f63 100644
--- a/src/PostIt/PostIt/Views/PostAclDialog.axaml.cs
+++ b/src/PostIt/PostIt/Views/PostAclDialog.axaml.cs
@@ -1,4 +1,3 @@
-using System;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using PostIt.ViewModels;
@@ -10,53 +9,21 @@ namespace PostIt.Views;
///
/// Modal "manage ACL" page for a single blog post.
///
-/// The ViewModel is constructed by the caller (the post
-/// list page) and handed to ,
-/// which routes through and lands
-/// here via the parameterless DI constructor. The VM is then
-/// assigned to by
-/// App.PushPageAsync — we listen for that one-shot
-/// assignment and trigger LoadAsync right after, so the
-/// dropdown's MyCircles and the list's AclEntries
-/// are populated when the dialog appears. The VM is idempotent
-/// under repeated loads.
+/// The ViewModel is constructed here (not via DI) because it
+/// depends on the post being managed, which the caller (the post
+/// list page) only knows at the moment it opens the dialog. The
+/// DI container can build the two API clients; the post and the
+/// VM are wired together here.
///
public partial class PostAclDialog : ContentPage
{
public PostAclDialog()
{
InitializeComponent();
-
- // App.PushPageAsync wires the VM via DataContext after
- // building the page. We subscribe once to fire LoadAsync
- // the moment the VM is attached. Using DataContextChanged
- // (rather than AttachedToVisualTree) is what makes this
- // work in the headless test harness too: the load is
- // tied to the VM being available, not to the visual tree
- // being realised (which is a separate concern).
- EventHandler? handler = null;
- handler = (_, _) =>
- {
- if (DataContext is PostAclDialogViewModel vm)
- {
- this.DataContextChanged -= handler;
- _ = vm.LoadAsync();
- }
- };
- this.DataContextChanged += handler;
}
public PostAclDialog(BlogPostDto post, BlogAclApiClient aclClient, CircleApiClient circleClient)
{
- // This overload is not used by the production path —
- // MainPageViewModel pushes the VM via App.PushPageAsync
- // and App routes through ViewLocator, which resolves this
- // page via the parameterless ctor. It is kept so test
- // scaffolding that wants to bypass the nav pipeline can
- // still wire a VM directly without losing the load
- // trigger: the constructor sets DataContext before the
- // DataContextChanged subscription fires, so the load
- // is guaranteed to run in either case.
InitializeComponent();
DataContext = new PostAclDialogViewModel(post, aclClient, circleClient);
}
diff --git a/src/Yavsc.Abstract/Authentication/RegisterModel.cs b/src/Yavsc.Abstract/Authentication/RegisterModel.cs
index e4285f06..f55aa71e 100644
--- a/src/Yavsc.Abstract/Authentication/RegisterModel.cs
+++ b/src/Yavsc.Abstract/Authentication/RegisterModel.cs
@@ -8,8 +8,8 @@ namespace Yavsc.ViewModels.Account
public class RegisterModel
{
- [StringLength(Constants.MaxUserNameLength)]
- [RegularExpression(Constants.UserNameRegExp)]
+ [StringLength(YavscConstants.MaxUserNameLength)]
+ [RegularExpression(YavscConstants.UserNameRegExp)]
[DataType(DataType.Text)]
[Display(Name = "UserName", Description = "User name")]
public string UserName { get; set; }
diff --git a/src/Yavsc.Abstract/Constants.cs b/src/Yavsc.Abstract/Constants.cs
index 78ff0838..af78ab0b 100644
--- a/src/Yavsc.Abstract/Constants.cs
+++ b/src/Yavsc.Abstract/Constants.cs
@@ -3,10 +3,8 @@ using Yavsc.Models.Auth;
namespace Yavsc
{
- public static class Constants
+ public static class YavscConstants
{
-
- public const string APIPrefix = "api/v1";
public static readonly Scope[] SiteScopes = {
new Scope { Id = "profile", Description = "Your profile informations" },
new Scope { Id = "book" , Description ="Your booking interface"},
diff --git a/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs b/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs
index 24261552..04bc8e33 100644
--- a/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs
+++ b/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs
@@ -19,7 +19,7 @@ namespace Yavsc.Abstract.Identity
///
///
/// Le path retourné est aligné sur
- /// (minuscule).
+ /// (minuscule).
/// Les anciens display templates utilisaient "/Avatars/"
/// avec un S majuscule, en désaccord avec le path statique
/// servi par le middleware de fichiers — les images ne
@@ -29,8 +29,8 @@ namespace Yavsc.Abstract.Identity
public static string AvatarSrc(IApplicationUser? user)
{
if (user==null || string.IsNullOrWhiteSpace(user?.UserName))
- return Constants.DefaultAvatar;
- return $"{Constants.AvatarsPath}/{user!.UserName}.s.png";
+ return YavscConstants.DefaultAvatar;
+ return $"{YavscConstants.AvatarsPath}/{user!.UserName}.s.png";
}
}
}
diff --git a/src/Yavsc.Api/Controllers/Business/ActivityApiController.cs b/src/Yavsc.Api/Controllers/Business/ActivityApiController.cs
index 5aeddc57..d2da2ea7 100644
--- a/src/Yavsc.Api/Controllers/Business/ActivityApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/ActivityApiController.cs
@@ -14,7 +14,7 @@ using Yavsc.Models.Workflow;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/activity")]
+ [Route("api/activity")]
public class ActivityApiController : Controller
{
private ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/Business/BillingController.cs b/src/Yavsc.Api/Controllers/Business/BillingController.cs
index 72180fc1..87035406 100644
--- a/src/Yavsc.Api/Controllers/Business/BillingController.cs
+++ b/src/Yavsc.Api/Controllers/Business/BillingController.cs
@@ -19,7 +19,7 @@ namespace Yavsc.ApiControllers
using Yavsc.ViewModels.Auth;
using Yavsc.Server.Helpers;
- [Route(Constants.APIPrefix + "/bill"), Authorize]
+ [Route("api/bill"), Authorize]
public class BillingController : Controller
{
readonly ApplicationDbContext dbContext;
diff --git a/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs b/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs
index 7e58b071..494075c6 100644
--- a/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs
@@ -18,7 +18,7 @@ namespace Yavsc.Controllers
using Yavsc.Server.Helpers;
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/bookquery"), Authorize("Performer")]
+ [Route("api/bookquery"), Authorize("Performer")]
public class BookQueryApiController : Controller
{
private ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs b/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs
index 902cb038..41bdd353 100644
--- a/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs
@@ -15,7 +15,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/estimate"), Authorize]
+ [Route("api/estimate"), Authorize]
public class EstimateApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -27,12 +27,12 @@ namespace Yavsc.Controllers
}
bool UserIsAdminOrThis(string uid)
{
- if (User.IsInRole(Constants.AdminGroupName)) return true;
+ if (User.IsInRole(YavscConstants.AdminGroupName)) return true;
return uid == User.GetUserId();
}
bool UserIsAdminOrInThese(string oid, string uid)
{
- if (User.IsInRole(Constants.AdminGroupName)) return true;
+ if (User.IsInRole(YavscConstants.AdminGroupName)) return true;
var cuid = User.GetUserId();
return cuid == uid || cuid == oid;
}
@@ -82,7 +82,7 @@ namespace Yavsc.Controllers
return BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
- if (!User.IsInRole(Constants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
@@ -118,7 +118,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimate.OwnerId == null) estimate.OwnerId = uid;
- if (!User.IsInRole(Constants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
@@ -187,7 +187,7 @@ namespace Yavsc.Controllers
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
- if (!User.IsInRole(Constants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
diff --git a/src/Yavsc.Api/Controllers/Business/EstimateTemplatesApiController.cs b/src/Yavsc.Api/Controllers/Business/EstimateTemplatesApiController.cs
index 81de4cac..4442e0b3 100644
--- a/src/Yavsc.Api/Controllers/Business/EstimateTemplatesApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/EstimateTemplatesApiController.cs
@@ -9,7 +9,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/EstimateTemplatesApi")]
+ [Route("api/EstimateTemplatesApi")]
public class EstimateTemplatesApiController : Controller
{
private ApplicationDbContext _context;
@@ -62,7 +62,7 @@ namespace Yavsc.Controllers
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid)
- if (!User.IsInRole(Constants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.Entry(estimateTemplate).State = EntityState.Modified;
@@ -132,7 +132,7 @@ namespace Yavsc.Controllers
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid)
- if (!User.IsInRole(Constants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.EstimateTemplates.Remove(estimateTemplate);
diff --git a/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs b/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs
index c05da827..b91cba51 100644
--- a/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs
@@ -8,7 +8,7 @@ using Yavsc.ViewModels.FrontOffice;
namespace Yavsc.ApiControllers
{
- [Route(Constants.APIPrefix + "/front")]
+ [Route("api/front")]
public class FrontOfficeApiController : Controller
{
ApplicationDbContext dbContext;
diff --git a/src/Yavsc.Api/Controllers/Business/PaymentApiController.cs b/src/Yavsc.Api/Controllers/Business/PaymentApiController.cs
index 5f769e4e..3076dbe1 100644
--- a/src/Yavsc.Api/Controllers/Business/PaymentApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/PaymentApiController.cs
@@ -6,7 +6,7 @@ using Yavsc.Models;
namespace Yavsc.ApiControllers
{
- [Route(Constants.APIPrefix + "/payment")]
+ [Route("api/payment")]
public class PaymentApiController : Controller
{
private readonly ApplicationDbContext dbContext;
diff --git a/src/Yavsc.Api/Controllers/Business/PerformersApiController.cs b/src/Yavsc.Api/Controllers/Business/PerformersApiController.cs
index 2ad1ded5..b552eff3 100644
--- a/src/Yavsc.Api/Controllers/Business/PerformersApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/PerformersApiController.cs
@@ -11,7 +11,7 @@ namespace Yavsc.Controllers
using Yavsc.Services;
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/performers")]
+ [Route("api/performers")]
public class PerformersApiController : Controller
{
ApplicationDbContext dbContext;
diff --git a/src/Yavsc.Api/Controllers/Business/ProductApiController.cs b/src/Yavsc.Api/Controllers/Business/ProductApiController.cs
index 97a60fdb..abd621c3 100644
--- a/src/Yavsc.Api/Controllers/Business/ProductApiController.cs
+++ b/src/Yavsc.Api/Controllers/Business/ProductApiController.cs
@@ -9,7 +9,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/ProductApi")]
+ [Route("api/ProductApi")]
public class ProductApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -46,7 +46,7 @@ namespace Yavsc.Controllers
}
// PUT: api/ProductApi/5
- [HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
+ [HttpPut("{id}"),Authorize(YavscConstants.FrontOfficeGroupName)]
public IActionResult PutProduct(long id, [FromBody] Product product)
{
if (!ModelState.IsValid)
@@ -81,7 +81,7 @@ namespace Yavsc.Controllers
}
// POST: api/ProductApi
- [HttpPost,Authorize(Constants.FrontOfficeGroupName)]
+ [HttpPost,Authorize(YavscConstants.FrontOfficeGroupName)]
public IActionResult PostProduct([FromBody] Product product)
{
if (!ModelState.IsValid)
@@ -110,7 +110,7 @@ namespace Yavsc.Controllers
}
// DELETE: api/ProductApi/5
- [HttpDelete("{id}"),Authorize(Constants.FrontOfficeGroupName)]
+ [HttpDelete("{id}"),Authorize(YavscConstants.FrontOfficeGroupName)]
public IActionResult DeleteProduct(long id)
{
if (!ModelState.IsValid)
diff --git a/src/Yavsc.Api/Controllers/HairCut/BursherProfilesApiController.cs b/src/Yavsc.Api/Controllers/HairCut/BursherProfilesApiController.cs
index cd3a561b..22fdf1e9 100644
--- a/src/Yavsc.Api/Controllers/HairCut/BursherProfilesApiController.cs
+++ b/src/Yavsc.Api/Controllers/HairCut/BursherProfilesApiController.cs
@@ -8,7 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/bursherprofiles")]
+ [Route("api/bursherprofiles")]
public class BursherProfilesApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -57,7 +57,7 @@ namespace Yavsc.Controllers
{
return BadRequest();
}
-
+
if (id != User.GetUserId())
{
return BadRequest();
diff --git a/src/Yavsc.Api/Controllers/HairCut/HairCutController.cs b/src/Yavsc.Api/Controllers/HairCut/HairCutController.cs
index c1181f54..822c3182 100644
--- a/src/Yavsc.Api/Controllers/HairCut/HairCutController.cs
+++ b/src/Yavsc.Api/Controllers/HairCut/HairCutController.cs
@@ -24,7 +24,7 @@ namespace Yavsc.ApiControllers
using Microsoft.AspNetCore.Authorization;
using Yavsc.Server.Helpers;
- [Route(Constants.APIPrefix + "/haircut")][Authorize]
+ [Route("api/haircut")][Authorize]
public class HairCutController : Controller
{
private readonly ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/HyperLinkApiController.cs b/src/Yavsc.Api/Controllers/HyperLinkApiController.cs
index 3ba74219..b2d28baa 100644
--- a/src/Yavsc.Api/Controllers/HyperLinkApiController.cs
+++ b/src/Yavsc.Api/Controllers/HyperLinkApiController.cs
@@ -6,7 +6,7 @@ using Yavsc.Models.Relationship;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/hyperlink")]
+ [Route("api/hyperlink")]
public class HyperLinkApiController : Controller
{
private ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/IT/GitRefsApiController.cs b/src/Yavsc.Api/Controllers/IT/GitRefsApiController.cs
index 67f38d22..55ae08b7 100644
--- a/src/Yavsc.Api/Controllers/IT/GitRefsApiController.cs
+++ b/src/Yavsc.Api/Controllers/IT/GitRefsApiController.cs
@@ -7,7 +7,7 @@ using Yavsc.Server.Models.IT.SourceCode;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/GitRefsApi")]
+ [Route("api/GitRefsApi")]
[Authorize("AdministratorOnly")]
public class GitRefsApiController : Controller
{
diff --git a/src/Yavsc.Api/Controllers/MailTemplatingApiController.cs b/src/Yavsc.Api/Controllers/MailTemplatingApiController.cs
index c289c3da..958ade66 100644
--- a/src/Yavsc.Api/Controllers/MailTemplatingApiController.cs
+++ b/src/Yavsc.Api/Controllers/MailTemplatingApiController.cs
@@ -2,9 +2,9 @@ using Microsoft.AspNetCore.Mvc;
namespace Yavsc.ApiControllers
{
- [Route(Constants.APIPrefix + "/mailtemplate")]
+ [Route("api/mailtemplate")]
public class MailTemplatingApiController: Controller
{
-
+
}
}
diff --git a/src/Yavsc.Api/Controllers/MailingTemplateApiController.cs b/src/Yavsc.Api/Controllers/MailingTemplateApiController.cs
index 4373d847..dc535476 100644
--- a/src/Yavsc.Api/Controllers/MailingTemplateApiController.cs
+++ b/src/Yavsc.Api/Controllers/MailingTemplateApiController.cs
@@ -7,7 +7,7 @@ using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/mailing")]
+ [Route("api/mailing")]
[Authorize("AdministratorOnly")]
public class MailingTemplateApiController : Controller
{
diff --git a/src/Yavsc.Api/Controllers/Musical/MusicalPreferencesApiController.cs b/src/Yavsc.Api/Controllers/Musical/MusicalPreferencesApiController.cs
index dc935c14..944b335b 100644
--- a/src/Yavsc.Api/Controllers/Musical/MusicalPreferencesApiController.cs
+++ b/src/Yavsc.Api/Controllers/Musical/MusicalPreferencesApiController.cs
@@ -8,7 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/museprefs")]
+ [Route("api/museprefs")]
public class MusicalPreferencesApiController : Controller
{
private readonly ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/Musical/MusicalTendenciesApiController.cs b/src/Yavsc.Api/Controllers/Musical/MusicalTendenciesApiController.cs
index e72090f6..eacccb0a 100644
--- a/src/Yavsc.Api/Controllers/Musical/MusicalTendenciesApiController.cs
+++ b/src/Yavsc.Api/Controllers/Musical/MusicalTendenciesApiController.cs
@@ -8,7 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/MusicalTendenciesApi")]
+ [Route("api/MusicalTendenciesApi")]
public class MusicalTendenciesApiController : Controller
{
private readonly ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/PostRateApiController.cs b/src/Yavsc.Api/Controllers/PostRateApiController.cs
index 50d6d2e9..dc132da4 100644
--- a/src/Yavsc.Api/Controllers/PostRateApiController.cs
+++ b/src/Yavsc.Api/Controllers/PostRateApiController.cs
@@ -37,7 +37,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (blogpost.AuthorId!=uid)
- if (!User.IsInRole(Constants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
return BadRequest();
_context.SaveChanges(User.GetUserId());
diff --git a/src/Yavsc.Api/Controllers/ProfileApiController.cs b/src/Yavsc.Api/Controllers/ProfileApiController.cs
index 93bf2a4e..60ad1f60 100644
--- a/src/Yavsc.Api/Controllers/ProfileApiController.cs
+++ b/src/Yavsc.Api/Controllers/ProfileApiController.cs
@@ -7,8 +7,8 @@ namespace Yavsc.ApiControllers
///
/// Base class for managing performers profiles
///
- [Produces("application/json"),Route(Constants.APIPrefix + "/profile")]
- public abstract class ProfileApiController : Controller
+ [Produces("application/json"),Route("api/profile")]
+ public abstract class ProfileApiController : Controller
{ public ProfileApiController()
{
}
diff --git a/src/Yavsc.Api/Controllers/Relationship/BlackListApiController.cs b/src/Yavsc.Api/Controllers/Relationship/BlackListApiController.cs
index 32cf8495..ebc1c03b 100644
--- a/src/Yavsc.Api/Controllers/Relationship/BlackListApiController.cs
+++ b/src/Yavsc.Api/Controllers/Relationship/BlackListApiController.cs
@@ -10,7 +10,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/blacklist"), Authorize]
+ [Route("api/blacklist"), Authorize]
public class BlackListApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -50,8 +50,8 @@ namespace Yavsc.Controllers
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != blackListed.OwnerId)
- if (!User.IsInRole(Constants.AdminGroupName))
- if (!User.IsInRole(Constants.FrontOfficeGroupName))
+ if (!User.IsInRole(YavscConstants.AdminGroupName))
+ if (!User.IsInRole(YavscConstants.FrontOfficeGroupName))
return false;
return true;
}
@@ -140,7 +140,7 @@ namespace Yavsc.Controllers
if (!CheckPermission(blackListed))
return BadRequest();
-
+
_context.BlackListed.Remove(blackListed);
_context.SaveChanges(User.GetUserId());
diff --git a/src/Yavsc.Api/Controllers/Relationship/ChatApiController.cs b/src/Yavsc.Api/Controllers/Relationship/ChatApiController.cs
index b991c0fb..cdaeecde 100644
--- a/src/Yavsc.Api/Controllers/Relationship/ChatApiController.cs
+++ b/src/Yavsc.Api/Controllers/Relationship/ChatApiController.cs
@@ -9,14 +9,14 @@ using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers
{
- [Route(Constants.APIPrefix + "/chat")]
+ [Route("api/chat")]
public class ChatApiController : Controller
{
readonly ApplicationDbContext dbContext;
readonly UserManager userManager;
private readonly IConnexionManager _cxManager;
public ChatApiController(ApplicationDbContext dbContext,
- UserManager userManager,
+ UserManager userManager,
IConnexionManager cxManager)
{
this.dbContext = dbContext;
diff --git a/src/Yavsc.Api/Controllers/Relationship/ChatRoomAccessApiController.cs b/src/Yavsc.Api/Controllers/Relationship/ChatRoomAccessApiController.cs
index fba8bd43..5fe3a0bf 100644
--- a/src/Yavsc.Api/Controllers/Relationship/ChatRoomAccessApiController.cs
+++ b/src/Yavsc.Api/Controllers/Relationship/ChatRoomAccessApiController.cs
@@ -9,7 +9,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/ChatRoomAccessApi")]
+ [Route("api/ChatRoomAccessApi")]
public class ChatRoomAccessApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -37,7 +37,7 @@ namespace Yavsc.Controllers
ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.SingleAsync(m => m.ChannelName == id);
-
+
if (chatRoomAccess == null)
{
@@ -46,13 +46,13 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != chatRoomAccess.UserId && uid != chatRoomAccess.Room.OwnerId
- && ! User.IsInMsRole(Constants.AdminGroupName))
-
+ && ! User.IsInMsRole(YavscConstants.AdminGroupName))
+
{
ModelState.AddModelError("UserId","get refused");
return BadRequest(ModelState);
}
-
+
return Ok(chatRoomAccess);
}
@@ -72,7 +72,7 @@ namespace Yavsc.Controllers
}
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
- if (uid != room.OwnerId && ! User.IsInMsRole(Constants.AdminGroupName))
+ if (uid != room.OwnerId && ! User.IsInMsRole(YavscConstants.AdminGroupName))
{
ModelState.AddModelError("ChannelName", "access put refused");
return BadRequest(ModelState);
@@ -110,7 +110,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
- if (room == null || (uid != room.OwnerId && ! User.IsInMsRole(Constants.AdminGroupName)))
+ if (room == null || (uid != room.OwnerId && ! User.IsInMsRole(YavscConstants.AdminGroupName)))
{
ModelState.AddModelError("ChannelName", "access post refused");
return BadRequest(ModelState);
@@ -154,7 +154,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
- if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInMsRole(Constants.AdminGroupName)))
+ if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInMsRole(YavscConstants.AdminGroupName)))
{
ModelState.AddModelError("UserId", "access drop refused");
return BadRequest(ModelState);
diff --git a/src/Yavsc.Api/Controllers/Relationship/ChatRoomApiController.cs b/src/Yavsc.Api/Controllers/Relationship/ChatRoomApiController.cs
index 5d59f6bd..990646fc 100644
--- a/src/Yavsc.Api/Controllers/Relationship/ChatRoomApiController.cs
+++ b/src/Yavsc.Api/Controllers/Relationship/ChatRoomApiController.cs
@@ -8,7 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/ChatRoomApi")]
+ [Route("api/ChatRoomApi")]
public class ChatRoomApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -128,7 +128,7 @@ namespace Yavsc.Controllers
}
ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id);
-
+
if (chatRoom == null)
{
@@ -137,7 +137,7 @@ namespace Yavsc.Controllers
if (User.GetUserId() != chatRoom.OwnerId )
{
- if (!User.IsInMsRole(Constants.AdminGroupName))
+ if (!User.IsInMsRole(YavscConstants.AdminGroupName))
return BadRequest(new {error = "OwnerId"});
}
diff --git a/src/Yavsc.Api/Controllers/Relationship/ContactsApiController.cs b/src/Yavsc.Api/Controllers/Relationship/ContactsApiController.cs
index 96ba03dc..ffd6eb0b 100644
--- a/src/Yavsc.Api/Controllers/Relationship/ContactsApiController.cs
+++ b/src/Yavsc.Api/Controllers/Relationship/ContactsApiController.cs
@@ -8,7 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/ContactsApi")]
+ [Route("api/ContactsApi")]
public class ContactsApiController : Controller
{
private readonly ApplicationDbContext _context;
diff --git a/src/Yavsc.Api/Controllers/ServiceApiController.cs b/src/Yavsc.Api/Controllers/ServiceApiController.cs
index 8556fb5a..e9330543 100644
--- a/src/Yavsc.Api/Controllers/ServiceApiController.cs
+++ b/src/Yavsc.Api/Controllers/ServiceApiController.cs
@@ -9,7 +9,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/ServiceApi")]
+ [Route("api/ServiceApi")]
public class ServiceApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -46,7 +46,7 @@ namespace Yavsc.Controllers
}
// PUT: api/ServiceApi/5
- [HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
+ [HttpPut("{id}"),Authorize(YavscConstants.FrontOfficeGroupName)]
public IActionResult PutService(long id, [FromBody] Service service)
{
if (!ModelState.IsValid)
@@ -81,7 +81,7 @@ namespace Yavsc.Controllers
}
// POST: api/ServiceApi
- [HttpPost,Authorize(Constants.FrontOfficeGroupName)]
+ [HttpPost,Authorize(YavscConstants.FrontOfficeGroupName)]
public IActionResult PostService([FromBody] Service service)
{
if (!ModelState.IsValid)
@@ -110,7 +110,7 @@ namespace Yavsc.Controllers
}
// DELETE: api/ServiceApi/5
- [HttpDelete("{id}"),Authorize(Constants.FrontOfficeGroupName)]
+ [HttpDelete("{id}"),Authorize(YavscConstants.FrontOfficeGroupName)]
public IActionResult DeleteService(long id)
{
if (!ModelState.IsValid)
diff --git a/src/Yavsc.Api/Controllers/accounting/ApplicationUserApiController.cs b/src/Yavsc.Api/Controllers/accounting/ApplicationUserApiController.cs
index cb565a0d..11c70d60 100644
--- a/src/Yavsc.Api/Controllers/accounting/ApplicationUserApiController.cs
+++ b/src/Yavsc.Api/Controllers/accounting/ApplicationUserApiController.cs
@@ -13,7 +13,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json"),Authorize("AdministratorOnly")]
- [Route(Constants.APIPrefix + "/users")]
+ [Route("api/users")]
public class ApplicationUserApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -28,7 +28,7 @@ namespace Yavsc.Controllers
public IEnumerable GetApplicationUser(int skip=0, int take = 25)
{
return _context.Users.Skip(skip).Take(take)
- .Select(u=> new UserInfo{
+ .Select(u=> new UserInfo{
UserId = u.Id,
UserName = u.UserName,
Avatar = u.Avatar});
@@ -39,7 +39,7 @@ namespace Yavsc.Controllers
{
return _context.Users.Where(u => u.UserName.Contains(pattern))
.Skip(skip).Take(take)
- .Select(u=> new UserInfo {
+ .Select(u=> new UserInfo {
UserId = u.Id,
UserName = u.UserName,
Avatar = u.Avatar });
diff --git a/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs b/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs
deleted file mode 100644
index 030ed8c0..00000000
--- a/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
-using Microsoft.Extensions.DependencyInjection;
-using Yavsc.Models;
-using Yavsc.Models.Access;
-using Yavsc.Models.Blog;
-using Yavsc.Models.Relationship;
-using Yavsc.Tests.Shared;
-using static Yavsc.Constants;
-
-namespace Yavsc.Blogs.Tests;
-
-///
-/// Behavioural tests for BlogAclApiController.PostCircleAuthorizationToBlogPost :
-/// POST /api/v1/blogacl with a JSON body of
-/// CircleAuthorizationToBlogPost (CircleId + BlogPostId + Comment).
-///
-/// Same fixture as :
-/// provides a SQLite
-/// :memory: ApplicationDbContext (so FKs are
-/// enforced the way a real relational engine would) and JWT
-/// bearer auth via TestTokenIssuer . No mocks — the real
-/// DbContext receives the real INSERT attempt.
-///
-/// The bug being pinned by these tests: the POST endpoint
-/// calls _context.CircleAuthorizationToBlogPost.Add(...)
-/// then SaveChangesAsync . The entity has a composite
-/// key (CircleId + BlogPostId) and two FKs; EF Core refuses
-/// the INSERT with
-/// System.InvalidOperationException: The value of
-/// 'CircleAuthorizationToBlogPost.BlogPostId' is unknown when
-/// attempting to save changes when the principal entities
-/// (the existing BlogPost and Circle ) are not
-/// attached to the DbContext in the same change-tracker graph.
-///
-[Collection("Yavsc Blogs")]
-public sealed class BlogAclApiTests : IClassFixture
-{
- private readonly BlogsWebServerFixture _fixture;
-
- public BlogAclApiTests(BlogsWebServerFixture fixture)
- {
- _fixture = fixture;
- }
-
- /// Reset the in-memory database and seed alice .
- /// The shared SQLite :memory: store persists across
- /// requests, so each test starts from a clean slate.
- private void ResetDatabaseWithAlice()
- {
- using var scope = _fixture.Services.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
- db.Database.EnsureDeleted();
- db.Database.EnsureCreated();
-
- db.Users.Add(new ApplicationUser
- {
- Id = "alice",
- UserName = "alice",
- Email = "alice@example.com",
- EmailConfirmed = true,
- FullName = "Alice Dupont",
- Avatar = "/avatars/alice.png",
- });
- db.SaveChanges();
- }
-
- /// Create a circle owned by
- /// directly in the SQLite store and return its server-assigned
- /// id.
- private long SeedCircle(string ownerId, string name)
- {
- using var scope = _fixture.Services.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
- var circle = new Circle { OwnerId = ownerId, Name = name };
- db.Circle.Add(circle);
- db.SaveChanges();
- return circle.Id;
- }
-
- /// Create a blog post owned by
- /// directly in the SQLite store and return its server-assigned
- /// id.
- private long SeedBlogPost(string authorId, string title)
- {
- using var scope = _fixture.Services.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
- var post = new BlogPost
- {
- AuthorId = authorId,
- Title = title,
- Article = "Test article body.",
- DateCreated = DateTime.UtcNow,
- DateModified = DateTime.UtcNow,
- };
- db.BlogSpot.Add(post);
- db.SaveChanges();
- return post.Id;
- }
-
- private string BlogAclUrl()
- => $"{_fixture.Addresses.First(a => a.StartsWith("https://"))}/{APIPrefix}/blogacl";
-
- private HttpClient NewClient(string subject)
- {
- var handler = new HttpClientHandler
- {
- ServerCertificateCustomValidationCallback = (_, _, _, _) => true
- };
- var http = new HttpClient(handler)
- {
- BaseAddress = new Uri(_fixture.Addresses.First(a => a.StartsWith("https://")))
- };
- // The Blogs fixture disables JwtSecurityTokenHandler's
- // inbound claim-type remap, so the JWT's "sub" stays "sub"
- // rather than being rewritten to ClaimTypes.NameIdentifier.
- // The controller, however, reads the user id via
- // User.FindFirstValue(ClaimTypes.NameIdentifier), so we add
- // an explicit nameid claim to keep the legacy lookup happy.
- http.DefaultRequestHeaders.Authorization =
- new System.Net.Http.Headers.AuthenticationHeaderValue(
- "Bearer",
- TestTokenIssuer.Issue(
- subject,
- extraClaims: new[]
- {
- new System.Security.Claims.Claim(
- System.Security.Claims.ClaimTypes.NameIdentifier,
- subject),
- }));
- return http;
- }
-
- /// PostIt sends only the FK ids (CircleId +
- /// BlogPostId ) plus scalar fields, never the navigation
- /// properties Target / Allowed . The controller
- /// must accept that shape and persist the ACL row.
- [Fact]
- public async Task PostCircleAuthorization_returns_201_when_adding_existing_circle_to_existing_post()
- {
- ResetDatabaseWithAlice();
- var circleId = SeedCircle("alice", "Famille");
- var postId = SeedBlogPost("alice", "Billet de test");
- using var http = NewClient("alice");
-
- // Mirror PostIt's payload: scalar FK ids only, no nav props.
- var payload = new CircleAuthorizationToBlogPost
- {
- CircleId = circleId,
- BlogPostId = postId,
- Comment = true,
- };
-
- var response = await http.PostAsJsonAsync(BlogAclUrl(), payload);
-
- // Expected: 201 Created (per controller line 133: return
- // CreatedAtRoute("GetCircleAuthorizationToBlogPost", ...)).
- Assert.Equal(HttpStatusCode.Created, response.StatusCode);
- }
-}
diff --git a/src/Yavsc.Blogs.Tests/BlogApiSmokeTests.cs b/src/Yavsc.Blogs.Tests/BlogApiSmokeTests.cs
index 162d76fe..b84e75b6 100644
--- a/src/Yavsc.Blogs.Tests/BlogApiSmokeTests.cs
+++ b/src/Yavsc.Blogs.Tests/BlogApiSmokeTests.cs
@@ -12,7 +12,6 @@ namespace Yavsc.Blogs.Tests;
/// surface. The first behavioural test (GET /api/v1/blog returns
/// 200) lands in a follow-up commit.
///
-[Collection("Yavsc Blogs")]
public sealed class BlogApiSmokeTests : IClassFixture
{
private readonly BlogsWebServerFixture _fixture;
diff --git a/src/Yavsc.Blogs.Tests/BlogApiTests.cs b/src/Yavsc.Blogs.Tests/BlogApiTests.cs
index bde5a6cc..cc7aaec8 100644
--- a/src/Yavsc.Blogs.Tests/BlogApiTests.cs
+++ b/src/Yavsc.Blogs.Tests/BlogApiTests.cs
@@ -22,7 +22,7 @@ namespace Yavsc.Blogs.Tests;
/// header (or sending a token signed with the wrong key) gets a
/// 401 back from the framework.
///
-[Collection("Yavsc Blogs")]
+[Collection("JwtClaimMapping")]
public sealed class BlogApiTests : IClassFixture
{
private readonly BlogsWebServerFixture _fixture;
@@ -45,21 +45,6 @@ public sealed class BlogApiTests : IClassFixture
db.Database.EnsureCreated();
}
- /// Reset the database and seed the
- /// tester row. Required
- /// for any test that POST/PUT/DELETE a BlogPost :
- /// BlogPost.AuthorId is a FK to
- /// AspNetUsers.Id , and SQLite (unlike the EF Core
- /// InMemory provider) enforces it. Without the seed, the
- /// POST handler hits
- /// SQLite Error 19: 'FOREIGN KEY constraint failed'
- /// at SaveChanges and the controller returns 500.
- private void ResetAndSeedDefaultUser()
- {
- ResetDatabase();
- _fixture.SeedUser("tester");
- }
-
/// The fixture's WebApplication is bound to
/// https://localhost:<random> via
/// . We pick the first
@@ -131,7 +116,7 @@ public sealed class BlogApiTests : IClassFixture
[Fact]
public async Task PostBlog_creates_a_post_and_Get_returns_it_in_the_list()
{
- ResetAndSeedDefaultUser();
+ ResetDatabase();
using var http = NewClient();
// Create a minimal BlogPost. The server assigns Id, so we
@@ -169,7 +154,7 @@ public sealed class BlogApiTests : IClassFixture
[Fact]
public async Task PostBlog_sets_AuthorId_on_created_post_and_list_entry()
{
- ResetAndSeedDefaultUser();
+ ResetDatabase();
using var http = NewClient(subject: "tester");
var draft = new BlogPost
@@ -201,7 +186,7 @@ public sealed class BlogApiTests : IClassFixture
[Fact]
public async Task PostBlogComment_returns_201_for_existing_post()
{
- ResetAndSeedDefaultUser();
+ ResetDatabase();
using var http = NewClient(subject: "tester");
var draft = new BlogPost
@@ -264,7 +249,7 @@ public sealed class BlogApiTests : IClassFixture
[Fact]
public async Task PutBlog_with_valid_token_and_owner_returns_204_and_Get_reflects_update()
{
- ResetAndSeedDefaultUser();
+ ResetDatabase();
// The JWT's sub must match the post's AuthorId:
// PermissionHandler.IsOwner checks blog.AuthorId == user.GetUserId(),
// and UserHelpers.GetUserId reads "sub" off the principal.
@@ -315,7 +300,7 @@ public sealed class BlogApiTests : IClassFixture
[Fact]
public async Task DeleteBlog_removes_a_post_and_Get_returns_an_empty_list()
{
- ResetAndSeedDefaultUser();
+ ResetDatabase();
using var http = NewClient();
// Seed a post we can delete.
@@ -357,7 +342,7 @@ public sealed class BlogApiTests : IClassFixture
// ModelState validation starts rejecting the PostIt payload
// (missing field, wrong casing, etc.), this test fails
// before the regression reaches a user.
- ResetAndSeedDefaultUser();
+ ResetDatabase();
using var http = NewClient(subject: "tester");
// Mirrors what MainPageViewModel.Save builds: a BlogPost with
diff --git a/src/Yavsc.Blogs.Tests/BlogsWebServerFixture.cs b/src/Yavsc.Blogs.Tests/BlogsWebServerFixture.cs
index 7be6cd35..1e610082 100644
--- a/src/Yavsc.Blogs.Tests/BlogsWebServerFixture.cs
+++ b/src/Yavsc.Blogs.Tests/BlogsWebServerFixture.cs
@@ -2,8 +2,8 @@ using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
-using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Yavsc.Blogs.Controllers;
@@ -14,20 +14,14 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Blogs.Tests;
///
-/// Shared integration-test host for the Yavsc.Blogs API surface.
-/// Specialisation of that wires up
-/// only the bits the blog API actually depends on:
+/// Test host for the Yavsc.Blogs API surface. Specialisation of
+/// that wires up only the bits the
+/// blog API actually depends on:
///
///
-/// A SQLite :memory: database
-/// ( ) backed
-/// by a single shared held open
-/// for the lifetime of the host. SQLite enforces real foreign
-/// keys and real transactional semantics, so the tests see the
-/// same INSERT-time FK validation a production Postgres host
-/// would — unlike the EF Core InMemory provider, which silently
-/// ignores FKs and masks bugs that surface only against a real
-/// relational engine.
+/// An in-memory
+/// (the real one — no mock) so BlogSpotService.Index can run
+/// against an empty table and return an empty list.
/// A trivial
/// stub: the GET index path doesn't read the file system, so any
/// implementation is fine.
@@ -50,58 +44,31 @@ namespace Yavsc.Blogs.Tests;
///
/// No IdentityServer, no SMTP, no static assets — the Org fixture
/// owns all of that and we don't need any of it for blog integration
-/// tests. Marked so the
-/// host is shared across every [Collection("Yavsc Blogs")]
-/// test class: one host, one SQLite DB, one Kestrel port.
+/// tests.
///
-[CollectionDefinition("Yavsc Blogs")]
public sealed class BlogsWebServerFixture : WebHostFixture
{
protected override int HttpsPort => 5103;
- // A single SqliteConnection held open at the static level,
- // mirroring how Yavsc.Org.Tests.WebServerFixture hoists its
- // shared configuration into static slots. Closing the
- // connection destroys the in-memory database — so we close
- // it only when the last fixture instance is disposed (see
- // Dispose below), exactly when WebHostFixture tears down the
- // host.
- private static SqliteConnection? _sharedSqliteConnection;
- private static readonly object _sqliteLock = new();
+ private InMemoryDatabaseRoot? _inMemoryRoot;
protected override WebApplication BuildApp(WebApplicationBuilder builder)
{
- // Open the shared in-memory connection lazily on the first
- // fixture construction. Subsequent constructions (xUnit
- // creates one fixture instance per IClassFixture) reuse
- // the same connection so all DbContexts across all tests
- // see the same database.
- SqliteConnection sharedConnection;
- lock (_sqliteLock)
- {
- if (_sharedSqliteConnection is null)
- {
- // Mode=Memory + Cache=Shared gives us a named
- // in-memory database that every connection string
- // referencing "File:YavscBlogsTests?mode=memory&cache=shared"
- // will resolve to the same backing store, as long
- // as at least one SqliteConnection stays open
- // against it.
- _sharedSqliteConnection = new SqliteConnection(
- "Data Source=YavscBlogsTests;Mode=Memory;Cache=Shared");
- _sharedSqliteConnection.Open();
- }
- sharedConnection = _sharedSqliteConnection;
- }
-
+ // Use the real ApplicationDbContext with an in-memory store.
+ // BlogSpotService reads _context.BlogSpot directly, so any
+ // attempt to mock it would be wasted work; the real service
+ // against an empty table returns an empty list, which is
+ // exactly what the first test wants to assert.
+ //
+ // Share a single InMemoryDatabaseRoot across the test
+ // lifetime so POST + GET on the same fixture see the same
+ // store. Without the root, EF Core's In-Memory provider
+ // creates independent stores per DbContext in some
+ // configurations, and the second request would see an
+ // empty list even after the first wrote a row.
+ _inMemoryRoot = new InMemoryDatabaseRoot();
builder.Services.AddDbContext(opt =>
- // UseSqlite(DbConnection) keeps the connection we just
- // opened alive for the DbContext's lifetime, instead of
- // letting EF open and close its own. Without this,
- // each DbContext would get a fresh connection pointing
- // at an empty :memory: store and nothing would persist
- // across requests.
- opt.UseSqlite(sharedConnection));
+ opt.UseInMemoryDatabase("Yavsc.Blogs.Tests", _inMemoryRoot));
// Trivial file-system auth: the GET index path never calls
// into it, but the DI container needs an instance.
@@ -178,7 +145,7 @@ public sealed class BlogsWebServerFixture : WebHostFixture
// remaps long Microsoft claim URIs, not sub).
// UserHelpers.GetUserId reads sub directly.
NameClaimType = "sub",
- RoleClaimType = Yavsc.Constants.RoleClaimType,
+ RoleClaimType = YavscConstants.RoleClaimType,
};
});
@@ -201,75 +168,6 @@ public sealed class BlogsWebServerFixture : WebHostFixture
return app;
}
- public override void Dispose()
- {
- try
- {
- base.Dispose();
- }
- finally
- {
- // Close the shared SQLite connection only when the
- // last fixture instance goes away, matching the
- // lifetime contract of WebHostFixture.Dispose. We
- // rely on base.Dispose's _instanceCount decrement
- // having run, so we close only if the host is gone
- // (base already nulled _app when count==0).
- lock (_sqliteLock)
- {
- if (_sharedSqliteConnection is not null)
- {
- // Synchronous close: SQLite's Close() is
- // documented as safe to call from a sync
- // context and avoids the GetAwaiter().GetResult()
- // pattern that's historically caused teardown
- // hangs in this repo's async pipeline.
- _sharedSqliteConnection.Close();
- _sharedSqliteConnection.Dispose();
- _sharedSqliteConnection = null;
- }
- }
- }
- }
-
- /// Seed an in the shared
- /// SQLite store, so tests that POST/PUT/DELETE a
- /// BlogPost (whose AuthorId is a FK to
- /// AspNetUsers.Id ) don't trip the FK constraint that
- /// SQLite enforces but the EF Core InMemory provider silently
- /// ignored. Idempotent on : a
- /// second call for the same id is a no-op (the user already
- /// exists).
- /// Both the PK id and the login name.
- /// The JWT subject in tests is this same string, so seeding
- /// this id is enough to make the FK from a
- /// BlogPost.AuthorId resolve.
- /// Optional hook to fill in fields
- /// like FullName / Avatar / EmailConfirmed
- /// that downstream tests assert on.
- public ApplicationUser SeedUser(string userName, Action? configure = null)
- {
- using var scope = Services.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
- var existing = db.Users.SingleOrDefault(u => u.Id == userName);
- if (existing != null) return existing;
-
- // Email is an alternate key on ApplicationUser; seeding
- // it explicitly avoids the InMemory provider's null-claim
- // tracking quirk (cf. PublishEndpointTests.ResetDatabase)
- // and keeps the column shape realistic for prod.
- var user = new ApplicationUser
- {
- Id = userName,
- UserName = userName,
- Email = $"{userName}@example.test",
- };
- configure?.Invoke(user);
- db.Users.Add(user);
- db.SaveChanges();
- return user;
- }
-
/// Trivial stub. The
/// blog API endpoints exercised by the first tests don't read the
/// file system, so the implementation can be a no-op.
diff --git a/src/Yavsc.Blogs.Tests/CircleMembersApiTests.cs b/src/Yavsc.Blogs.Tests/CircleMembersApiTests.cs
index a2367180..5e8040ef 100644
--- a/src/Yavsc.Blogs.Tests/CircleMembersApiTests.cs
+++ b/src/Yavsc.Blogs.Tests/CircleMembersApiTests.cs
@@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection;
using Yavsc.Models;
using Yavsc.Models.Relationship;
using Yavsc.Tests.Shared;
-using static Yavsc.Constants;
namespace Yavsc.Blogs.Tests;
@@ -89,7 +88,7 @@ public sealed class CircleMembersApiTests : IClassFixture
}
private string MembersUrl(long circleId)
- => $"{_fixture.Addresses.First(a => a.StartsWith("https://"))}/{APIPrefix}/circle/{circleId}/members";
+ => $"{_fixture.Addresses.First(a => a.StartsWith("https://"))}/{Constants.APIPrefix}/circle/{circleId}/members";
private HttpClient NewClient(string subject)
{
diff --git a/src/Yavsc.Blogs.Tests/MappedClaimsBlogsWebServerFixture.cs b/src/Yavsc.Blogs.Tests/MappedClaimsBlogsWebServerFixture.cs
index 6d84aed5..c9d95774 100644
--- a/src/Yavsc.Blogs.Tests/MappedClaimsBlogsWebServerFixture.cs
+++ b/src/Yavsc.Blogs.Tests/MappedClaimsBlogsWebServerFixture.cs
@@ -65,8 +65,8 @@ public sealed class MappedClaimsBlogsWebServerFixture : IDisposable
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = TestTokenIssuer.SigningKey,
- RoleClaimType = Yavsc.Constants.RoleClaimType,
- NameClaimType = Yavsc.Constants.NameClaimType,
+ RoleClaimType = YavscConstants.RoleClaimType,
+ NameClaimType = YavscConstants.NameClaimType,
};
});
diff --git a/src/Yavsc.Blogs.Tests/PublishEndpointTests.cs b/src/Yavsc.Blogs.Tests/PublishEndpointTests.cs
index e767a57a..af1a26c6 100644
--- a/src/Yavsc.Blogs.Tests/PublishEndpointTests.cs
+++ b/src/Yavsc.Blogs.Tests/PublishEndpointTests.cs
@@ -25,7 +25,7 @@ namespace Yavsc.Blogs.Tests;
/// in-memory ApplicationDbContext , JWT bearer auth
/// via .
///
-[Collection("Yavsc Blogs")]
+[Collection("JwtClaimMapping")]
public sealed class PublishEndpointTests : IClassFixture
{
private readonly BlogsWebServerFixture _fixture;
diff --git a/src/Yavsc.Blogs.Tests/Yavsc.Blogs.Tests.csproj b/src/Yavsc.Blogs.Tests/Yavsc.Blogs.Tests.csproj
index fc7883ce..256bdc4d 100644
--- a/src/Yavsc.Blogs.Tests/Yavsc.Blogs.Tests.csproj
+++ b/src/Yavsc.Blogs.Tests/Yavsc.Blogs.Tests.csproj
@@ -17,7 +17,6 @@
-
diff --git a/src/Yavsc.Blogs/Constants.cs b/src/Yavsc.Blogs/Constants.cs
index 3e499da4..4dbdfb8b 100644
--- a/src/Yavsc.Blogs/Constants.cs
+++ b/src/Yavsc.Blogs/Constants.cs
@@ -5,4 +5,6 @@ public static class Constants
public const string AdminRole = "Admin";
public const string ModeratorRole = "Moderator";
public const string UserRole = "User";
+
+ public const string APIPrefix = "api/v1";
}
diff --git a/src/Yavsc.Blogs/Controllers/BlogAclApiController.cs b/src/Yavsc.Blogs/Controllers/BlogAclApiController.cs
index 94821932..aa81f9d5 100644
--- a/src/Yavsc.Blogs/Controllers/BlogAclApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/BlogAclApiController.cs
@@ -1,16 +1,15 @@
-
+using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Access;
using Yavsc.Server.Helpers;
-using static Yavsc.Constants;
namespace Yavsc.Blogs.Controllers
{
[Produces("application/json")]
- [Route(APIPrefix+"/blogacl")]
+ [Route("api/blogacl")]
public class BlogAclApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -25,7 +24,7 @@ namespace Yavsc.Blogs.Controllers
/// Blog posts (and therefore their ACLs) are private to their
/// author — the API never exposes another user's ACL.
///
- // GET: api/v1/blogacl
+ // GET: api/blogacl
[HttpGet]
public IEnumerable GetBlogACL()
{
diff --git a/src/Yavsc.Blogs/Controllers/BlogApiController.cs b/src/Yavsc.Blogs/Controllers/BlogApiController.cs
index fcd3a336..76aa777e 100644
--- a/src/Yavsc.Blogs/Controllers/BlogApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/BlogApiController.cs
@@ -3,7 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Yavsc.Blogspot;
using Yavsc.Server.Exceptions;
using Yavsc.Server.Helpers;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Blogs.Controllers
{
diff --git a/src/Yavsc.Blogs/Controllers/BlogTagsApiController.cs b/src/Yavsc.Blogs/Controllers/BlogTagsApiController.cs
index ad6a0893..a5d905eb 100644
--- a/src/Yavsc.Blogs/Controllers/BlogTagsApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/BlogTagsApiController.cs
@@ -1,8 +1,12 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Blog;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Blogs.Controllers
{
[Produces("application/json")]
diff --git a/src/Yavsc.Blogs/Controllers/CircleApiController.cs b/src/Yavsc.Blogs/Controllers/CircleApiController.cs
index ea3c981b..73bbfff9 100644
--- a/src/Yavsc.Blogs/Controllers/CircleApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/CircleApiController.cs
@@ -4,7 +4,7 @@ using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Relationship;
using Yavsc.Server.Helpers;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Blogs.Controllers
{
diff --git a/src/Yavsc.Blogs/Controllers/CommentsApiController.cs b/src/Yavsc.Blogs/Controllers/CommentsApiController.cs
index d4c80f99..b9f334dc 100644
--- a/src/Yavsc.Blogs/Controllers/CommentsApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/CommentsApiController.cs
@@ -5,7 +5,7 @@ using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Blog;
using Yavsc.Server.Helpers;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Blogs.Controllers
{
diff --git a/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs b/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs
index 5e834503..5b067c1b 100644
--- a/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs
@@ -2,7 +2,7 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Blogs.Controllers
{
@@ -21,7 +21,7 @@ namespace Yavsc.Blogs.Controllers
private readonly ILogger _logger;
public FileSystemApiController(ApplicationDbContext context,
- IAuthorizationService authorizationService,
+ IAuthorizationService authorizationService,
ILoggerFactory loggerFactory)
{
@@ -38,7 +38,7 @@ namespace Yavsc.Blogs.Controllers
[HttpGet("{*subdir}")]
public IActionResult GetDir([ValidRemoteUserFilePath] string subdir="")
- {
+ {
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
// _logger.LogInformation($"listing files from {User.Identity.Name}{subdir}");
var files = AbstractFileSystemHelpers.GetUserFiles(User.GetUserId(), subdir);
@@ -57,20 +57,20 @@ namespace Yavsc.Blogs.Controllers
} catch (InvalidPathException ex) {
pathex = ex;
}
- if (pathex!=null)
+ if (pathex!=null)
{
_logger.LogError($"invalid sub path: '{subdir}'.");
return BadRequest(pathex);
}
_logger.LogInformation($"Receiving files, saved in '{destDir}' (specified as '{subdir}').");
-
+
var uid = User.GetUserId();
var user = dbContext.Users.Single(
u => u.Id == uid
);
int i=0;
_logger.LogInformation($"Receiving {Request.Form.Files.Count} files.");
-
+
foreach (var f in Request.Form.Files)
{
var item = user.ReceiveUserFile(destDir, f);
@@ -178,7 +178,7 @@ namespace Yavsc.Blogs.Controllers
return Ok(new { deleted=id });
}
-
+
}
}
diff --git a/src/Yavsc.Blogs/Controllers/FileSystemStreamController.cs b/src/Yavsc.Blogs/Controllers/FileSystemStreamController.cs
index bc6485dd..23cf0cc6 100644
--- a/src/Yavsc.Blogs/Controllers/FileSystemStreamController.cs
+++ b/src/Yavsc.Blogs/Controllers/FileSystemStreamController.cs
@@ -8,7 +8,7 @@ using Yavsc.Models.Messaging;
using Yavsc.Services;
using Microsoft.AspNetCore.SignalR;
using Yavsc.Server.Helpers;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
using Yavsc.Server.Hubs;
namespace Yavsc.Blogs.Controllers
diff --git a/src/Yavsc.Blogs/Controllers/PostTagsApiController.cs b/src/Yavsc.Blogs/Controllers/PostTagsApiController.cs
index da03c19c..e908edec 100644
--- a/src/Yavsc.Blogs/Controllers/PostTagsApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/PostTagsApiController.cs
@@ -1,5 +1,5 @@
using Microsoft.AspNetCore.Mvc;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Blogs.Controllers
{
diff --git a/src/Yavsc.Blogs/Controllers/TagsApiController.cs b/src/Yavsc.Blogs/Controllers/TagsApiController.cs
index d4c2b538..daf0220b 100644
--- a/src/Yavsc.Blogs/Controllers/TagsApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/TagsApiController.cs
@@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
-using static Yavsc.Constants;
+using static Yavsc.Blogs.Constants;
namespace Yavsc.Controllers
{
diff --git a/src/Yavsc.Blogs/Controllers/UserSearchApiController.cs b/src/Yavsc.Blogs/Controllers/UserSearchApiController.cs
index 951a5880..048db154 100644
--- a/src/Yavsc.Blogs/Controllers/UserSearchApiController.cs
+++ b/src/Yavsc.Blogs/Controllers/UserSearchApiController.cs
@@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
-using static Yavsc.Constants;
namespace Yavsc.Blogs.Controllers
{
@@ -27,7 +26,7 @@ namespace Yavsc.Blogs.Controllers
/// exposing it.
///
[Produces("application/json")]
- [Route(APIPrefix + "/user-search")]
+ [Route( Constants.APIPrefix + "/user-search")]
[Authorize]
public class UserSearchApiController : Controller
{
@@ -67,9 +66,8 @@ namespace Yavsc.Blogs.Controllers
// book callers already know the email they're
// searching for and we don't want to surface a
// long tail of partial matches.
- var normalized = e.Trim();
- query = query.Where(u => u.Email != null &&
- string.Compare(u.Email, normalized, true) ==0);
+ var normalised = e.Trim();
+ query = query.Where(u => u.Email != null && u.Email.ToLower() == normalised.ToLower());
}
if (!string.IsNullOrWhiteSpace(q))
diff --git a/src/Yavsc.Blogs/Program.cs b/src/Yavsc.Blogs/Program.cs
index 952115d3..742c9eee 100644
--- a/src/Yavsc.Blogs/Program.cs
+++ b/src/Yavsc.Blogs/Program.cs
@@ -51,7 +51,7 @@ internal class Program
// DbContextBuilder
services.AddDbContext(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString(
- Yavsc.Constants.YavscConnectionStringName)));
+ YavscConstants.YavscConnectionStringName)));
// other services
services
diff --git a/src/Yavsc.Org.Tests/NonRegression/UserDisplayHelpersTests.cs b/src/Yavsc.Org.Tests/NonRegression/UserDisplayHelpersTests.cs
index 7543a42e..a0249fa4 100644
--- a/src/Yavsc.Org.Tests/NonRegression/UserDisplayHelpersTests.cs
+++ b/src/Yavsc.Org.Tests/NonRegression/UserDisplayHelpersTests.cs
@@ -14,7 +14,7 @@ namespace Yavsc.Org.Tests.NonRegression;
/// ne voit rien — juste un 500 muet.
///
/// Le fix passe par qui
-/// retourne pour toute
+/// retourne pour toute
/// donnée partielle. Ces tests couvrent les trois formes de
/// "donnée absente" : user null, UserName vide, UserName whitespace.
///
@@ -23,21 +23,21 @@ public class UserDisplayHelpersTests
[Fact]
public void AvatarSrc_null_user_returns_default_avatar()
{
- Assert.Equal(Yavsc.Constants.DefaultAvatar, UserDisplayHelpers.AvatarSrc(null));
+ Assert.Equal(YavscConstants.DefaultAvatar, UserDisplayHelpers.AvatarSrc(null));
}
[Fact]
public void AvatarSrc_user_with_empty_UserName_returns_default_avatar()
{
var user = new FakeUser { UserName = "" };
- Assert.Equal(Yavsc.Constants.DefaultAvatar, UserDisplayHelpers.AvatarSrc(user));
+ Assert.Equal(YavscConstants.DefaultAvatar, UserDisplayHelpers.AvatarSrc(user));
}
[Fact]
public void AvatarSrc_user_with_whitespace_UserName_returns_default_avatar()
{
var user = new FakeUser { UserName = " " };
- Assert.Equal(Yavsc.Constants.DefaultAvatar, UserDisplayHelpers.AvatarSrc(user));
+ Assert.Equal(YavscConstants.DefaultAvatar, UserDisplayHelpers.AvatarSrc(user));
}
[Fact]
@@ -47,7 +47,7 @@ public class UserDisplayHelpersTests
// Le path doit matcher YavscConstants.AvatarsPath (minuscule),
// pas un /Avatars/ avec S majuscule qui ne résout pas
// dans le middleware de fichiers statiques.
- var expected = $"{Yavsc.Constants.AvatarsPath}/alice.s.png";
+ var expected = $"{YavscConstants.AvatarsPath}/alice.s.png";
Assert.Equal(expected, UserDisplayHelpers.AvatarSrc(user));
}
diff --git a/src/Yavsc.Org.Tests/WebServerFixture.cs b/src/Yavsc.Org.Tests/WebServerFixture.cs
index edfd87d9..a623bc9e 100644
--- a/src/Yavsc.Org.Tests/WebServerFixture.cs
+++ b/src/Yavsc.Org.Tests/WebServerFixture.cs
@@ -80,8 +80,8 @@ public sealed class WebServerFixture : WebHostFixture
// can resolve it. The AddConfiguration extension takes care of
// that plus the in-memory overrides below.
builder.AddConfiguration(null).AddInMemoryCollection(new Dictionary
- {
- [$"ConnectionStrings:{Yavsc.Constants.YavscConnectionStringName}"] = "InMemory",
+ {
+ [$"ConnectionStrings:{YavscConstants.YavscConnectionStringName}"] = "InMemory",
// SMTP test config: UserName non-null so MailSender
// exercises the Authenticate branch — the
// RecordingSmtpClient captures it.
diff --git a/src/Yavsc.Org/Controllers/Accounting/AccountController.cs b/src/Yavsc.Org/Controllers/Accounting/AccountController.cs
index c562736d..43565442 100644
--- a/src/Yavsc.Org/Controllers/Accounting/AccountController.cs
+++ b/src/Yavsc.Org/Controllers/Accounting/AccountController.cs
@@ -90,7 +90,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
"ConfirmYourAccountTitle"
})
Debug.Assert(!_localizer[name].ResourceNotFound);
-
+
}
@@ -116,7 +116,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
{
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
- // only set explicit expiration here if user chooses "remember me".
+ // only set explicit expiration here if user chooses "remember me".
// otherwise we rely upon expiration configured in cookie middleware.
await HttpContext.SignInAsync(user, _roleManager, model.RememberMe, _dbContext);
var authResult = await HttpContext.AuthenticateAsync();
@@ -198,7 +198,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
///
/// Entry point into the login workflow
///
- [HttpGet(Constants.SigninPath)]
+ [HttpGet(YavscConstants.SigninPath)]
public async Task Signin(SignInModel model)
{
// build a model so we know what to show on the login page
@@ -216,11 +216,11 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
///
/// Handle postback from username/password login
///
- ///
- [HttpPost(Constants.SigninPath)]
+ ///
+ [HttpPost(YavscConstants.SigninPath)]
[ValidateAntiForgeryToken]
[AllowAnonymous]
-
+
public async Task Signin([FromForm] SignInModel model, [FromForm] string button)
{
@@ -232,7 +232,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
{
if (context != null)
{
- // if the user cancels, send a result back into IdentityServer as if they
+ // if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);
@@ -269,7 +269,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
{
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
- // only set explicit expiration here if user chooses "remember me".
+ // only set explicit expiration here if user chooses "remember me".
// otherwise we rely upon expiration configured in cookie middleware.
await HttpContext.SignInAsync(user, _roleManager, model.RememberMe, _dbContext);
@@ -396,7 +396,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
var local = context.IdP == IdentityServer8.IdentityServerConstants.LocalIdentityProvider;
// this is meant to short circuit the UI and only trigger the one external IdP
-
+
model.EnableLocalLogin = local;
model.UserName = context?.LoginHint;
model.IsExternalLoginOnly = false;
@@ -579,7 +579,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
// Send an email with this link
Uri authority = new Uri(Config.Authority);
-
+
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account",
new { userId = user.Id, code },
@@ -659,7 +659,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
}
//
// POST: /Account/LogOff
- [HttpPost(Constants.LogoutPath)]
+ [HttpPost(YavscConstants.LogoutPath)]
[ValidateAntiForgeryToken]
public async Task LogOff(string returnUrl = null)
{
@@ -829,7 +829,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
bool result = false;
try
{
- result = await _userManager.VerifyTwoFactorTokenAsync(user, Constants.DefaultFactor, code);
+ result = await _userManager.VerifyTwoFactorTokenAsync(user, YavscConstants.DefaultFactor, code);
_dbContext.SaveChanges(userId);
}
catch (Exception ex)
@@ -1024,12 +1024,12 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
}
// Generate the token and send it
- if (model.SelectedProvider == Constants.MobileAppFactor)
+ if (model.SelectedProvider == YavscConstants.MobileAppFactor)
{
return View("Error", new Exception("No mobile app service was activated"));
}
else
- if (model.SelectedProvider == Constants.SMSFactor)
+ if (model.SelectedProvider == YavscConstants.SMSFactor)
{
return View("Error", new Exception("No SMS service was activated"));
// await _smsSender.SendSmsAsync(_twilioSettings, await _userManager.GetPhoneNumberAsync(user), message);
diff --git a/src/Yavsc.Org/Controllers/Administration/AdministrationController.cs b/src/Yavsc.Org/Controllers/Administration/AdministrationController.cs
index e2944e9e..7104e178 100644
--- a/src/Yavsc.Org/Controllers/Administration/AdministrationController.cs
+++ b/src/Yavsc.Org/Controllers/Administration/AdministrationController.cs
@@ -50,12 +50,12 @@ namespace Yavsc.Controllers
{
// ensure all roles existence
foreach (string roleName in new string[] {
- Constants.AdminGroupName,
- Constants.StarGroupName,
- Constants.PerformerGroupName,
- Constants.FrontOfficeGroupName,
- Constants.StarHunterGroupName,
- Constants.BlogModeratorGroupName
+ YavscConstants.AdminGroupName,
+ YavscConstants.StarGroupName,
+ YavscConstants.PerformerGroupName,
+ YavscConstants.FrontOfficeGroupName,
+ YavscConstants.StarHunterGroupName,
+ YavscConstants.BlogModeratorGroupName
})
if (!await _roleManager.RoleExistsAsync(roleName))
{
@@ -80,11 +80,11 @@ namespace Yavsc.Controllers
public async Task Take()
{
// If some amdin already exists, make this method disapear
- var admins = await _userManager.GetUsersInRoleAsync(Constants.AdminGroupName);
+ var admins = await _userManager.GetUsersInRoleAsync(YavscConstants.AdminGroupName);
if (admins != null && admins.Count > 0)
{
// All is ok, nothing to do here.
- if (User.IsInMsRole(Constants.AdminGroupName))
+ if (User.IsInMsRole(YavscConstants.AdminGroupName))
{
return Ok(new { message = "you already got it." });
@@ -100,7 +100,7 @@ namespace Yavsc.Controllers
return new BadRequestObjectResult(ModelState);
}
- var addToRoleResult = await _userManager.AddToRoleAsync(user, Constants.AdminGroupName);
+ var addToRoleResult = await _userManager.AddToRoleAsync(user, YavscConstants.AdminGroupName);
if (!addToRoleResult.Succeeded)
{
AddErrors(addToRoleResult);
@@ -114,11 +114,11 @@ namespace Yavsc.Controllers
public async Task Index()
{
var adminCount = await _userManager.GetUsersInRoleAsync(
- Constants.AdminGroupName);
+ YavscConstants.AdminGroupName);
var userCount = await _dbContext.Users.CountAsync();
var youAreAdmin = await _userManager.IsInRoleAsync(
await _userManager.FindByIdAsync(User.GetUserId()),
- Constants.AdminGroupName);
+ YavscConstants.AdminGroupName);
var roles = await _roleManager.Roles.Select(x => new RoleInfo
{
diff --git a/src/Yavsc.Org/Controllers/Administration/ApiScopesApiController.cs b/src/Yavsc.Org/Controllers/Administration/ApiScopesApiController.cs
index d6e83c36..983e7233 100644
--- a/src/Yavsc.Org/Controllers/Administration/ApiScopesApiController.cs
+++ b/src/Yavsc.Org/Controllers/Administration/ApiScopesApiController.cs
@@ -1,13 +1,13 @@
using IdentityServer8.EntityFramework.Entities;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Server.Helpers;
-using static Yavsc.Constants;
namespace Yavsc.Org.Controllers.Administration
{
- [Route(APIPrefix + "/[controller]")]
+ [Route("api/[controller]")]
[ApiController]
public class ApiScopesApiController : ControllerBase
{
diff --git a/src/Yavsc.Org/Controllers/Communicating/AnnouncesController.cs b/src/Yavsc.Org/Controllers/Communicating/AnnouncesController.cs
index f8b41c99..e5002168 100644
--- a/src/Yavsc.Org/Controllers/Communicating/AnnouncesController.cs
+++ b/src/Yavsc.Org/Controllers/Communicating/AnnouncesController.cs
@@ -18,11 +18,11 @@ namespace Yavsc.Controllers
readonly IStringLocalizer _localizer;
readonly IAuthorizationService _authorizationService;
- public AnnouncesController(ApplicationDbContext context,
+ public AnnouncesController(ApplicationDbContext context,
IAuthorizationService authorizationService,
IStringLocalizer localizer)
{
- _context = context;
+ _context = context;
_authorizationService = authorizationService;
_localizer = localizer;
}
@@ -59,16 +59,16 @@ namespace Yavsc.Controllers
}
private async Task SetupView(Announce announce)
{
- ViewBag.IsAdmin = User.IsInMsRole(Constants.AdminGroupName);
- ViewBag.IsPerformer = User.IsInMsRole(Constants.PerformerGroupName);
+ ViewBag.IsAdmin = User.IsInMsRole(YavscConstants.AdminGroupName);
+ ViewBag.IsPerformer = User.IsInMsRole(YavscConstants.PerformerGroupName);
ViewBag.AllowEdit = announce==null || announce.Id<=0 || !_authorizationService.AuthorizeAsync(User,announce,new EditPermission()).IsFaulted;
List dl = new List();
var rnames = System.Enum.GetNames(typeof(Reason));
var rvalues = System.Enum.GetValues(typeof(Reason));
-
+
for (int i = 0; i a.Children).FirstOrDefault(a => a.Code == code);
@@ -123,9 +123,9 @@ namespace Yavsc.Controllers
[ValidateAntiForgeryToken]
public IActionResult Create(Activity activity)
{
- if (activity.ParentCode==Constants.NoneCode)
+ if (activity.ParentCode==YavscConstants.NoneCode)
activity.ParentCode=null;
- if (activity.SettingsClassName==Constants.NoneCode)
+ if (activity.SettingsClassName==YavscConstants.NoneCode)
activity.SettingsClassName=null;
if (ModelState.IsValid)
@@ -161,9 +161,9 @@ namespace Yavsc.Controllers
[ValidateAntiForgeryToken]
public IActionResult Edit(Activity activity)
{
- if (activity.ParentCode==Constants.NoneCode)
+ if (activity.ParentCode==YavscConstants.NoneCode)
activity.ParentCode=null;
- if (activity.SettingsClassName==Constants.NoneCode)
+ if (activity.SettingsClassName==YavscConstants.NoneCode)
activity.SettingsClassName=null;
if (ModelState.IsValid)
{
diff --git a/src/Yavsc.Org/Controllers/DimissClicksApiController.cs b/src/Yavsc.Org/Controllers/DimissClicksApiController.cs
index b07bc4b3..19f90787 100644
--- a/src/Yavsc.Org/Controllers/DimissClicksApiController.cs
+++ b/src/Yavsc.Org/Controllers/DimissClicksApiController.cs
@@ -10,7 +10,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
- [Route(Constants.APIPrefix + "/v1/dimiss")]
+ [Route("api/v1/dimiss")]
public class DimissClicksApiController : Controller
{
private readonly ApplicationDbContext _context;
@@ -140,7 +140,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator"))
if (uid != id) return new ChallengeResult();
-
+
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
diff --git a/src/Yavsc.Org/Controllers/HomeController.cs b/src/Yavsc.Org/Controllers/HomeController.cs
index c7aa131f..67c19fed 100644
--- a/src/Yavsc.Org/Controllers/HomeController.cs
+++ b/src/Yavsc.Org/Controllers/HomeController.cs
@@ -20,10 +20,10 @@ namespace Yavsc.Controllers
readonly IHtmlLocalizer _localizer;
private SiteSettings siteSettings;
- public HomeController(ILogger logger,
- IHtmlLocalizer localizer,
+ public HomeController(ILogger logger,
+ IHtmlLocalizer localizer,
ApplicationDbContext context,
- IOptions settingsOptions,
+ IOptions settingsOptions,
IWebHostEnvironment env
)
{
@@ -37,9 +37,9 @@ namespace Yavsc.Controllers
public async Task Index(string id)
{
- ViewBag.IsFromSecureProx = Request.Headers.ContainsKey(Constants.SshHeaderKey) && Request.Headers[Constants.SshHeaderKey] == "on";
+ ViewBag.IsFromSecureProx = Request.Headers.ContainsKey(YavscConstants.SshHeaderKey) && Request.Headers[YavscConstants.SshHeaderKey] == "on";
ViewBag.SecureHomeUrl = "https://" + Request.Headers["X-Forwarded-Host"];
- ViewBag.SshHeaderKey = Request.Headers[Constants.SshHeaderKey];
+ ViewBag.SshHeaderKey = Request.Headers[YavscConstants.SshHeaderKey];
var uid = User.GetUserId();
long[] clicked = null;
if (uid == null)
@@ -140,8 +140,8 @@ namespace Yavsc.Controllers
errorViewModel.Description ??= string.Empty;
errorViewModel.Description += " Page: Home.";
}
-
-
+
+
return View("~/Views/Shared/Error.cshtml", errorViewModel);
}
public IActionResult Status(int id)
diff --git a/src/Yavsc.Org/Controllers/Musical/InstrumentationController.cs b/src/Yavsc.Org/Controllers/Musical/InstrumentationController.cs
index 536c7417..dc905d08 100644
--- a/src/Yavsc.Org/Controllers/Musical/InstrumentationController.cs
+++ b/src/Yavsc.Org/Controllers/Musical/InstrumentationController.cs
@@ -17,7 +17,7 @@ namespace Yavsc.Controllers
public InstrumentationController(ApplicationDbContext context)
{
- _context = context;
+ _context = context;
}
// GET: Instrumentation
@@ -50,7 +50,7 @@ namespace Yavsc.Controllers
var owned = _context.Instrumentation.Include(i=>i.Tool).Where(i=>i.UserId==uid).Select(i=>i.InstrumentId);
var ownedArray = owned.ToArray();
- ViewBag.YetAvailableInstruments = _context.Instrument.Select(k=>new SelectListItem
+ ViewBag.YetAvailableInstruments = _context.Instrument.Select(k=>new SelectListItem
{ Text = k.Name, Value = k.Id.ToString(), Disabled = ownedArray.Contains(k.Id) });
return View(new Instrumentation { UserId = uid });
@@ -64,7 +64,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (ModelState.IsValid)
{
- if (model.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
+ if (model.UserId != uid) if (!User.IsInMsRole(YavscConstants.AdminGroupName))
return new ChallengeResult();
_context.Instrumentation.Add(model);
@@ -82,7 +82,7 @@ namespace Yavsc.Controllers
{
return NotFound();
}
- if (id != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
+ if (id != uid) if (!User.IsInMsRole(YavscConstants.AdminGroupName))
return new ChallengeResult();
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
@@ -98,7 +98,7 @@ namespace Yavsc.Controllers
public async Task Edit(Instrumentation musicianSettings)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
- if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
+ if (musicianSettings.UserId != uid) if (!User.IsInMsRole(YavscConstants.AdminGroupName))
return new ChallengeResult();
if (ModelState.IsValid)
{
@@ -124,7 +124,7 @@ namespace Yavsc.Controllers
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
- if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
+ if (musicianSettings.UserId != uid) if (!User.IsInMsRole(YavscConstants.AdminGroupName))
return new ChallengeResult();
return View(musicianSettings);
}
@@ -135,12 +135,12 @@ namespace Yavsc.Controllers
public async Task DeleteConfirmed(string id)
{
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
-
+
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
- if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
+ if (musicianSettings.UserId != uid) if (!User.IsInMsRole(YavscConstants.AdminGroupName))
return new ChallengeResult();
-
+
_context.Instrumentation.Remove(musicianSettings);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
diff --git a/src/Yavsc.Org/Extensions/HostingExtensions.cs b/src/Yavsc.Org/Extensions/HostingExtensions.cs
index f92dc3c9..0cae23a7 100644
--- a/src/Yavsc.Org/Extensions/HostingExtensions.cs
+++ b/src/Yavsc.Org/Extensions/HostingExtensions.cs
@@ -169,7 +169,7 @@ public static class HostingExtensions
public static IdentityBuilder AddIdentityDBAndStores(this WebApplicationBuilder builder)
{
IServiceCollection services = builder.Services;
- var connectionString = builder.Configuration.GetConnectionString(Constants.YavscConnectionStringName);
+ var connectionString = builder.Configuration.GetConnectionString(YavscConstants.YavscConnectionStringName);
services.AddDbContext(options =>
{
@@ -197,7 +197,7 @@ public static class HostingExtensions
options.SignIn.RequireConfirmedAccount = builder.Environment.IsEnvironment(
builder.Environment.EnvironmentName);
options.ClaimsIdentity.UserNameClaimType = JwtClaimTypes.PreferredUserName;
- options.ClaimsIdentity.RoleClaimType = Constants.RoleClaimType;
+ options.ClaimsIdentity.RoleClaimType = YavscConstants.RoleClaimType;
}
)
.AddEntityFrameworkStores();
@@ -239,18 +239,18 @@ public static class HostingExtensions
{
policy
.RequireAuthenticatedUser()
- .RequireClaim(Constants.RoleClaimType,
- new string[] { Constants.PerformerGroupName, Constants.AdminGroupName })
+ .RequireClaim(YavscConstants.RoleClaimType,
+ new string[] { YavscConstants.PerformerGroupName, YavscConstants.AdminGroupName })
;
});
options.AddPolicy("AdministratorOnly", policy =>
{
_ = policy
.RequireAuthenticatedUser()
- .RequireClaim(Constants.RoleClaimType, Constants.AdminGroupName);
+ .RequireClaim(YavscConstants.RoleClaimType, YavscConstants.AdminGroupName);
});
- options.AddPolicy("FrontOffice", policy => policy.RequireRole(Constants.FrontOfficeGroupName));
+ options.AddPolicy("FrontOffice", policy => policy.RequireRole(YavscConstants.FrontOfficeGroupName));
// options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456"));
// options.AddPolicy("BuildingEntry", policy => policy.Requirements.Add(new OfficeEntryRequirement()));
@@ -314,10 +314,10 @@ public static class HostingExtensions
{
options.ClaimsIdentity.UserIdClaimType = JwtClaimTypes.Subject;
options.ClaimsIdentity.UserNameClaimType = JwtClaimTypes.Name;
- options.ClaimsIdentity.RoleClaimType = Constants.RoleClaimType;
+ options.ClaimsIdentity.RoleClaimType = YavscConstants.RoleClaimType;
});
var migrationsAssembly = typeof(Program).GetTypeInfo().Assembly.GetName().Name;
- var connectionString = builder.Configuration.GetConnectionString(Constants.YavscConnectionStringName);
+ var connectionString = builder.Configuration.GetConnectionString(YavscConstants.YavscConnectionStringName);
string sqliteConnectionString = $"Data Source={Path.Combine(Path.GetTempPath(), "yavsc_test.db")}";
@@ -1220,7 +1220,7 @@ ADD COLUMN IF NOT EXISTS ""Moderated"" boolean NOT NULL DEFAULT FALSE;");
Config.UserFilesOptions = new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(AbstractFileSystemHelpers.UserFilesDirName),
- RequestPath = PathString.FromUriComponent(Constants.UserFilesPath),
+ RequestPath = PathString.FromUriComponent(YavscConstants.UserFilesPath),
EnableDirectoryBrowsing = enableDirectoryBrowsing,
};
Config.UserFilesOptions.EnableDefaultFiles = true;
@@ -1233,7 +1233,7 @@ ADD COLUMN IF NOT EXISTS ""Moderated"" boolean NOT NULL DEFAULT FALSE;");
Config.AvatarsOptions = new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(Config.AvatarsDirName),
- RequestPath = PathString.FromUriComponent(Constants.AvatarsPath),
+ RequestPath = PathString.FromUriComponent(YavscConstants.AvatarsPath),
EnableDirectoryBrowsing = enableDirectoryBrowsing
};
@@ -1244,7 +1244,7 @@ ADD COLUMN IF NOT EXISTS ""Moderated"" boolean NOT NULL DEFAULT FALSE;");
Config.GitOptions = new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(Config.GitDirName),
- RequestPath = PathString.FromUriComponent(Constants.GitPath),
+ RequestPath = PathString.FromUriComponent(YavscConstants.GitPath),
EnableDirectoryBrowsing = enableDirectoryBrowsing,
};
Config.GitOptions.DefaultFilesOptions.DefaultFileNames.Add("index.md");
diff --git a/src/Yavsc.Org/ViewModels/Manage/SetUserNameViewModel.cs b/src/Yavsc.Org/ViewModels/Manage/SetUserNameViewModel.cs
index 61cf0727..69507b92 100644
--- a/src/Yavsc.Org/ViewModels/Manage/SetUserNameViewModel.cs
+++ b/src/Yavsc.Org/ViewModels/Manage/SetUserNameViewModel.cs
@@ -7,7 +7,7 @@ namespace Yavsc.ViewModels.Manage
public class SetUserNameViewModel
{
[Required]
- [Display(Name = "User name"),RegularExpression(Constants.UserNameRegExp)]
+ [Display(Name = "User name"),RegularExpression(YavscConstants.UserNameRegExp)]
public string UserName { get; set; }
}
diff --git a/src/Yavsc.Org/Views/Shared/DisplayTemplates/ApplicationUser.cshtml b/src/Yavsc.Org/Views/Shared/DisplayTemplates/ApplicationUser.cshtml
index dd6b0ff8..f0a961c9 100644
--- a/src/Yavsc.Org/Views/Shared/DisplayTemplates/ApplicationUser.cshtml
+++ b/src/Yavsc.Org/Views/Shared/DisplayTemplates/ApplicationUser.cshtml
@@ -13,7 +13,7 @@
} else {
Utilisateur inconnu
-
+
}
diff --git a/src/Yavsc.Org/Views/Shared/_LoginPartial.cshtml b/src/Yavsc.Org/Views/Shared/_LoginPartial.cshtml
index 7bfa2a3f..431fe61e 100644
--- a/src/Yavsc.Org/Views/Shared/_LoginPartial.cshtml
+++ b/src/Yavsc.Org/Views/Shared/_LoginPartial.cshtml
@@ -16,7 +16,7 @@
Features
- @if (User.IsInMsRole(Constants.AdminGroupName)) {
+ @if (User.IsInMsRole(YavscConstants.AdminGroupName)) {
Administration
diff --git a/src/Yavsc.Server/Helpers/HtmlHelpers.cs b/src/Yavsc.Server/Helpers/HtmlHelpers.cs
index 213ea369..2c5ac562 100644
--- a/src/Yavsc.Server/Helpers/HtmlHelpers.cs
+++ b/src/Yavsc.Server/Helpers/HtmlHelpers.cs
@@ -14,7 +14,7 @@ namespace Yavsc.Helpers
public static string ToAbsolute(this HttpRequest request, string url)
{
var host = request.Host;
- var isSecure = request.Headers[Constants.SshHeaderKey] == "on";
+ var isSecure = request.Headers[YavscConstants.SshHeaderKey] == "on";
return (isSecure ? "https" : "http") + $"://{host}/{url}";
}
}
diff --git a/src/Yavsc.Server/Helpers/ServiceExtensions.cs b/src/Yavsc.Server/Helpers/ServiceExtensions.cs
index 0ac1f135..2efbad7e 100644
--- a/src/Yavsc.Server/Helpers/ServiceExtensions.cs
+++ b/src/Yavsc.Server/Helpers/ServiceExtensions.cs
@@ -105,8 +105,8 @@ public static class ServiceExtensions
{
ValidateAudience = true,
ValidAudiences = audiences,
- RoleClaimType = Constants.RoleClaimType,
- NameClaimType = Constants.NameClaimType,
+ RoleClaimType = YavscConstants.RoleClaimType,
+ NameClaimType = YavscConstants.NameClaimType,
};
options.MapInboundClaims = true;
options.ClaimsIssuer = authority;
diff --git a/src/Yavsc.Server/Hubs/ChatHub.cs b/src/Yavsc.Server/Hubs/ChatHub.cs
index 4a99b507..56ffe901 100644
--- a/src/Yavsc.Server/Hubs/ChatHub.cs
+++ b/src/Yavsc.Server/Hubs/ChatHub.cs
@@ -84,7 +84,7 @@ namespace Yavsc.Server.Hubs
var userId = _dbContext.Users.First(u => u.UserName == Context.User.Identity.Name).Id;
await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.Connected, userName, null);
- isCop = Context.User.IsInMsRole(Constants.AdminGroupName) ;
+ isCop = Context.User.IsInMsRole(YavscConstants.AdminGroupName) ;
if (isCop)
{
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.HubGroupCops);
@@ -351,7 +351,7 @@ namespace Yavsc.Server.Hubs
var identityUserName = Context.User.GetUserName();
if (userName[0] != '?' && Context.User!=null)
- if (!Context.User.IsInMsRole(Constants.AdminGroupName))
+ if (!Context.User.IsInMsRole(YavscConstants.AdminGroupName))
{
var bl = _dbContext.BlackListed
diff --git a/src/Yavsc.Server/Models/ApplicationDbContext.cs b/src/Yavsc.Server/Models/ApplicationDbContext.cs
index 5ebf931f..fd924944 100644
--- a/src/Yavsc.Server/Models/ApplicationDbContext.cs
+++ b/src/Yavsc.Server/Models/ApplicationDbContext.cs
@@ -92,8 +92,8 @@ namespace Yavsc.Models
builder.Entity().Property(u => u.FullName).IsRequired(false);
builder.Entity().Property(u => u.DedicatedGoogleCalendar).IsRequired(false);
builder.Entity().HasMany(c => c.Connections);
- builder.Entity().Property(u => u.Avatar).HasDefaultValue(Constants.DefaultAvatar);
- builder.Entity().Property(u => u.DiskQuota).HasDefaultValue(Constants.DefaultFSQ);
+ builder.Entity().Property(u => u.Avatar).HasDefaultValue(YavscConstants.DefaultAvatar);
+ builder.Entity().Property(u => u.DiskQuota).HasDefaultValue(YavscConstants.DefaultFSQ);
builder.Entity().HasAlternateKey(u => u.Email);
builder.Entity().HasOne(bl => bl.User);
builder.Entity().HasOne(bl => bl.Owner);
diff --git a/src/Yavsc.Server/Services/LiveProcessor.cs b/src/Yavsc.Server/Services/LiveProcessor.cs
index f10a8201..6858d225 100644
--- a/src/Yavsc.Server/Services/LiveProcessor.cs
+++ b/src/Yavsc.Server/Services/LiveProcessor.cs
@@ -61,7 +61,7 @@ namespace Yavsc.Services
// TODO: Handle the socket here.
// Find receivers: others in the chat room
// send them the flow
- var buffer = new byte[Constants.WebSocketsMaxBufLen];
+ var buffer = new byte[YavscConstants.WebSocketsMaxBufLen];
var sBuffer = new ArraySegment(buffer);
_logger.LogInformation("Receiving bytes...");
@@ -69,16 +69,16 @@ namespace Yavsc.Services
_logger.LogInformation($"Received bytes : {received.Count}");
_logger.LogInformation($"Is the end : {received.EndOfMessage}");
+
-
-
+
var fsInputQueue = new Queue>();
bool endOfInput = false;
sBuffer = new ArraySegment(buffer,0,received.Count);
fsInputQueue.Enqueue(sBuffer);
var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, () => endOfInput);
-
+
Stack ToClose = new Stack();
@@ -105,19 +105,19 @@ namespace Yavsc.Services
}
}
- if (!received.CloseStatus.HasValue)
+ if (!received.CloseStatus.HasValue)
{
_logger.LogInformation("try and receive new bytes");
- buffer = new byte[Constants.WebSocketsMaxBufLen];
+ buffer = new byte[YavscConstants.WebSocketsMaxBufLen];
received = await liveHandler.Socket.ReceiveAsync(sBuffer, liveHandler.TokenSource.Token);
-
+
_logger.LogInformation($"Received bytes : {received.Count}");
sBuffer = new ArraySegment(buffer,0,received.Count);
_logger.LogInformation($"segment : offset: {sBuffer.Offset} count: {sBuffer.Count}");
_logger.LogInformation($"Is the end : {received.EndOfMessage}");
-
+
if (received.CloseStatus.HasValue)
{
endOfInput=true;
@@ -140,7 +140,7 @@ namespace Yavsc.Services
}
}
while (liveHandler.Socket.State == WebSocketState.Open);
-
+
_logger.LogInformation("Closing connection");
taskWritingToFs.Wait();
await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, received.CloseStatusDescription, liveHandler.TokenSource.Token);
diff --git a/src/Yavsc.Server/Services/ProfileService.cs b/src/Yavsc.Server/Services/ProfileService.cs
index bda689a4..b4bdbfe2 100644
--- a/src/Yavsc.Server/Services/ProfileService.cs
+++ b/src/Yavsc.Server/Services/ProfileService.cs
@@ -13,8 +13,8 @@ namespace Yavsc.Services
{
private readonly UserManager _userManager;
public ProfileService(
- UserManager userManager,
- ILogger logger)
+ UserManager userManager,
+ ILogger logger)
{
_userManager = userManager;
}
@@ -23,7 +23,7 @@ namespace Yavsc.Services
ProfileDataRequestContext context,
ApplicationUser user)
{
-
+
var claims = new List {
new Claim(JwtClaimTypes.Subject,user.Id.ToString()),
};
@@ -43,7 +43,7 @@ namespace Yavsc.Services
claimAdds.Remove("profile");
claimAdds.Add(JwtClaimTypes.Name);
claimAdds.Add(JwtClaimTypes.Email);
- claimAdds.Add(Constants.RoleClaimType);
+ claimAdds.Add(YavscConstants.RoleClaimType);
}
if (claimAdds.Contains(JwtClaimTypes.Name))
@@ -51,13 +51,13 @@ namespace Yavsc.Services
if (claimAdds.Contains(JwtClaimTypes.Email))
claims.Add(new Claim(JwtClaimTypes.Email, user.Email));
-
- if (claimAdds.Contains(Constants.RoleClaimType))
+
+ if (claimAdds.Contains(YavscConstants.RoleClaimType))
{
var roles = await this._userManager.GetRolesAsync(user);
if (roles.Count()>0)
{
- claims.AddRange(roles.Select(r => new Claim(Constants.RoleClaimType, r)));
+ claims.AddRange(roles.Select(r => new Claim(YavscConstants.RoleClaimType, r)));
}
}
return claims;
diff --git a/src/Yavsc.Server/ViewModels/Account/ExternalLoginConfirmationViewModel.cs b/src/Yavsc.Server/ViewModels/Account/ExternalLoginConfirmationViewModel.cs
index 09519543..3611cf31 100644
--- a/src/Yavsc.Server/ViewModels/Account/ExternalLoginConfirmationViewModel.cs
+++ b/src/Yavsc.Server/ViewModels/Account/ExternalLoginConfirmationViewModel.cs
@@ -8,8 +8,8 @@ namespace Yavsc.ViewModels.Account
public class ExternalLoginConfirmationViewModel
{
[Required]
- [YaStringLength(2,Constants.MaxUserNameLength)]
- [YaRegularExpression(Constants.UserNameRegExp)]
+ [YaStringLength(2,YavscConstants.MaxUserNameLength)]
+ [YaRegularExpression(YavscConstants.UserNameRegExp)]
public string Name { get; set; }
[Required]
diff --git a/src/cli/Commands/Streamer.cs b/src/cli/Commands/Streamer.cs
index 3210b841..d592379d 100644
--- a/src/cli/Commands/Streamer.cs
+++ b/src/cli/Commands/Streamer.cs
@@ -16,7 +16,7 @@ namespace cli {
private CommandArgument _destArg;
private CancellationTokenSource _tokenSource;
- public Streamer(ILoggerFactory loggerFactory,
+ public Streamer(ILoggerFactory loggerFactory,
IOptions cxSettings,
IOptions userCxSettings
)
@@ -38,7 +38,7 @@ namespace cli {
_sourceArg = target.Argument("source", "Source file to send, use '-' for standard input", false);
_destArg = target.Argument("destination", "destination file name", false);
-
+
target.HelpOption("-? | -h | --help");
});
streamCmd.OnExecute(async() => await DoExecute());
@@ -47,7 +47,7 @@ namespace cli {
private async Task DoExecute()
{
-
+
if (_sourceArg.Value != "-")
{
var fi = new FileInfo(_sourceArg.Value);
@@ -80,7 +80,7 @@ namespace cli {
_logger.LogInformation("Connecting to " + url);
await _client.ConnectAsync(new Uri(url), _tokenSource.Token);
_logger.LogInformation("Connected");
- const int bufLen = Yavsc.Constants.WebSocketsMaxBufLen;
+ const int bufLen = Yavsc.YavscConstants.WebSocketsMaxBufLen;
byte [] buffer = new byte[bufLen];
const int offset=0;
int read;
@@ -90,7 +90,7 @@ namespace cli {
do
{
read = await stream.ReadAsync(buffer, offset, bufLen);
- lastFrame = read < Yavsc.Constants.WebSocketsMaxBufLen;
+ lastFrame = read < Yavsc.YavscConstants.WebSocketsMaxBufLen;
ArraySegment segment = new ArraySegment(buffer, offset, read);
await _client.SendAsync(segment, pckType, lastFrame, _tokenSource.Token);
_logger.LogInformation($"sent {segment.Count} ");
diff --git a/src/cli/Settings/ConnectionSettings.cs b/src/cli/Settings/ConnectionSettings.cs
index 62622ebc..b7a1110a 100644
--- a/src/cli/Settings/ConnectionSettings.cs
+++ b/src/cli/Settings/ConnectionSettings.cs
@@ -40,8 +40,8 @@ namespace cli
[NotMapped]
[JsonIgnore]
public string StreamingUrl { get {
- return Port==0 ? $"ws://{Authority}"+Constants.StreamingPath:
- $"ws://{Authority}:{Port}"+Constants.StreamingPath;
+ return Port==0 ? $"ws://{Authority}"+YavscConstants.StreamingPath:
+ $"ws://{Authority}:{Port}"+YavscConstants.StreamingPath;
} }
}