feat: Chronos Desktop shares its library on the LAN (owner review 5 P4)
Chronos Server for Windows is replaced by Settings > Server > Share this library: Chronos Desktop hosts the server engine in its own process over its own index, archive and processing services, job engine and scheduler, so a second PC, the Uploader and render nodes use this PC's library without a Windows service or a second index. - Chronos.Server is a library; Chronos.Server.Host is the console exe that Docker and development runs start. The App references the library and the ASP.NET Core shared framework (no package). - ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and never creates, starts or disposes them; no static log sink, no console lifetime; server.json plus desktop-owned values locked "Set in Chronos Desktop"; only upload-cleanup and audit-cleanup schedules are added. - Both modes: by-id endpoints scoped to the served archive, a client's render export folder dropped; hosted mode exposes server job kinds only. - Desktop: LibraryShare (start after the schedules, stop first, port in use named), Settings > Server sharing rows, Server > This library panel (state, addresses with Copy, ports, fingerprint, temporary admin password, clients, admin panel), own library refused by ConnectFlow and dropped from LAN discovery, the uploads sweep step, thumbnails after scans while sharing, capture scenes server-share and server-share-failed. - Removed: the Windows service hosting of Chronos.Server, its switches and its tests. Refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9ad8c6f7a9
commit
8d41992d84
69 files changed
+2633
-859
No files matched your search
@@ -13,8 +13,13 @@
|
||||
<ProjectReference Include="..\Chronos.Core.Windows\Chronos.Core.Windows.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Data\Chronos.Data.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Server\Chronos.Server.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Ui\Chronos.Ui.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Share this library hosts the server in-process (owner review 5, #67): ASP.NET Core is a shared framework, no package. -->
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Chronos.App.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -69,6 +69,36 @@ public sealed class SampleData
|
||||
/// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary>
|
||||
public Guid ProxiedSequenceId => _sunrise;
|
||||
|
||||
/// <summary>The certificate fingerprint of this PC's shared library in the captures.</summary>
|
||||
public const string ShareFingerprint = "4F:0B:E2:91:7C:3A:D5:68:B0:1E:29:C7:83:5D:F4:A6:12:9E:7B:40:D8:6C:35:E1:A9:52:0F:BD:74:C3:86:2E";
|
||||
|
||||
/// <summary>Server › This library shared (owner review 5, #67): sample addresses, two clients, the temporary password.</summary>
|
||||
public static void ShowShare(AppServices services)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
var pc = AppEnvironment.SamplePcName;
|
||||
services.Share.ShowSample(ShareState.On, null,
|
||||
[$"https://{pc}:8443", $"https://{pc}.studio.lan:8443", "https://192.168.1.20:8443", "https://100.88.14.3:8443"], 8443, 8080, ShareFingerprint,
|
||||
"kT7p-Qm2x-Wf9r", [
|
||||
new ShareClient("anna", "Chronos Uploader (ANNA-LAPTOP)", "192.168.1.31", Now.AddMinutes(-1)),
|
||||
new ShareClient("admin", Chronos.Server.Security.ClientActivity.AdminPanel, "127.0.0.1", Now.AddMinutes(-3)),
|
||||
]);
|
||||
}
|
||||
|
||||
/// <summary>Server › This library that could not start: the port is taken.</summary>
|
||||
public static void ShowShareFailed(AppServices services)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
services.Share.ShowSample(ShareState.Failed, Loc.L("Errors.Share.PortInUse", 8443), [], 0, 0, null, null, []);
|
||||
}
|
||||
|
||||
/// <summary>Server › This library not shared, as before <see cref="ShowShare"/>.</summary>
|
||||
public static void HideShare(AppServices services)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
services.Share.ShowSample(ShareState.Off, null, [], 0, 0, null, null, []);
|
||||
}
|
||||
|
||||
/// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary>
|
||||
public static SampleData Configure(AppServices services)
|
||||
{
|
||||
|
||||
@@ -44,6 +44,16 @@ public sealed class AppEnvironment
|
||||
public string LogDirectory => Path.Combine(DataDirectory, "logs");
|
||||
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
|
||||
public string BackupDirectory => Path.Combine(DataDirectory, "backups");
|
||||
|
||||
/// <summary>The private folder of the server this PC runs while it shares its library: certificate, settings, uploads, logs.</summary>
|
||||
public string ShareDirectory => Path.Combine(DataDirectory, "server");
|
||||
|
||||
/// <summary>The PC's name as the screens show it: a capture shows <see cref="SamplePcName"/>.</summary>
|
||||
public string PcName => IsCapture ? SamplePcName : Environment.MachineName;
|
||||
|
||||
/// <summary>The PC name captures show.</summary>
|
||||
public const string SamplePcName = "STUDIO-PC";
|
||||
|
||||
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
|
||||
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
|
||||
|
||||
|
||||
@@ -74,6 +74,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
// The editor's open and closed groups survive a restart (owner review 1, R3).
|
||||
Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings);
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
Share = new LibraryShare(this);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
|
||||
@@ -114,6 +115,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
if (_server is not null) _server.PropertyChanged -= OnServerChanged;
|
||||
_server = value;
|
||||
_server.IsOwnLibrary = Share.IsOwn;
|
||||
_server.PropertyChanged += OnServerChanged;
|
||||
UpdateRenderNode();
|
||||
Sync.Update();
|
||||
@@ -123,6 +125,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
|
||||
public SyncHost Sync { get; }
|
||||
|
||||
/// <summary>Settings › Server › Share this library: this PC's library served to the LAN while Chronos runs (owner review 5, #67).</summary>
|
||||
public LibraryShare Share { get; }
|
||||
|
||||
/// <summary>
|
||||
/// A job of this PC moved a sequence's folder or changed its title or file names (a Reorganize step), or replaced its
|
||||
/// frames' files (a conversion), with the sequence's id (any thread): an open editor reads it again where and as it is now.
|
||||
@@ -239,6 +244,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
SaveSettingsAction();
|
||||
UpdateRenderNode();
|
||||
ApplyJobSettings();
|
||||
if (!Environment.IsCapture) Share.Apply();
|
||||
}
|
||||
|
||||
/// <summary>Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last).</summary>
|
||||
@@ -329,6 +335,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
await _stopping.CancelAsync().ConfigureAwait(false);
|
||||
await _schedules.ConfigureAwait(false);
|
||||
// First: the shared library's clients and its subscriptions to the engine and the scheduler go before they do.
|
||||
await Share.DisposeAsync().ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_stopping.Dispose();
|
||||
@@ -361,6 +369,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
await StartSchedulerAsync(ct).ConfigureAwait(false);
|
||||
if (reopen is null)
|
||||
{
|
||||
await Share.StartAsync(ct).ConfigureAwait(false);
|
||||
await ScanNowAsync(started, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
@@ -369,6 +378,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
|
||||
await Share.StartAsync(ct).ConfigureAwait(false);
|
||||
await ScanNowAsync(null, ct).ConfigureAwait(false);
|
||||
Scheduler?.Wake();
|
||||
return;
|
||||
@@ -559,19 +569,24 @@ public sealed class AppServices : IAsyncDisposable
|
||||
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
|
||||
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
|
||||
// The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c).
|
||||
// The shared library's upload-cleanup schedule runs on this PC's scheduler (owner review 5, #67).
|
||||
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)),
|
||||
new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)],
|
||||
new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace), new ShareUploadsStep(() => Share)],
|
||||
BackupDirectory = Environment.BackupDirectory,
|
||||
// Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job runs.
|
||||
SequenceChanged = (id, _, _) =>
|
||||
// While the library is shared, its clients see thumbnails and proxies of what a scan finds, as a server's do.
|
||||
ImagesAfterScanWhen = () => Share.IsOn,
|
||||
// Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job
|
||||
// runs; the shared library's clients are told too.
|
||||
SequenceChanged = (id, change, token) =>
|
||||
{
|
||||
SequenceReorganized?.Invoke(id);
|
||||
return Task.CompletedTask;
|
||||
return Share.SequenceChangedAsync(id, change, token);
|
||||
},
|
||||
ProjectsChanged = (changed, token) => Share.ProjectsChangedAsync(changed, token),
|
||||
};
|
||||
Archives = new ArchiveService(database, archive);
|
||||
// The videos folder may not lie in the workspace either, and a copy of a server's renders downloads through its connection (phase 5).
|
||||
Archives.Videos.ProtectedFolders = () => [Workspace.Root];
|
||||
Archives.Videos.ProtectedFolders = () => [Workspace.Root, Share.Folder];
|
||||
Archives.Videos.Servers = Sync;
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
Sync.Open(database, Archives, archive);
|
||||
@@ -602,6 +617,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
|
||||
Host = EncoderHost.Client,
|
||||
ProducedBy = System.Environment.MachineName,
|
||||
// A render or an advice recorded on this PC reaches the shared library's clients (owner review 5, #67).
|
||||
SequenceChanged = (id, change, token) => Share.SequenceChangedAsync(id, change, token),
|
||||
Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount,
|
||||
CacheStore.Folder(Environment, Settings)),
|
||||
};
|
||||
|
||||
@@ -88,6 +88,40 @@ public sealed class KnownServer
|
||||
public DateTimeOffset LastSeen { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Server › Sharing (owner review 5, #67): this PC's library served to the LAN by the server Chronos hosts
|
||||
/// while it runs. Absent in a 1.0 settings file: off, on Docker's ports.
|
||||
/// </summary>
|
||||
public sealed class ShareSettings
|
||||
{
|
||||
public const int DefaultHttpsPort = 8443;
|
||||
public const int DefaultHttpPort = 8080;
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>The name clients see; empty: this PC's name.</summary>
|
||||
public string? Name { get; set; }
|
||||
|
||||
public int HttpsPort { get; set; } = DefaultHttpsPort;
|
||||
public int HttpPort { get; set; } = DefaultHttpPort;
|
||||
|
||||
/// <summary>The ports clients reach when a router forwards others to this PC; null: the ones above.</summary>
|
||||
public int? PublicHttpsPort { get; set; }
|
||||
|
||||
public int? PublicHttpPort { get; set; }
|
||||
|
||||
/// <summary>Announce the library to Chronos programs on the local network.</summary>
|
||||
public bool Discovery { get; set; } = true;
|
||||
|
||||
/// <summary>What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live.</summary>
|
||||
public bool SameEndpoint(ShareSettings other)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(other);
|
||||
return string.Equals(Name?.Trim() ?? string.Empty, other.Name?.Trim() ?? string.Empty, StringComparison.Ordinal) && HttpsPort == other.HttpsPort &&
|
||||
HttpPort == other.HttpPort && PublicHttpsPort == other.PublicHttpsPort && PublicHttpPort == other.PublicHttpPort && Discovery == other.Discovery;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
|
||||
/// <c>settings.json</c> next to the database and written atomically, because language and theme apply before the
|
||||
@@ -292,6 +326,9 @@ public sealed class AppSettings
|
||||
/// <summary>The known server of <paramref name="id"/>; null when this PC has none.</summary>
|
||||
public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
|
||||
|
||||
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67).</summary>
|
||||
public ShareSettings Share { get; set; } = new();
|
||||
|
||||
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
|
||||
public bool RenderNodeOptIn { get; set; }
|
||||
|
||||
|
||||
@@ -67,6 +67,8 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
|
||||
// The ages and the limit are Settings › Workspace's, read at each run: the schedule holds no days of its own.
|
||||
new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime),
|
||||
new ScheduleParametersDto(Steps: [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], OlderThanDays: 0)),
|
||||
// While this PC shares its library (owner review 5, #67): the shared library's own clean-ups, which its Reset restores.
|
||||
.. settings.Share.Enabled ? Chronos.Server.Jobs.ServerScheduleHost.ShareSchedules(0) : [],
|
||||
];
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
xmlns:shell="clr-namespace:Chronos.App.Shell"
|
||||
xmlns:srv="clr-namespace:Chronos.App.Server">
|
||||
xmlns:srv="clr-namespace:Chronos.App.Server"
|
||||
xmlns:sec="clr-namespace:Chronos.App.Sections">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
|
||||
<Setter Property="MinWidth" Value="60" />
|
||||
@@ -42,14 +43,87 @@
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- Server.html: the connection panel, then the sync table. The render-node status panel is not built (see the decisions). -->
|
||||
<!-- Server.html: this PC's shared library, the connection panel, then the sync table. The render-node status panel is not
|
||||
built (see the decisions). -->
|
||||
<Grid Margin="20,16,20,12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="16,14">
|
||||
<!-- This library (owner review 5, #67): sharing state, addresses with Copy, ports, fingerprint, temporary admin password,
|
||||
clients and the admin panel; off, one row and Sharing settings. -->
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="16,12" DataContext="{Binding SharePanel}">
|
||||
<StackPanel>
|
||||
<DockPanel>
|
||||
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Title}" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.AdminPanel}" Command="{Binding AdminPanelCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.AdminPanel}" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Settings}" Command="{Binding SettingsCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.Settings}" Visibility="{Binding IsNotShared, Converter={StaticResource BoolToVisibility}}" />
|
||||
<WrapPanel VerticalAlignment="Center">
|
||||
<ui:StatusGlyph Kind="{Binding StatusKind}" Text="{Binding StateText}" FontSize="13" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Share.State}"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateText}" />
|
||||
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Restart}" Command="{Binding RestartCommand}" ToolTip="{l:Loc Tooltips.Server.Share.Restart}"
|
||||
Margin="12,0,0,0" Visibility="{Binding HasFailed, Converter={StaticResource BoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
</DockPanel>
|
||||
<ui:StatusGlyph Kind="Error" Text="{Binding Reason}" FontSize="12" Margin="0,8,0,0" HorizontalAlignment="Left"
|
||||
Visibility="{Binding Reason, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
<Grid Margin="0,10,0,0" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Addresses}" Margin="0,4,10,0" VerticalAlignment="Top" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding Addresses}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type sec:ShareAddressRow}">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,18,4">
|
||||
<TextBlock Text="{Binding Address}" FlowDirection="LeftToRight" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyCommand}" CommandParameter="{Binding Address}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.Copy}" AutomationProperties.Name="{Binding Address}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Ports}" Margin="0,6,10,0" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding PortsText}" Margin="0,6,0,0" Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Share.Ports}" />
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Fingerprint}" Margin="0,10,10,0" VerticalAlignment="Center" />
|
||||
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal" Margin="0,6,0,0">
|
||||
<TextBlock Text="{Binding Fingerprint}" FontFamily="{DynamicResource Font.Mono}" FontSize="12" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.Fingerprint}" />
|
||||
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyFingerprintCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.CopyFingerprint}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.AdminPassword}" Margin="0,10,10,0" VerticalAlignment="Center"
|
||||
Visibility="{Binding HasAdminPassword, Converter={StaticResource BoolToVisibility}}" />
|
||||
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" Margin="0,6,0,0" Visibility="{Binding HasAdminPassword, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{Binding PasswordText}" FontFamily="{DynamicResource Font.Mono}" FontSize="12" VerticalAlignment="Center" FlowDirection="LeftToRight"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.AdminPassword}" />
|
||||
<Button Style="{StaticResource Button.Compact}" Content="{Binding ShowPasswordText}" Command="{Binding ShowPasswordCommand}" ToolTip="{l:Loc Tooltips.Server.Share.Show}"
|
||||
Margin="8,0,0,0" />
|
||||
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyPasswordCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.CopyPassword}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Clients}" Margin="0,10,10,0" VerticalAlignment="Top" />
|
||||
<StackPanel Grid.Row="4" Grid.Column="1" Margin="0,10,0,0" ToolTip="{l:Loc Tooltips.Server.Share.Clients}">
|
||||
<TextBlock Text="{Binding ClientsText}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<ItemsControl ItemsSource="{Binding Clients}" Focusable="False" Visibility="{Binding HasClients, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Padding="16,14" Margin="0,14,0,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@@ -167,7 +241,7 @@
|
||||
</Border>
|
||||
|
||||
<!-- Sequences of this PC and of the server: chips, search, Upload all local; table; footer. -->
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
|
||||
<Border Grid.Row="2" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
|
||||
@@ -41,11 +41,15 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
Sync = new SyncTableViewModel(shell);
|
||||
_conflicts = Sync.Chips.Single(c => c.Filter == SyncFilter.Conflicts);
|
||||
_conflicts.PropertyChanged += OnConflictsChanged;
|
||||
SharePanel = new SharePanelViewModel(shell);
|
||||
}
|
||||
|
||||
/// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary>
|
||||
public SyncTableViewModel Sync { get; }
|
||||
|
||||
/// <summary>This PC's library shared to the LAN (owner review 5, #67).</summary>
|
||||
public SharePanelViewModel SharePanel { get; }
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
private ServerSession Session => _session ?? Shell.Services.Server;
|
||||
@@ -222,6 +226,7 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
|
||||
Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged;
|
||||
Sync.Dispose();
|
||||
SharePanel.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
|
||||
@@ -635,6 +635,47 @@
|
||||
|
||||
<!-- ================= Server ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}">
|
||||
<!-- Sharing (owner review 5, #67): this PC's library served to the LAN while Chronos runs. -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Share}">
|
||||
<CheckBox Content="{l:Loc Settings.Server.ShareLibrary}" IsChecked="{Binding ShareRows.Enabled}" ToolTip="{l:Loc Tooltips.Settings.ShareLibrary}" Margin="0,4,0,0" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.ShareName}">
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding ShareRows.Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ShareRows.Name}" ToolTip="{Binding ShareRows.Name.ToolTip}" ui:Field.Placeholder="{Binding ShareRows.PcName}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Server.ShareName}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.HttpsPort}">
|
||||
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.HttpsPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ShareRows.HttpsPort}" ToolTip="{Binding ShareRows.HttpsPort.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Server.HttpsPort}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.HttpPort}">
|
||||
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.HttpPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ShareRows.HttpPort}" ToolTip="{Binding ShareRows.HttpPort.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Server.HttpPort}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.PublicHttpsPort}">
|
||||
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.PublicHttpsPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ShareRows.PublicHttpsPort}" ToolTip="{Binding ShareRows.PublicHttpsPort.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Server.PublicHttpsPort}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.PublicHttpPort}">
|
||||
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.PublicHttpPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding ShareRows.PublicHttpPort}" ToolTip="{Binding ShareRows.PublicHttpPort.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Server.PublicHttpPort}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Discovery}">
|
||||
<CheckBox Content="{l:Loc Settings.Server.Announce}" IsChecked="{Binding ShareRows.Discovery}" ToolTip="{l:Loc Tooltips.Settings.Discovery}" Margin="0,4,0,0" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.ShareFolder}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding ShareRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.ShareFolder}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Server.ShareFolder}" />
|
||||
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding ShareRows.OpenFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenShareFolder}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}">
|
||||
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding DefaultServer.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
|
||||
|
||||
@@ -91,7 +91,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
|
||||
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
|
||||
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Share", "Settings.Server.ShareName", "Settings.Server.HttpsPort", "Settings.Server.HttpPort",
|
||||
"Settings.Server.PublicHttpsPort", "Settings.Server.PublicHttpPort", "Settings.Server.Discovery", "Settings.Server.ShareFolder", "Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
|
||||
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
|
||||
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
|
||||
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
|
||||
@@ -177,6 +178,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
// Saving applies them to the log files (App.SaveSettings).
|
||||
Logs = new LogSettingsRows(_s, Save);
|
||||
|
||||
// ---- Server › Sharing (owner review 5, #67); saving applies it to the share (AppServices.SaveSettings). ----
|
||||
ShareRows = new ShareSettingsRows(_s, Save, Shell.Services.Environment.ShareDirectory, Shell.Services.Environment.PcName);
|
||||
|
||||
// ---- Workspace ----
|
||||
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
|
||||
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
|
||||
@@ -831,6 +835,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
|
||||
public LogSettingsRows Logs { get; }
|
||||
|
||||
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN (owner review 5, #67).</summary>
|
||||
public ShareSettingsRows ShareRows { get; }
|
||||
|
||||
public ICommand OpenDataFolderCommand { get; }
|
||||
public ICommand OpenLogsCommand { get; }
|
||||
public ICommand ExportDiagnosticsCommand { get; }
|
||||
@@ -1667,6 +1674,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
break;
|
||||
case SettingsPage.Server:
|
||||
_s.RenderNodeOptIn = defaults.RenderNodeOptIn;
|
||||
ShareRows.Reset();
|
||||
break;
|
||||
case SettingsPage.Updates:
|
||||
_s.CheckForUpdates = defaults.CheckForUpdates;
|
||||
@@ -1774,6 +1782,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
Logs.Refresh();
|
||||
WorkspaceRows.Refresh();
|
||||
ShareRows.Refresh();
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
/// <summary>An address of the shared library with its Copy button.</summary>
|
||||
public sealed record ShareAddressRow(string Address, ICommand CopyCommand);
|
||||
|
||||
/// <summary>
|
||||
/// Server › This library (owner review 5, #67): whether this PC shares its library, why not when it could not start
|
||||
/// (with Restart), the addresses with Copy, the ports, the certificate's fingerprint with Copy, the first administrator's
|
||||
/// temporary password while it exists (Show, Copy), the clients of the last minutes and the admin panel. Off, one row and
|
||||
/// Sharing settings. Follows <see cref="LibraryShare"/> on the UI thread; the clients are read again every few seconds.
|
||||
/// </summary>
|
||||
public sealed class SharePanelViewModel : LocalizedViewModel
|
||||
{
|
||||
private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(10);
|
||||
|
||||
private readonly ShellViewModel _shell;
|
||||
private readonly LibraryShare _share;
|
||||
private readonly DispatcherTimer? _timer;
|
||||
private bool _showPassword;
|
||||
|
||||
public SharePanelViewModel(ShellViewModel shell)
|
||||
{
|
||||
_shell = shell;
|
||||
_share = shell.Services.Share;
|
||||
_share.PropertyChanged += OnShareChanged;
|
||||
CopyCommand = new RelayCommand(p => Copy(p as string));
|
||||
CopyFingerprintCommand = new RelayCommand(() => Copy(_share.Fingerprint), () => _share.Fingerprint is not null);
|
||||
ShowPasswordCommand = new RelayCommand(() =>
|
||||
{
|
||||
_showPassword = !_showPassword;
|
||||
OnPropertyChanged(nameof(PasswordText));
|
||||
OnPropertyChanged(nameof(ShowPasswordText));
|
||||
}, () => _share.AdminPassword is not null);
|
||||
CopyPasswordCommand = new RelayCommand(() => Copy(_share.AdminPassword), () => _share.AdminPassword is not null);
|
||||
AdminPanelCommand = new RelayCommand(() => ShellActions.OpenUrl($"https://localhost:{_share.HttpsPort}/admin"), () => _share.IsOn && _share.HttpsPort > 0);
|
||||
RestartCommand = new RelayCommand(() => _ = RestartAsync(), () => _share.State is ShareState.Failed);
|
||||
SettingsCommand = new RelayCommand(() =>
|
||||
{
|
||||
_shell.Settings.Page = SettingsPage.Server;
|
||||
_shell.Navigate(SectionKey.Settings);
|
||||
});
|
||||
if (Application.Current is not null && !shell.Services.Environment.IsCapture)
|
||||
{
|
||||
_timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = RefreshInterval };
|
||||
_timer.Tick += (_, _) =>
|
||||
{
|
||||
if (_share.IsOn) _ = RefreshAsync();
|
||||
};
|
||||
_timer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand CopyCommand { get; }
|
||||
public ICommand CopyFingerprintCommand { get; }
|
||||
public ICommand ShowPasswordCommand { get; }
|
||||
public ICommand CopyPasswordCommand { get; }
|
||||
public ICommand AdminPanelCommand { get; }
|
||||
public ICommand RestartCommand { get; }
|
||||
public ICommand SettingsCommand { get; }
|
||||
|
||||
/// <summary>Sharing is on in the settings, whether it runs or not: the details show.</summary>
|
||||
public bool IsShared => _share.State is not ShareState.Off;
|
||||
|
||||
public bool IsNotShared => !IsShared;
|
||||
|
||||
public bool IsOn => _share.IsOn;
|
||||
|
||||
public bool HasFailed => _share.State is ShareState.Failed;
|
||||
|
||||
public StatusKind StatusKind => _share.State switch
|
||||
{
|
||||
ShareState.On => StatusKind.Online,
|
||||
ShareState.Starting => StatusKind.Running,
|
||||
ShareState.Failed => StatusKind.Error,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
|
||||
public string StateText => Loc.L("Server.Share.State." + _share.State);
|
||||
|
||||
public string? Reason => _share.Reason;
|
||||
|
||||
public IReadOnlyList<ShareAddressRow> Addresses => [.. _share.Addresses.Select(a => new ShareAddressRow(a, CopyCommand))];
|
||||
|
||||
public string? PortsText => _share.IsOn ? Loc.L("Server.Share.PortsValue", _share.HttpsPort, _share.HttpPort) : null;
|
||||
|
||||
public string? Fingerprint => _share.Fingerprint is { } fingerprint ? Formatting.LeftToRight(fingerprint) : null;
|
||||
|
||||
public bool HasAdminPassword => _share.AdminPassword is not null;
|
||||
|
||||
/// <summary>The temporary password, masked until Show.</summary>
|
||||
public string? PasswordText => _share.AdminPassword is not { } password ? null : _showPassword ? password : new string('•', 12);
|
||||
|
||||
public string ShowPasswordText => Loc.L(_showPassword ? "Server.Share.Hide" : "Server.Share.Show");
|
||||
|
||||
/// <summary>"anna · Chronos Uploader · 192.168.1.20", the latest first.</summary>
|
||||
public IReadOnlyList<string> Clients => [.. _share.Clients.Select(c => Loc.L("Server.Share.ClientRow", c.User, c.Program, c.Address).TrimEnd(' ', '·'))];
|
||||
|
||||
public bool HasClients => _share.Clients.Count > 0;
|
||||
|
||||
public string ClientsText => HasClients ? Loc.Plural("Server.Share.ClientCount", _share.Clients.Count) : Loc.L("Server.Share.NoClients");
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_timer?.Stop();
|
||||
_share.PropertyChanged -= OnShareChanged;
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private async Task RestartAsync()
|
||||
{
|
||||
await _share.RestartAsync();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private async Task RefreshAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _share.RefreshAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException)
|
||||
{
|
||||
Log.Warning("share", "The clients of the shared library could not be read", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Copy(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return;
|
||||
try
|
||||
{
|
||||
Clipboard.SetText(text);
|
||||
}
|
||||
catch (ExternalException ex)
|
||||
{
|
||||
// Another program holds the clipboard: nothing was copied, as the next try may.
|
||||
Log.Warning("share", "The clipboard is busy", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnShareChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (Application.Current?.Dispatcher is { } dispatcher && !dispatcher.CheckAccess())
|
||||
{
|
||||
dispatcher.BeginInvoke(Changed);
|
||||
return;
|
||||
}
|
||||
Changed();
|
||||
}
|
||||
|
||||
private void Changed()
|
||||
{
|
||||
if (!_share.IsOn) _showPassword = false;
|
||||
OnAllPropertiesChanged();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,9 @@ public enum ConnectError
|
||||
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
|
||||
CertificateChanged,
|
||||
Failed,
|
||||
|
||||
/// <summary>The address is this PC's own shared library (owner review 5, #67), which this desktop already has open.</summary>
|
||||
OwnLibrary,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,6 +115,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
|
||||
/// <summary>Raised after every step change.</summary>
|
||||
public event EventHandler? Changed;
|
||||
|
||||
/// <summary>
|
||||
/// True for this PC's own shared library, by its certificate fingerprint or its server id (owner review 5, #67): the
|
||||
/// flow refuses it before any trust question or password.
|
||||
/// </summary>
|
||||
public Func<string?, Guid?, bool>? IsOwnLibrary { get; set; }
|
||||
|
||||
/// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary>
|
||||
public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default)
|
||||
{
|
||||
@@ -221,10 +230,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
|
||||
var clock = Stopwatch.StartNew();
|
||||
Info = await _api.GetInfoAsync(ct);
|
||||
Latency = clock.Elapsed;
|
||||
if (IsOwnLibrary?.Invoke(Info.TlsFingerprint, Info.ServerId) == true) return Fail(ConnectError.OwnLibrary);
|
||||
return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
|
||||
}
|
||||
catch (UntrustedCertificateException untrusted)
|
||||
{
|
||||
if (IsOwnLibrary?.Invoke(untrusted.Fingerprint, null) == true) return Fail(ConnectError.OwnLibrary);
|
||||
PendingFingerprint = untrusted.Fingerprint;
|
||||
return Set(ConnectStep.AwaitingTrust, ConnectError.None);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>Where sharing this PC's library stands (Server › This library).</summary>
|
||||
public enum ShareState
|
||||
{
|
||||
/// <summary>Settings › Server › Share this library is off.</summary>
|
||||
Off,
|
||||
|
||||
Starting,
|
||||
|
||||
/// <summary>The library is served: clients connect to <see cref="LibraryShare.Addresses"/>.</summary>
|
||||
On,
|
||||
|
||||
/// <summary>Sharing is on in the settings but could not start: <see cref="LibraryShare.Reason"/> says why.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>A program that used the shared library lately, as the Server section lists it.</summary>
|
||||
public sealed record ShareClient(string User, string Program, string Address, DateTimeOffset? LastSeen);
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts in its own process to serve this
|
||||
/// PC's current archive to the LAN, over the index, engines, job engine and scheduler of <see cref="AppServices"/> (one
|
||||
/// engine, one index). Started after the schedules, stopped before them; started, stopped and restarted off the UI thread,
|
||||
/// one at a time. A settings save applies the live values at once and restarts on a new name, port, discovery choice or
|
||||
/// archive. Its state, addresses, fingerprint, clients and the first administrator's temporary password are what the Server
|
||||
/// section shows. Property changes are raised on any thread (scalar values and whole lists only).
|
||||
/// </summary>
|
||||
public sealed class LibraryShare : ObservableObject, IAsyncDisposable
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private HostedServer? _server;
|
||||
private ShareSettings? _running;
|
||||
private string? _archiveRoot;
|
||||
private ShareState _state = ShareState.Off;
|
||||
private string? _reason;
|
||||
private IReadOnlyList<string> _addresses = [];
|
||||
private IReadOnlyList<ShareClient> _clients = [];
|
||||
private string? _fingerprint;
|
||||
private string? _adminPassword;
|
||||
private int _httpsPort;
|
||||
private int _httpPort;
|
||||
private bool _sample;
|
||||
private bool _disposed;
|
||||
|
||||
public LibraryShare(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
}
|
||||
|
||||
public ShareState State
|
||||
{
|
||||
get => _state;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _state, value)) return;
|
||||
OnPropertyChanged(nameof(IsOn));
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while the library is served.</summary>
|
||||
public bool IsOn => _state == ShareState.On;
|
||||
|
||||
/// <summary>One sentence on why sharing did not start; null otherwise.</summary>
|
||||
public string? Reason
|
||||
{
|
||||
get => _reason;
|
||||
private set => Set(ref _reason, value);
|
||||
}
|
||||
|
||||
/// <summary>The addresses clients reach this library at, one per name and network address of this PC.</summary>
|
||||
public IReadOnlyList<string> Addresses
|
||||
{
|
||||
get => _addresses;
|
||||
private set => Set(ref _addresses, value);
|
||||
}
|
||||
|
||||
/// <summary>The certificate's SHA-256 fingerprint, colon hex, as clients see it on their first connection.</summary>
|
||||
public string? Fingerprint
|
||||
{
|
||||
get => _fingerprint;
|
||||
private set => Set(ref _fingerprint, value);
|
||||
}
|
||||
|
||||
/// <summary>The port the HTTPS listener got; 0 while not shared.</summary>
|
||||
public int HttpsPort
|
||||
{
|
||||
get => _httpsPort;
|
||||
private set => Set(ref _httpsPort, value);
|
||||
}
|
||||
|
||||
/// <summary>The port the HTTP listener got; 0 while not shared.</summary>
|
||||
public int HttpPort
|
||||
{
|
||||
get => _httpPort;
|
||||
private set => Set(ref _httpPort, value);
|
||||
}
|
||||
|
||||
/// <summary>The first administrator's temporary password while its file exists; null once an administrator set their own.</summary>
|
||||
public string? AdminPassword
|
||||
{
|
||||
get => _adminPassword;
|
||||
private set => Set(ref _adminPassword, value);
|
||||
}
|
||||
|
||||
/// <summary>The programs of the last minutes and the render nodes online (<see cref="RefreshAsync"/>).</summary>
|
||||
public IReadOnlyList<ShareClient> Clients
|
||||
{
|
||||
get => _clients;
|
||||
private set => Set(ref _clients, value);
|
||||
}
|
||||
|
||||
/// <summary>The server while the library is served (tests, the change bridge); null otherwise.</summary>
|
||||
public HostedServer? Server => _server;
|
||||
|
||||
/// <summary>The private folder of the shared library's own state: certificate, settings, partial uploads, logs.</summary>
|
||||
public string Folder => _services.Environment.ShareDirectory;
|
||||
|
||||
/// <summary>The state changed (any thread).</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>
|
||||
/// Starts sharing when Settings › Server says so and it is not running: the current archive of Settings › Archive is
|
||||
/// served. Never throws: a failure is the state <see cref="ShareState.Failed"/> with its <see cref="Reason"/>.
|
||||
/// </summary>
|
||||
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed || _sample || _server is not null || !_services.Settings.Share.Enabled) return;
|
||||
await StartCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops sharing (the desktop's engines run on); the state reads as the settings say.</summary>
|
||||
public async Task StopAsync()
|
||||
{
|
||||
await _gate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await StopCoreAsync().ConfigureAwait(false);
|
||||
State = ShareState.Off;
|
||||
Reason = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops sharing if it runs and starts it again (Server › Restart, a new port or archive).</summary>
|
||||
public async Task RestartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed || _sample) return;
|
||||
await StopCoreAsync().ConfigureAwait(false);
|
||||
if (_services.Settings.Share.Enabled) await StartCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
else State = ShareState.Off;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings were saved: sharing turned off stops, turned on starts, a new name, port, discovery choice or archive
|
||||
/// restarts; the parallelism, the priority queue, the language and the logs apply to the running server at once.
|
||||
/// </summary>
|
||||
public void Apply()
|
||||
{
|
||||
if (_disposed || _sample) return;
|
||||
var share = _services.Settings.Share;
|
||||
if (!share.Enabled)
|
||||
{
|
||||
if (_server is not null || _state != ShareState.Off) _ = Run(StopAsync());
|
||||
return;
|
||||
}
|
||||
if (_server is not { } server)
|
||||
{
|
||||
// Not running yet: the start after the schedules starts it, or it waits for the index; a failed one tries again.
|
||||
if (_services.Scheduler is not null && _state != ShareState.Starting) _ = Run(StartAsync());
|
||||
return;
|
||||
}
|
||||
if (_running is { } running && running.SameEndpoint(share) && string.Equals(_archiveRoot, _services.Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
server.ApplyDesktop(DesktopValues(_archiveRoot!));
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
Log.Warning("share", "The settings could not be applied to the shared library", ex);
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ = Run(RestartAsync());
|
||||
}
|
||||
|
||||
/// <summary>True for this PC's own shared library, by its certificate or its server id: the desktop never connects to itself.</summary>
|
||||
public bool IsOwn(string? fingerprint, Guid? serverId)
|
||||
{
|
||||
if (_server is not { } server) return false;
|
||||
if (serverId is { } id && server.ServerId == id) return true;
|
||||
return fingerprint is { Length: > 0 } && string.Equals(fingerprint, server.Fingerprint, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Reads the programs of the last minutes, the render nodes online and the temporary password again.</summary>
|
||||
public async Task RefreshAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_sample || _server is not { } server) return;
|
||||
var clients = server.Clients.Recent().Select(c => new ShareClient(c.User, c.Client, c.Address, c.LastSeen)).ToList();
|
||||
try
|
||||
{
|
||||
foreach (var node in await server.RenderNodesAsync(cancellationToken).ConfigureAwait(false))
|
||||
clients.Add(new ShareClient(node, Loc.L("Server.Share.RenderNode"), string.Empty, null));
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or ObjectDisposedException)
|
||||
{
|
||||
Log.Warning("share", "The render nodes online could not be read", ex);
|
||||
}
|
||||
Clients = clients;
|
||||
AdminPassword = server.AdminPassword();
|
||||
}
|
||||
|
||||
/// <summary>The <c>uploads</c> clean-up step while sharing (<see cref="ShareUploadsStep"/>): the server's sweep, or nothing.</summary>
|
||||
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
|
||||
_server is { } server ? server.SweepUploadsAsync(context, parameters) : Task.FromResult(Loc.L("Server.Log.SharingOff"));
|
||||
|
||||
/// <summary>The desktop's archive or processing service changed sequence <paramref name="id"/>: the clients are told.</summary>
|
||||
public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
|
||||
_server is { } server ? server.SequenceChangedAsync(id, change, cancellationToken) : Task.CompletedTask;
|
||||
|
||||
/// <summary>The desktop's archive service changed a sequence's projects: the clients are told.</summary>
|
||||
public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
|
||||
_server is { } server ? server.ProjectsChangedAsync(changed, cancellationToken) : Task.CompletedTask;
|
||||
|
||||
/// <summary>Capture and design time: a shared library with sample values, no server.</summary>
|
||||
internal void ShowSample(ShareState state, string? reason, IReadOnlyList<string> addresses, int httpsPort, int httpPort, string? fingerprint,
|
||||
string? adminPassword, IReadOnlyList<ShareClient> clients)
|
||||
{
|
||||
_sample = true;
|
||||
Reason = reason;
|
||||
Addresses = addresses;
|
||||
HttpsPort = httpsPort;
|
||||
HttpPort = httpPort;
|
||||
Fingerprint = fingerprint;
|
||||
AdminPassword = adminPassword;
|
||||
Clients = clients;
|
||||
State = state;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _gate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
await StopCoreAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The addresses of <paramref name="port"/> on this PC: its name, its full name, and each network address that is up.</summary>
|
||||
public static IReadOnlyList<string> AddressesOf(int port)
|
||||
{
|
||||
var hosts = new List<string> { System.Environment.MachineName };
|
||||
try
|
||||
{
|
||||
if (IPGlobalProperties.GetIPGlobalProperties().DomainName is { Length: > 0 } domain) hosts.Add(System.Environment.MachineName + "." + domain);
|
||||
foreach (var network in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (network.OperationalStatus != OperationalStatus.Up || network.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
|
||||
foreach (var unicast in network.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
var ip = unicast.Address;
|
||||
if (IPAddress.IsLoopback(ip)) continue;
|
||||
if (ip.AddressFamily == AddressFamily.InterNetwork && !ip.ToString().StartsWith("169.254.", StringComparison.Ordinal)) hosts.Add(ip.ToString());
|
||||
else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !ip.IsIPv6LinkLocal && !ip.IsIPv6SiteLocal && !ip.IsIPv6Multicast)
|
||||
hosts.Add("[" + new IPAddress(ip.GetAddressBytes()) + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (NetworkInformationException ex)
|
||||
{
|
||||
Log.Warning("share", "The network addresses of this PC could not be read", ex);
|
||||
}
|
||||
return [.. hosts.Distinct(StringComparer.OrdinalIgnoreCase).Select(h => $"https://{h}:{port}")];
|
||||
}
|
||||
|
||||
private async Task StartCoreAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var s = _services;
|
||||
if (s.Database is not { } db || s.Archives is not { } archives || s.Processing is not { } processing || s.Engine is not { } engine
|
||||
|| s.Scheduler is not { } scheduler)
|
||||
{
|
||||
Fail(Loc.L("Errors.Share.NotReady"));
|
||||
return;
|
||||
}
|
||||
Reason = null;
|
||||
State = ShareState.Starting;
|
||||
var archive = await s.ScheduleHost.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (archive is null)
|
||||
{
|
||||
Fail(Loc.L("Errors.Share.NoArchive"));
|
||||
return;
|
||||
}
|
||||
var share = Snapshot(s.Settings.Share);
|
||||
HostedServer? server = null;
|
||||
try
|
||||
{
|
||||
server = await Task.Run(() =>
|
||||
{
|
||||
var options = ServerOptions.ForHosted(Folder, DesktopValues(archive.RootPath));
|
||||
return ServerHost.BuildHosted(options, new HostedEngine(db, archives, processing, engine, scheduler, archive));
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
// Off the caller's thread: the server's own services never continue on the UI thread.
|
||||
await Task.Run(() => server.StartAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException && Failure(ex, share) is { } reason)
|
||||
{
|
||||
if (server is not null) await DisposeQuietlyAsync(server).ConfigureAwait(false);
|
||||
Log.Error("share", "This library could not be shared", ex);
|
||||
Fail(reason);
|
||||
return;
|
||||
}
|
||||
_server = server;
|
||||
_running = share;
|
||||
_archiveRoot = archive.RootPath;
|
||||
server.JobChangedOutside += OnJobChangedOutside;
|
||||
HttpsPort = server.HttpsPort;
|
||||
HttpPort = server.HttpPort;
|
||||
Fingerprint = server.Fingerprint;
|
||||
Addresses = AddressesOf(server.HttpsPort);
|
||||
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
|
||||
await RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("share", $"Sharing {archive.RootPath} on HTTPS {server.HttpsPort} and HTTP {server.HttpPort}");
|
||||
State = ShareState.On;
|
||||
}
|
||||
|
||||
private async Task StopCoreAsync()
|
||||
{
|
||||
if (_server is not { } server) return;
|
||||
_server = null;
|
||||
_running = null;
|
||||
_archiveRoot = null;
|
||||
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
|
||||
server.JobChangedOutside -= OnJobChangedOutside;
|
||||
await DisposeQuietlyAsync(server).ConfigureAwait(false);
|
||||
Addresses = [];
|
||||
Clients = [];
|
||||
Fingerprint = null;
|
||||
AdminPassword = null;
|
||||
HttpsPort = 0;
|
||||
HttpPort = 0;
|
||||
Log.Info("share", "Sharing stopped");
|
||||
}
|
||||
|
||||
private void Fail(string reason)
|
||||
{
|
||||
Reason = reason;
|
||||
State = ShareState.Failed;
|
||||
}
|
||||
|
||||
/// <summary>The desktop's values the shared library takes: Settings › Server, Rendering, Videos and Advanced › Logs.</summary>
|
||||
private HostedSettings DesktopValues(string archiveRoot)
|
||||
{
|
||||
var s = _services.Settings;
|
||||
var share = s.Share;
|
||||
return new HostedSettings(string.IsNullOrWhiteSpace(share.Name) ? null : share.Name.Trim(), share.HttpPort, share.HttpsPort, share.PublicHttpPort,
|
||||
share.PublicHttpsPort, share.Discovery, archiveRoot, string.IsNullOrWhiteSpace(s.VideosFolder) ? null : s.VideosFolder, _services.Parallelism,
|
||||
s.PriorityQueue, new Dictionary<string, string>(s.JobPriorities, StringComparer.OrdinalIgnoreCase), Loc.Culture.TwoLetterISOLanguageName,
|
||||
s.LogLevel, s.LogRetentionDays, s.LogMaxFileMb, s.LogMaxTotalMb, s.LogRotation, s.DiagnosticsLogMb);
|
||||
}
|
||||
|
||||
/// <summary>The sentence for a start that failed; null for an exception that is not an expected failure.</summary>
|
||||
private static string? Failure(Exception ex, ShareSettings share)
|
||||
{
|
||||
if (IsAddressInUse(ex)) return Loc.L("Errors.Share.PortInUse", PortInUse(share));
|
||||
return ex is InvalidOperationException or IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException
|
||||
or DatabaseException or ArgumentException
|
||||
? Loc.L("Errors.Share.Failed", ex.Message)
|
||||
: null;
|
||||
}
|
||||
|
||||
private static bool IsAddressInUse(Exception ex)
|
||||
{
|
||||
for (var e = ex; e is not null; e = e.InnerException)
|
||||
{
|
||||
if (e is Microsoft.AspNetCore.Connections.AddressInUseException or SocketException { SocketErrorCode: SocketError.AddressAlreadyInUse }) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The configured port another program listens on (the HTTPS one when neither can be told).</summary>
|
||||
private static int PortInUse(ShareSettings share)
|
||||
{
|
||||
try
|
||||
{
|
||||
var listening = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Select(e => e.Port).ToHashSet();
|
||||
if (!listening.Contains(share.HttpsPort) && listening.Contains(share.HttpPort)) return share.HttpPort;
|
||||
}
|
||||
catch (NetworkInformationException)
|
||||
{
|
||||
}
|
||||
return share.HttpsPort;
|
||||
}
|
||||
|
||||
private static ShareSettings Snapshot(ShareSettings share) => new()
|
||||
{
|
||||
Enabled = share.Enabled,
|
||||
Name = share.Name,
|
||||
HttpsPort = share.HttpsPort,
|
||||
HttpPort = share.HttpPort,
|
||||
PublicHttpsPort = share.PublicHttpsPort,
|
||||
PublicHttpPort = share.PublicHttpPort,
|
||||
Discovery = share.Discovery,
|
||||
};
|
||||
|
||||
private static async Task DisposeQuietlyAsync(HostedServer server)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The app's exit waits for this on the UI thread: nothing the server's services await may continue on it.
|
||||
await Task.Run(() => server.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or IOException or ObjectDisposedException or OperationCanceledException or AggregateException)
|
||||
{
|
||||
Log.Warning("share", "The shared library did not stop cleanly", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnNetworkChanged(object? sender, EventArgs e)
|
||||
{
|
||||
if (_server is { } server) Addresses = AddressesOf(server.HttpsPort);
|
||||
}
|
||||
|
||||
/// <summary>A render node changed a job outside the engine: the Jobs section follows it as it follows the engine's own changes.</summary>
|
||||
private void OnJobChangedOutside(Chronos.Core.Model.Job job) => JobChangedOutside?.Invoke(job);
|
||||
|
||||
/// <summary>A render node changed a job's state outside this PC's engine (any thread).</summary>
|
||||
public event Action<Chronos.Core.Model.Job>? JobChangedOutside;
|
||||
|
||||
/// <summary>Runs a fire-and-forget step, logging what it throws.</summary>
|
||||
private static async Task Run(Task task)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Error("share", "Sharing could not be updated", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's clean-up step <c>uploads</c> (owner review 5, #67): the upload-cleanup schedule the shared library adds runs
|
||||
/// on this PC's scheduler, so the step is the desktop's, and it sweeps the shared library's abandoned uploads while it runs.
|
||||
/// </summary>
|
||||
public sealed class ShareUploadsStep(Func<LibraryShare> share) : ICleanupStep
|
||||
{
|
||||
public string Name => Chronos.Server.Storage.UploadCleanupStep.StepName;
|
||||
|
||||
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters) => share().SweepUploadsAsync(context, parameters);
|
||||
}
|
||||
@@ -70,7 +70,8 @@ public sealed class DpapiTokenProtector : ITokenProtector
|
||||
}
|
||||
|
||||
/// <summary>A Chronos Server announced on the LAN.</summary>
|
||||
public sealed record DiscoveredServer(string Name, string Address);
|
||||
/// <summary>A server announced on the LAN; <paramref name="Fingerprint"/> is its beacon's certificate fingerprint, if any.</summary>
|
||||
public sealed record DiscoveredServer(string Name, string Address, string? Fingerprint = null);
|
||||
|
||||
/// <summary>
|
||||
/// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) and reports each server once.
|
||||
@@ -120,7 +121,7 @@ public sealed class DiscoveryListener : IDisposable
|
||||
{
|
||||
var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
|
||||
if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
|
||||
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address));
|
||||
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address), beacon.TlsFingerprint);
|
||||
lock (_seen)
|
||||
{
|
||||
if (!_seen.Add(server.Address)) continue;
|
||||
|
||||
@@ -32,6 +32,13 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
||||
|
||||
public ConnectFlow Flow => _flow;
|
||||
|
||||
/// <summary>True for this PC's own shared library (by fingerprint or server id): never connected to, never listed as found.</summary>
|
||||
public Func<string?, Guid?, bool>? IsOwnLibrary
|
||||
{
|
||||
get => _flow.IsOwnLibrary;
|
||||
set => _flow.IsOwnLibrary = value;
|
||||
}
|
||||
|
||||
/// <summary>Servers that announced themselves on this network.</summary>
|
||||
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
|
||||
|
||||
@@ -185,6 +192,8 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
||||
_discovery = new DiscoveryListener();
|
||||
_discovery.Found += server =>
|
||||
{
|
||||
// This PC's own shared library announces itself too: it is open here already (owner review 5, #67).
|
||||
if (_flow.IsOwnLibrary?.Invoke(server.Fingerprint, null) == true) return;
|
||||
if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
|
||||
Discovered.Add(server);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// The sharing rows of Settings › Server (owner review 5, #67): Share this library, its name, its ports (the public ones
|
||||
/// may stay empty), the LAN announcement and the shared library's own data folder. Each value is stored and saved at once;
|
||||
/// saving applies it to the share (<see cref="AppServices.SaveSettings"/>), which restarts on a new name, port or
|
||||
/// announcement. The rows read <see cref="AppSettings.Share"/> each time: Reset and Import replace it.
|
||||
/// </summary>
|
||||
public sealed class ShareSettingsRows : ObservableObject
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private readonly Action _save;
|
||||
|
||||
public ShareSettingsRows(AppSettings settings, Action save, string folder, string pcName)
|
||||
{
|
||||
_settings = settings;
|
||||
_save = save;
|
||||
PcName = pcName;
|
||||
Folder = AppEnvironment.Shown(folder);
|
||||
Name = new EditableField(Share.Name ?? string.Empty, _ => null, v =>
|
||||
{
|
||||
Share.Name = v.Trim().Length == 0 ? null : v.Trim();
|
||||
_save();
|
||||
}, () => Loc.L("Tooltips.Settings.ShareName"));
|
||||
HttpsPort = Port(() => Share.HttpsPort, v => Share.HttpsPort = v, "Tooltips.Settings.HttpsPort");
|
||||
HttpPort = Port(() => Share.HttpPort, v => Share.HttpPort = v, "Tooltips.Settings.HttpPort");
|
||||
PublicHttpsPort = PublicPort(() => Share.PublicHttpsPort, v => Share.PublicHttpsPort = v);
|
||||
PublicHttpPort = PublicPort(() => Share.PublicHttpPort, v => Share.PublicHttpPort = v);
|
||||
OpenFolderCommand = new RelayCommand(() => ShellActions.Reveal(folder));
|
||||
}
|
||||
|
||||
private ShareSettings Share => _settings.Share;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => Share.Enabled;
|
||||
set
|
||||
{
|
||||
if (Share.Enabled == value) return;
|
||||
Share.Enabled = value;
|
||||
_save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public EditableField Name { get; }
|
||||
public EditableField HttpsPort { get; }
|
||||
public EditableField HttpPort { get; }
|
||||
public EditableField PublicHttpsPort { get; }
|
||||
public EditableField PublicHttpPort { get; }
|
||||
|
||||
public bool Discovery
|
||||
{
|
||||
get => Share.Discovery;
|
||||
set
|
||||
{
|
||||
if (Share.Discovery == value) return;
|
||||
Share.Discovery = value;
|
||||
_save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The name clients see while <see cref="Name"/> is empty: this PC's.</summary>
|
||||
public string PcName { get; }
|
||||
|
||||
/// <summary>The shared library's private folder, as the screens show paths.</summary>
|
||||
public string Folder { get; }
|
||||
|
||||
public ICommand OpenFolderCommand { get; }
|
||||
|
||||
/// <summary>Settings › Server › Reset: sharing off, on the default ports.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_settings.Share = new ShareSettings();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Shows the values as they are now (after Reset all, Import, or a reset of the page).</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
Name.Load(Share.Name ?? string.Empty);
|
||||
HttpsPort.Load(Text(Share.HttpsPort));
|
||||
HttpPort.Load(Text(Share.HttpPort));
|
||||
PublicHttpsPort.Load(Share.PublicHttpsPort is { } https ? Text(https) : string.Empty);
|
||||
PublicHttpPort.Load(Share.PublicHttpPort is { } http ? Text(http) : string.Empty);
|
||||
OnPropertyChanged(nameof(Enabled));
|
||||
OnPropertyChanged(nameof(Discovery));
|
||||
}
|
||||
|
||||
private EditableField Port(Func<int> read, Action<int> write, string toolTip) =>
|
||||
new(Text(read()), v => ValidatePort(v), v =>
|
||||
{
|
||||
write(int.Parse(v.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture));
|
||||
_save();
|
||||
}, () => Loc.L(toolTip));
|
||||
|
||||
private EditableField PublicPort(Func<int?> read, Action<int?> write) =>
|
||||
new(read() is { } port ? Text(port) : string.Empty, v => v.Trim().Length == 0 ? null : ValidatePort(v), v =>
|
||||
{
|
||||
write(v.Trim().Length == 0 ? null : int.Parse(v.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture));
|
||||
_save();
|
||||
}, () => Loc.L("Tooltips.Settings.PublicPorts"));
|
||||
|
||||
private static string Text(int port) => port.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static string? ValidatePort(string text) =>
|
||||
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n is >= 1 and <= 65535
|
||||
? null
|
||||
: Loc.L("Errors.Number.Range", 1.ToString("N0", Loc.Culture), 65535.ToString("N0", Loc.Culture));
|
||||
}
|
||||
@@ -113,6 +113,12 @@ public static class ScreenCapture
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
written += await SaveAsync(window, directory, "server", theme);
|
||||
// This PC's library shared (owner review 5, #67), then one that could not start.
|
||||
SampleData.ShowShare(shell.Services);
|
||||
written += await SaveAsync(window, directory, "server-share", theme);
|
||||
SampleData.ShowShareFailed(shell.Services);
|
||||
written += await SaveAsync(window, directory, "server-share-failed", theme);
|
||||
SampleData.HideShare(shell.Services);
|
||||
|
||||
// Every page, About last (owner review 2, R5).
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
|
||||
Reference in new issue
Block a user