Scaffolded c# app

This commit is contained in:
Marco 2026-10-16 15:36:51 +02:00
commit 387a6ac182
57 changed files with 3930 additions and 0 deletions

View file

@ -0,0 +1,139 @@
using Surveillance.Client.Application;
using Surveillance.Client.App;
using Surveillance.Client.Domain;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
using Xunit;
namespace Surveillance.Client.App.Tests;
public sealed class MainWindowViewModelTests
{
[Fact]
public void RemembersCredentialsByDefault()
{
var viewModel = new MainWindowViewModel(new CoordinatorStub());
Assert.True(viewModel.RememberCredentials);
}
[Fact]
public async Task KeepsAuthenticatedSessionWhenPreviewProtocolIsUnverified()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator);
await viewModel.ConnectCommand.ExecuteAsync(null);
Assert.True(viewModel.IsConnected);
Assert.True(coordinator.IsConnected);
Assert.Equal("Authenticated; live preview unavailable", viewModel.StatusMessage);
}
[Fact]
public async Task InvalidPortDoesNotAttemptToConnect()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator) { Port = "70000" };
await viewModel.ConnectCommand.ExecuteAsync(null);
Assert.Equal(0, coordinator.ConnectCount);
Assert.Contains("port", viewModel.DetailMessage, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SavesCredentialsOnCloseWhenRememberIsEnabled()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator)
{
Host = "camera.local",
Port = "9000",
UserName = "viewer",
Password = "secret"
};
await viewModel.SaveCredentialsOnCloseAsync();
Assert.Equal(1, coordinator.SaveCount);
Assert.Equal("camera.local", coordinator.SavedEndpoint?.Host);
Assert.Equal(9000, coordinator.SavedEndpoint?.Port);
Assert.Equal("viewer", coordinator.SavedCredentials?.UserName);
Assert.Equal("secret", coordinator.SavedCredentials?.Password);
}
[Fact]
public async Task DoesNotSaveIncompleteOrUnrememberedCredentialsOnClose()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator)
{
UserName = "viewer",
Password = "secret",
RememberCredentials = false
};
await viewModel.SaveCredentialsOnCloseAsync();
viewModel.RememberCredentials = true;
viewModel.Password = string.Empty;
await viewModel.SaveCredentialsOnCloseAsync();
Assert.Equal(0, coordinator.SaveCount);
}
private sealed class CoordinatorStub : ILiveViewCoordinator
{
public int ConnectCount { get; private set; }
public int SaveCount { get; private set; }
public DeviceEndpoint? SavedEndpoint { get; private set; }
public DeviceCredentials? SavedCredentials { get; private set; }
public bool IsConnected { get; private set; }
public bool IsPreviewing => false;
public ValueTask<AuthenticationResult> ConnectAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
bool rememberCredentials,
CancellationToken cancellationToken = default)
{
ConnectCount++;
IsConnected = true;
return ValueTask.FromResult(AuthenticationResult.Success());
}
public ValueTask SaveCredentialsAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
SaveCount++;
SavedEndpoint = endpoint;
SavedCredentials = credentials;
return ValueTask.CompletedTask;
}
public ValueTask StartPreviewAsync(ChannelId channel, CancellationToken cancellationToken = default) =>
ValueTask.FromException(new ProtocolNotVerifiedException("Preview protocol is not verified."));
public async IAsyncEnumerable<DecodedVideoFrame> ReadFramesAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
yield break;
}
public ValueTask StopAsync(CancellationToken cancellationToken = default)
{
IsConnected = false;
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Client.App\Surveillance.Client.App.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,223 @@
using System.Runtime.CompilerServices;
using Surveillance.Client.Application;
using Surveillance.Client.Domain;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
using Xunit;
namespace Surveillance.Client.Application.Tests;
public sealed class LiveViewCoordinatorTests
{
[Fact]
public async Task ConnectLoadsRememberedCredentialsAndPreviewCanBeStopped()
{
var savedCredentials = new DeviceCredentials("viewer", "secret");
var store = new FakeCredentialStore(savedCredentials);
var preview = new FakePreview();
var session = new FakeSession(preview, AuthenticationResult.Success());
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(session),
store,
new FakeDecoder());
var result = await coordinator.ConnectAsync(
new DeviceEndpoint("camera.local", 34567),
new DeviceCredentials(string.Empty, string.Empty),
rememberCredentials: true,
TestContext.Current.CancellationToken);
Assert.True(result.IsAuthenticated);
Assert.Same(savedCredentials, session.AuthenticatedCredentials);
Assert.Equal(1, store.ReadCount);
Assert.Equal(1, store.WriteCount);
Assert.True(coordinator.IsConnected);
await coordinator.StartPreviewAsync(new ChannelId(0), TestContext.Current.CancellationToken);
var receivedFrames = new List<DecodedVideoFrame>();
await foreach (var frame in coordinator.ReadFramesAsync(TestContext.Current.CancellationToken))
{
receivedFrames.Add(frame);
}
Assert.Single(receivedFrames);
Assert.True(coordinator.IsPreviewing);
await coordinator.StopAsync(TestContext.Current.CancellationToken);
Assert.False(coordinator.IsConnected);
Assert.False(coordinator.IsPreviewing);
Assert.True(preview.WasStopped);
Assert.True(session.WasDisconnected);
}
[Fact]
public async Task RejectedAuthenticationDoesNotPersistCredentials()
{
var store = new FakeCredentialStore(null);
var session = new FakeSession(
new FakePreview(),
AuthenticationResult.Rejected(AuthenticationFailure.InvalidCredentials));
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(session),
store,
new FakeDecoder());
var result = await coordinator.ConnectAsync(
new DeviceEndpoint("127.0.0.1", 34567),
new DeviceCredentials("viewer", "wrong"),
rememberCredentials: true,
TestContext.Current.CancellationToken);
Assert.False(result.IsAuthenticated);
Assert.False(coordinator.IsConnected);
Assert.Equal(0, store.WriteCount);
Assert.True(session.WasDisconnected);
await coordinator.DisposeAsync();
}
[Fact]
public async Task SaveCredentialsWritesToTheEndpointCredentialKey()
{
var store = new FakeCredentialStore(null);
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(new FakeSession(new FakePreview(), AuthenticationResult.Success())),
store,
new FakeDecoder());
var endpoint = new DeviceEndpoint("camera.local", 9000);
var credentials = new DeviceCredentials("viewer", "secret");
await coordinator.SaveCredentialsAsync(endpoint, credentials, TestContext.Current.CancellationToken);
Assert.Equal(endpoint.CredentialKey, store.LastKey);
Assert.Same(credentials, store.LastCredentials);
Assert.Equal(1, store.WriteCount);
await coordinator.DisposeAsync();
}
[Fact]
public async Task ConnectUsesSavedCredentialForBlankField()
{
var savedCredentials = new DeviceCredentials("saved-user", "saved-password");
var store = new FakeCredentialStore(savedCredentials);
var session = new FakeSession(new FakePreview(), AuthenticationResult.Success());
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(session),
store,
new FakeDecoder());
var result = await coordinator.ConnectAsync(
new DeviceEndpoint("127.0.0.1", 34567),
new DeviceCredentials("typed-user", string.Empty),
rememberCredentials: true,
TestContext.Current.CancellationToken);
Assert.True(result.IsAuthenticated);
Assert.Equal("typed-user", session.AuthenticatedCredentials?.UserName);
Assert.Equal("saved-password", session.AuthenticatedCredentials?.Password);
Assert.Equal(1, store.ReadCount);
Assert.Equal(1, store.WriteCount);
await coordinator.DisposeAsync();
}
private sealed class FakeCredentialStore(DeviceCredentials? credentials) : ICredentialStore
{
public int ReadCount { get; private set; }
public int WriteCount { get; private set; }
public string? LastKey { get; private set; }
public DeviceCredentials? LastCredentials { get; private set; }
public ValueTask<DeviceCredentials?> ReadAsync(string key, CancellationToken cancellationToken = default)
{
ReadCount++;
return ValueTask.FromResult(credentials);
}
public ValueTask WriteAsync(
string key,
DeviceCredentials value,
CancellationToken cancellationToken = default)
{
WriteCount++;
LastKey = key;
LastCredentials = value;
return ValueTask.CompletedTask;
}
}
private sealed class FakeSessionFactory(FakeSession session) : IDeviceSessionFactory
{
public ValueTask<IDeviceSession> ConnectAsync(
DeviceEndpoint endpoint,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<IDeviceSession>(session);
}
private sealed class FakeSession(FakePreview preview, AuthenticationResult authentication) : IDeviceSession
{
public DeviceCredentials? AuthenticatedCredentials { get; private set; }
public bool WasDisconnected { get; private set; }
public ValueTask<AuthenticationResult> AuthenticateAsync(
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
AuthenticatedCredentials = credentials;
return ValueTask.FromResult(authentication);
}
public ValueTask<ILivePreview> StartPreviewAsync(
ChannelId channel,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<ILivePreview>(preview);
public ValueTask DisconnectAsync(CancellationToken cancellationToken = default)
{
WasDisconnected = true;
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class FakePreview : ILivePreview
{
public VideoStreamDescriptor Stream { get; } = new(VideoCodec.H264, 1, 1);
public bool WasStopped { get; private set; }
public async IAsyncEnumerable<EncodedVideoPacket> ReadPacketsAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
yield return new EncodedVideoPacket(new byte[] { 1 }, null, null, 1, 1, true);
await Task.CompletedTask;
}
public ValueTask StopAsync(CancellationToken cancellationToken = default)
{
WasStopped = true;
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class FakeDecoder : ILiveVideoDecoder
{
public async IAsyncEnumerable<DecodedVideoFrame> DecodeAsync(
VideoStreamDescriptor stream,
IAsyncEnumerable<EncodedVideoPacket> packets,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var packet in packets.WithCancellation(cancellationToken))
{
yield return new DecodedVideoFrame(1, 1, 4, new byte[] { 0, 0, 0, 255 });
yield break;
}
}
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Client.Application\Surveillance.Client.Application.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,34 @@
using Surveillance.Client.Domain;
using Xunit;
namespace Surveillance.Client.Domain.Tests;
public sealed class DeviceEndpointTests
{
[Fact]
public void CredentialKeyIsStableAcrossHostCaseAndWhitespace()
{
var first = new DeviceEndpoint(" camera.local ", 34567);
var second = new DeviceEndpoint("CAMERA.local", 34567);
Assert.Equal(first.CredentialKey, second.CredentialKey);
Assert.Equal("camera.local:34567", first.ToString());
}
[Theory]
[InlineData(0)]
[InlineData(65536)]
public void RejectsPortsOutsideTcpRange(int port)
{
Assert.Throws<ArgumentOutOfRangeException>(() => new DeviceEndpoint("127.0.0.1", port));
}
[Fact]
public void CredentialsNeverExposeTheirValuesInToString()
{
var credentials = new DeviceCredentials("viewer", "a-secret-value");
Assert.DoesNotContain("viewer", credentials.ToString(), StringComparison.Ordinal);
Assert.DoesNotContain("a-secret-value", credentials.ToString(), StringComparison.Ordinal);
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Client.Domain\Surveillance.Client.Domain.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,33 @@
using System.Runtime.CompilerServices;
using Surveillance.Client.Media;
using Surveillance.Media.FFmpegCore;
using Xunit;
namespace Surveillance.Media.FFmpegCore.Tests;
public sealed class FfmpegCoreLiveVideoDecoderTests
{
[Fact]
public async Task RejectsDecodedFramesAboveConfiguredMemoryLimit()
{
var decoder = new FfmpegCoreLiveVideoDecoder();
var stream = new VideoStreamDescriptor(VideoCodec.H264, 4097, 4096);
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await foreach (var _ in decoder.DecodeAsync(
stream,
EmptyPackets(TestContext.Current.CancellationToken),
TestContext.Current.CancellationToken))
{
}
});
}
private static async IAsyncEnumerable<EncodedVideoPacket> EmptyPackets(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
yield break;
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Media.FFmpegCore\Surveillance.Media.FFmpegCore.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,181 @@
using System.Buffers.Binary;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Surveillance.Client.Domain;
using Surveillance.Client.Protocol;
using Surveillance.Protocol.RSNet;
using Xunit;
namespace Surveillance.Protocol.RSNet.Tests;
public sealed class RsNetSessionFactoryTests
{
[Fact]
public void DecodesCapturedNativeModeZeroRequestHeader()
{
var header = Convert.FromHexString("02000601001000400100040082000083");
TransformBits(header.AsSpan(2), decode: true);
Assert.Equal(0x02u, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0, 4)));
Assert.Equal(0x1fu, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(4, 4)));
Assert.Equal(0x50u, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(8, 4)));
Assert.Equal(348u, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(12, 4)));
}
[Fact]
public async Task SendsReconstructedLoginFrameAndAcceptsSuccessfulResponse()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var endpoint = new DeviceEndpoint(IPAddress.Loopback.ToString(), ((IPEndPoint)listener.LocalEndpoint).Port);
var serverTask = ReceiveLoginAndRespondAsync(listener, 0, SuccessfulResponsePayload(), timeout.Token);
var factory = new RsNetSessionFactory();
await using var session = await factory.ConnectAsync(endpoint, timeout.Token);
var result = await session.AuthenticateAsync(
new DeviceCredentials("viewer", "secret"),
timeout.Token);
var request = await serverTask;
Assert.True(result.IsAuthenticated);
Assert.Equal(0x02u, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(0, 4)));
Assert.Equal(0x1fu, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(4, 4)));
Assert.Equal(0x50u, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(8, 4)));
Assert.NotEqual(0u, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(12, 4)));
var expectedPayload = new byte[0x50];
Encoding.UTF8.GetBytes("viewer").CopyTo(expectedPayload, 0);
Encoding.UTF8.GetBytes("secret").CopyTo(expectedPayload, 0x24);
Assert.Equal(expectedPayload, request.Payload);
}
[Fact]
public async Task RejectsNonzeroLoginStatus()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var endpoint = new DeviceEndpoint(IPAddress.Loopback.ToString(), ((IPEndPoint)listener.LocalEndpoint).Port);
var serverTask = ReceiveLoginAndRespondAsync(listener, 10, [], timeout.Token);
var factory = new RsNetSessionFactory();
await using var session = await factory.ConnectAsync(endpoint, timeout.Token);
var result = await session.AuthenticateAsync(new DeviceCredentials("viewer", "wrong"), timeout.Token);
await serverTask;
Assert.False(result.IsAuthenticated);
Assert.Equal(AuthenticationFailure.Unknown, result.Failure);
}
[Fact]
public async Task AcceptsResponseWithNativeModeFlagsAndExtendedHeader()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var endpoint = new DeviceEndpoint(IPAddress.Loopback.ToString(), ((IPEndPoint)listener.LocalEndpoint).Port);
var serverTask = ReceiveLoginAndRespondAsync(
listener,
0,
SuccessfulResponsePayload(),
timeout.Token,
responseFlags: 0x06);
var factory = new RsNetSessionFactory();
await using var session = await factory.ConnectAsync(endpoint, timeout.Token);
var result = await session.AuthenticateAsync(new DeviceCredentials("viewer", "secret"), timeout.Token);
await serverTask;
Assert.True(result.IsAuthenticated);
}
private static async Task<(byte[] Header, byte[] Payload)> ReceiveLoginAndRespondAsync(
TcpListener listener,
ushort status,
byte[] responsePayload,
CancellationToken cancellationToken,
byte responseFlags = 0)
{
using var client = await listener.AcceptTcpClientAsync(cancellationToken);
var stream = client.GetStream();
var header = new byte[16];
var payload = new byte[0x50];
await stream.ReadExactlyAsync(header, cancellationToken);
await stream.ReadExactlyAsync(payload, cancellationToken);
if ((header[0] & 0x03) == 0x02)
{
TransformBits(header.AsSpan(2), decode: true);
TransformBits(payload, decode: true);
}
var additionalHeaderLength = (responseFlags >> 2) * sizeof(uint);
var responseHeader = new byte[16 + additionalHeaderLength];
responseHeader[0] = responseFlags;
BinaryPrimitives.WriteUInt16LittleEndian(responseHeader.AsSpan(2, 2), status);
BinaryPrimitives.WriteUInt32LittleEndian(responseHeader.AsSpan(8, 4), (uint)responsePayload.Length);
var wireResponsePayload = responsePayload.ToArray();
if ((responseFlags & 0x03) == 0x02)
{
TransformBits(responseHeader.AsSpan(2), decode: false);
TransformBits(wireResponsePayload, decode: false);
}
await stream.WriteAsync(responseHeader, cancellationToken);
await stream.WriteAsync(wireResponsePayload, cancellationToken);
return (header, payload);
}
private static void TransformBits(Span<byte> data, bool decode)
{
var bitCount = data.Length * 8;
if (bitCount == 0)
{
return;
}
var next = new int[bitCount];
for (var index = 0; index < bitCount; index++)
{
next[index] = (index + 1) % bitCount;
}
var current = bitCount - 1;
var remaining = bitCount;
for (var step = 0; step < 2 % remaining; step++)
{
current = next[current];
}
var transformed = new byte[data.Length];
for (var bitIndex = 0; bitIndex < bitCount; bitIndex++)
{
for (var step = 0; step < 2 % remaining; step++)
{
current = next[current];
}
var selected = next[current];
var sourceBitIndex = decode ? bitIndex : selected;
var destinationBitIndex = decode ? selected : bitIndex;
if ((data[sourceBitIndex / 8] & (0x80 >> (sourceBitIndex % 8))) != 0)
{
transformed[destinationBitIndex / 8] |= (byte)(0x80 >> (destinationBitIndex % 8));
}
next[current] = next[selected];
remaining--;
}
transformed.AsSpan().CopyTo(data);
}
private static byte[] SuccessfulResponsePayload()
{
var payload = new byte[8];
payload[6] = (byte)'S';
payload[7] = (byte)'R';
return payload;
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Protocol.RSNet\Surveillance.Protocol.RSNet.csproj" />
</ItemGroup>
</Project>