-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCameraLibraryPageViewModel.cs
More file actions
524 lines (455 loc) · 20.3 KB
/
Copy pathCameraLibraryPageViewModel.cs
File metadata and controls
524 lines (455 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.Logging;
using OpenIPC.Viewer.App.Messages;
using OpenIPC.Viewer.App.Services;
using OpenIPC.Viewer.App.ViewModels.Dialogs;
using OpenIPC.Viewer.Core.Entities;
using OpenIPC.Viewer.Core.Onvif.Discovery;
using OpenIPC.Viewer.Core.Services;
namespace OpenIPC.Viewer.App.ViewModels;
public sealed partial class CameraLibraryPageViewModel : ViewModelBase
{
private readonly CameraDirectoryService _directory;
private readonly IDialogService _dialogs;
private readonly CameraEditorFactory _editorFactory;
private readonly DiscoveryDialogFactory _discoveryFactory;
private readonly ILogger<CameraLibraryPageViewModel> _logger;
public string Title => Localizer.Instance["Library.Title"];
public ObservableCollection<CameraRowViewModel> Cameras { get; } = new();
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasCameras))]
[NotifyPropertyChangedFor(nameof(IsEmpty))]
private bool _isLoaded;
// Gates the centered loader. Empty-state is also suppressed while loading so
// refresh doesn't flash "No cameras yet" between Clear() and Add().
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsEmpty))]
private bool _isLoading;
public bool HasCameras => IsLoaded && Cameras.Count > 0;
public bool IsEmpty => IsLoaded && !IsLoading && Cameras.Count == 0;
private readonly UserSettingsService _userSettings;
private readonly IDiscoveryService _discovery;
private readonly IReachabilityProbe _reachability;
private readonly ManageGroupsDialogFactory _manageGroupsFactory;
private bool _autoScanRanThisSession;
private System.Collections.Generic.IReadOnlyList<Camera> _allCameras = System.Array.Empty<Camera>();
public ObservableCollection<CameraGroup?> AvailableGroups { get; } = new();
[ObservableProperty] private CameraGroup? _selectedGroupFilter;
partial void OnSelectedGroupFilterChanged(CameraGroup? value) => RefilterCameras();
public CameraLibraryPageViewModel(
CameraDirectoryService directory,
IDialogService dialogs,
CameraEditorFactory editorFactory,
DiscoveryDialogFactory discoveryFactory,
ManageGroupsDialogFactory manageGroupsFactory,
UserSettingsService userSettings,
IDiscoveryService discovery,
IReachabilityProbe reachability,
ILogger<CameraLibraryPageViewModel> logger)
{
_directory = directory;
_dialogs = dialogs;
_editorFactory = editorFactory;
_discoveryFactory = discoveryFactory;
_manageGroupsFactory = manageGroupsFactory;
_userSettings = userSettings;
_discovery = discovery;
_reachability = reachability;
_logger = logger;
Cameras.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(HasCameras));
OnPropertyChanged(nameof(IsEmpty));
};
}
public async Task LoadAsync(CancellationToken ct)
{
IsLoading = true;
try
{
_allCameras = await _directory.ListAsync(ct).ConfigureAwait(true);
await ReloadGroupsAsync(ct).ConfigureAwait(true);
RefilterCameras();
IsLoaded = true;
}
finally
{
IsLoading = false;
}
// First-run welcome — only the very first time the library opens
// empty. WelcomeShown persists across launches; the user can't be
// nagged again after they've dismissed it once, even if they later
// delete all cameras.
if (Cameras.Count == 0 && !_userSettings.Current.WelcomeShown)
await ShowWelcomeAsync().ConfigureAwait(true);
if (_userSettings.Current.AutoScanLanOnStartup && !_autoScanRanThisSession)
_ = MaybeAutoScanAsync();
}
private async Task MaybeAutoScanAsync()
{
_autoScanRanThisSession = true;
try
{
// Existing host names already in library — discovery candidates
// matching one of these are dropped before any UI prompt.
var existing = new System.Collections.Generic.HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var row in Cameras) existing.Add(row.Camera.Host);
var found = new System.Collections.Generic.List<string>();
using var cts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(4));
await foreach (var dc in _discovery.ScanAsync(TimeSpan.FromSeconds(4), cts.Token).ConfigureAwait(true))
{
if (existing.Add(dc.Host))
found.Add(dc.Host);
}
if (found.Count == 0)
{
_logger.LogInformation("Auto-scan: no new cameras on the LAN");
return;
}
_logger.LogInformation("Auto-scan: {Count} new camera(s) on the LAN: {Hosts}", found.Count, string.Join(", ", found));
var open = await _dialogs.ConfirmAsync(
title: Localizer.Instance["Library.Dialog.NewCamerasTitle"],
message: string.Format(Localizer.Instance["Library.Dialog.NewCamerasMessage"], found.Count),
confirmLabel: Localizer.Instance["Library.Dialog.OpenDiscovery"],
cancelLabel: Localizer.Instance["Library.Dialog.NotNow"]).ConfigureAwait(true);
if (open)
await DiscoverCameraAsync().ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Auto-scan failed");
}
}
private async Task ShowWelcomeAsync()
{
// Mark "shown" up front so a dialog crash doesn't loop us back into
// the prompt on every refresh. If the user picks an action, we run
// the matching command after persisting.
await _userSettings.UpdateAsync(_userSettings.Current with { WelcomeShown = true })
.ConfigureAwait(true);
var pick = await _dialogs.ShowWelcomeAsync().ConfigureAwait(true);
switch (pick)
{
case WelcomeResult.Discover:
await DiscoverCameraAsync().ConfigureAwait(true);
break;
case WelcomeResult.ScanQr:
await ScanQrAsync().ConfigureAwait(true);
break;
case WelcomeResult.AddManually:
await AddCameraAsync().ConfigureAwait(true);
break;
// Skip → nothing.
}
}
[RelayCommand]
private Task RefreshAsync() => LoadAsync(CancellationToken.None);
private async Task ReloadGroupsAsync(CancellationToken ct)
{
var groups = await _directory.ListGroupsAsync(ct).ConfigureAwait(true);
// Preserve the current selection's Id across reloads (record identity
// changes when we re-query the DB).
var prevId = SelectedGroupFilter?.Id;
AvailableGroups.Clear();
AvailableGroups.Add(null); // "All groups"
foreach (var g in groups) AvailableGroups.Add(g);
if (prevId is { } id)
{
foreach (var g in AvailableGroups)
if (g is not null && g.Id.Equals(id)) { SelectedGroupFilter = g; return; }
}
SelectedGroupFilter = null;
}
private void RefilterCameras()
{
var filtered = SelectedGroupFilter is null
? _allCameras
: (System.Collections.Generic.IReadOnlyList<Camera>)
System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Where(_allCameras, c => c.GroupId.Equals(SelectedGroupFilter.Id)));
Cameras.Clear();
foreach (var camera in filtered)
Cameras.Add(new CameraRowViewModel(camera, _directory, _reachability, _logger));
// Kick off reachability probes for the freshly-built rows. Fire-and-forget:
// each row updates its own Status independently, in parallel.
_ = ProbeReachabilityAsync();
}
/// <summary>
/// Re-runs reachability probes for the rows already on screen. Called by
/// the view on every Loaded — the full LoadAsync only runs once (IsLoaded
/// gate), so without this a status probed before e.g. a Wi-Fi hiccup
/// stayed OFFLINE forever while the stream itself played fine.
/// </summary>
public Task ReprobeReachabilityAsync() => ProbeReachabilityAsync();
private async Task ProbeReachabilityAsync()
{
var rows = new System.Collections.Generic.List<CameraRowViewModel>(Cameras);
var tasks = new System.Collections.Generic.List<Task>(rows.Count);
foreach (var row in rows)
tasks.Add(row.RefreshReachabilityAsync(CancellationToken.None));
await Task.WhenAll(tasks).ConfigureAwait(true);
}
[RelayCommand]
private async Task ManageGroupsAsync()
{
var vm = _manageGroupsFactory.Create();
await _dialogs.ShowManageGroupsAsync(vm).ConfigureAwait(true);
// After the dialog closes, refresh both lists — groups may have been
// added/renamed/removed; cameras' GroupId might have been orphaned.
await LoadAsync(CancellationToken.None).ConfigureAwait(true);
}
[RelayCommand]
private void OpenCamera(CameraRowViewModel? row)
{
if (row is null)
return;
WeakReferenceMessenger.Default.Send(new OpenCameraMessage(row.Camera.Id));
}
[RelayCommand]
private async Task AddCameraAsync()
{
var editor = _editorFactory.CreateForNew();
var result = await _dialogs.ShowCameraEditorAsync(editor).ConfigureAwait(true);
if (result?.NewRequest is not { } req)
return;
try
{
await _directory.AddAsync(req, CancellationToken.None).ConfigureAwait(true);
await LoadAsync(CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to add camera {Name}", req.Name);
}
}
[RelayCommand]
private async Task DiscoverCameraAsync()
{
var discoveryVm = _discoveryFactory.Create();
var found = await _dialogs.ShowDiscoveryDialogAsync(discoveryVm).ConfigureAwait(true);
if (found is null)
return;
// Pre-fill the editor from the probe result so the user sees / can tweak
// everything before saving (RTSP URI especially — phase-04 risks §"ONVIF
// returns wrong RTSP URI behind NAT" applies).
var editor = _editorFactory.CreateForNew();
editor.Name = found.Discovered.Model ?? found.Discovered.Name ?? found.Discovered.Host;
editor.Host = found.Discovered.Host;
editor.OnvifPortText = found.Discovered.OnvifPort.ToString(System.Globalization.CultureInfo.InvariantCulture);
editor.RtspMainText = found.Probe.RtspMainUri.ToString();
editor.Username = found.Credentials?.Username ?? "";
editor.Password = found.Credentials?.Password ?? "";
var result = await _dialogs.ShowCameraEditorAsync(editor).ConfigureAwait(true);
if (result?.NewRequest is not { } req)
return;
try
{
var id = await _directory.AddAsync(req, CancellationToken.None).ConfigureAwait(true);
// Persist HasPtz / ProfileToken / manufacturer info from the probe so
// SingleCameraPage knows whether to show the PTZ joystick (Phase 4c).
await _directory.SaveOnvifMetadataAsync(id, found.Probe, CancellationToken.None).ConfigureAwait(true);
await LoadAsync(CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to add discovered camera {Host}", req.Host);
}
}
[RelayCommand]
private async Task ScanQrAsync()
{
// Desktop-only flow: pick a saved QR image, decode it via ZXing, parse
// one of the three supported payload shapes, pre-fill CameraEditor so
// the user reviews + confirms before save. Mobile in-camera scan is a
// follow-up (phase-11.2 spec).
var path = await _dialogs.PickImageFileAsync(Localizer.Instance["Library.ScanQr.PickerTitle"]).ConfigureAwait(true);
if (string.IsNullOrEmpty(path)) return;
string? text;
try
{
text = await QrImageDecoder.DecodeAsync(path, CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "QR decode failed");
await _dialogs.ConfirmAsync(
title: Localizer.Instance["Library.ScanQr.DecodeFailedTitle"],
message: string.Format(Localizer.Instance["Library.ScanQr.DecodeFailedFormat"], ex.Message),
confirmLabel: Localizer.Instance["Common.Cancel"],
cancelLabel: Localizer.Instance["Common.Cancel"]).ConfigureAwait(true);
return;
}
if (string.IsNullOrEmpty(text))
{
await _dialogs.ConfirmAsync(
title: Localizer.Instance["Library.ScanQr.NoQrTitle"],
message: Localizer.Instance["Library.ScanQr.NoQrMessage"],
confirmLabel: Localizer.Instance["Common.Cancel"],
cancelLabel: Localizer.Instance["Common.Cancel"]).ConfigureAwait(true);
return;
}
var payload = QrPayloadParser.TryParse(text);
if (payload is null)
{
await _dialogs.ConfirmAsync(
title: Localizer.Instance["Library.ScanQr.UnsupportedTitle"],
message: Localizer.Instance["Library.ScanQr.UnsupportedMessage"],
confirmLabel: Localizer.Instance["Common.Cancel"],
cancelLabel: Localizer.Instance["Common.Cancel"]).ConfigureAwait(true);
return;
}
var editor = _editorFactory.CreateForNew();
if (!string.IsNullOrEmpty(payload.Name)) editor.Name = payload.Name!;
else if (!string.IsNullOrEmpty(payload.Host)) editor.Name = payload.Host!;
if (!string.IsNullOrEmpty(payload.Host)) editor.Host = payload.Host!;
if (!string.IsNullOrEmpty(payload.RtspMain)) editor.RtspMainText = payload.RtspMain!;
if (payload.OnvifPort is { } op) editor.OnvifPortText = op.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (payload.HttpPort is { } hp) editor.HttpPort = hp;
if (!string.IsNullOrEmpty(payload.Username)) editor.Username = payload.Username!;
if (!string.IsNullOrEmpty(payload.Password)) editor.Password = payload.Password!;
var result = await _dialogs.ShowCameraEditorAsync(editor).ConfigureAwait(true);
if (result?.NewRequest is not { } req) return;
try
{
await _directory.AddAsync(req, CancellationToken.None).ConfigureAwait(true);
await LoadAsync(CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to add QR-scanned camera {Host}", req.Host);
}
}
[RelayCommand]
private async Task EditCameraAsync(CameraRowViewModel? row)
{
if (row is null)
return;
var creds = await _directory.GetCredentialsAsync(row.Camera.Id, CancellationToken.None).ConfigureAwait(true);
var editor = _editorFactory.CreateForEdit(row.Camera, creds);
var result = await _dialogs.ShowCameraEditorAsync(editor).ConfigureAwait(true);
if (result?.UpdateRequest is not { } req)
return;
try
{
await _directory.UpdateAsync(row.Camera.Id, req, CancellationToken.None).ConfigureAwait(true);
await LoadAsync(CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update camera {Id}", row.Camera.Id);
}
}
[RelayCommand]
private async Task DeleteCameraAsync(CameraRowViewModel? row)
{
if (row is null)
return;
var confirmed = await _dialogs.ConfirmAsync(
title: Localizer.Instance["Library.Dialog.DeleteTitle"],
message: string.Format(Localizer.Instance["Library.Dialog.DeleteMessage"], row.Camera.Name),
confirmLabel: Localizer.Instance["Common.Delete"],
cancelLabel: Localizer.Instance["Common.Cancel"]).ConfigureAwait(true);
if (!confirmed)
return;
try
{
await _directory.RemoveAsync(row.Camera.Id, CancellationToken.None).ConfigureAwait(true);
await LoadAsync(CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete camera {Id}", row.Camera.Id);
}
}
}
public enum CameraReachability { Checking, Online, Offline }
public sealed partial class CameraRowViewModel : ViewModelBase
{
// Probe timeout per camera. Kept short so a screen of offline cameras
// settles quickly — probes run in parallel, so this is the worst-case
// wait for the whole list, not a per-camera sum.
private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(2);
private readonly CameraDirectoryService? _directory;
private readonly IReachabilityProbe? _reachability;
private readonly ILogger? _logger;
public Camera Camera { get; }
public string Name => Camera.Name;
public string HostAndPort => Camera.HttpPort == 80
? Camera.Host
: $"{Camera.Host}:{Camera.HttpPort}";
[ObservableProperty] private bool _isIncludedInGrid;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(StatusText))]
private CameraReachability _status = CameraReachability.Checking;
public string StatusText => Localizer.Instance[Status switch
{
CameraReachability.Online => "Library.Online",
CameraReachability.Checking => "Library.Checking",
_ => "Library.Offline",
}];
public CameraRowViewModel(Camera camera) : this(camera, null, null, null) { }
public CameraRowViewModel(Camera camera, CameraDirectoryService? directory, ILogger? logger)
: this(camera, directory, null, logger) { }
public CameraRowViewModel(Camera camera, CameraDirectoryService? directory, IReachabilityProbe? reachability, ILogger? logger)
{
Camera = camera;
_directory = directory;
_reachability = reachability;
_logger = logger;
_isIncludedInGrid = camera.IncludedInGrid;
}
/// <summary>
/// TCP-probes the camera's RTSP port and updates <see cref="Status"/>.
/// Started from the UI thread; the connect runs off-thread and the status
/// write resumes on the UI thread (ConfigureAwait(true)).
/// </summary>
public async Task RefreshReachabilityAsync(CancellationToken ct)
{
if (_reachability is null)
return;
Status = CameraReachability.Checking;
// RTSP default port is 554; Uri.Port yields -1 when the scheme has no
// registered default and the URI omits an explicit port.
var port = Camera.RtspMainUri.Port;
if (port <= 0) port = 554;
// Probe the endpoint the player actually dials. The RTSP URI host can
// differ from the Host field (ONVIF behind NAT, mDNS name vs IP) — a
// probe against the wrong one showed OFFLINE while the stream played.
var host = Camera.RtspMainUri.Host;
if (string.IsNullOrEmpty(host)) host = Camera.Host;
try
{
var reachable = await _reachability
.IsReachableAsync(host, port, ProbeTimeout, ct)
.ConfigureAwait(true);
Status = reachable ? CameraReachability.Online : CameraReachability.Offline;
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Reachability probe failed for {CameraId}", Camera.Id);
Status = CameraReachability.Offline;
}
}
partial void OnIsIncludedInGridChanged(bool value)
{
if (_directory is null) return;
_ = PersistGridFlagAsync(value);
}
private async Task PersistGridFlagAsync(bool value)
{
try
{
await _directory!.SetIncludedInGridAsync(Camera.Id, value, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Failed to persist IncludedInGrid for {CameraId}", Camera.Id);
}
}
}