-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathFileSyncListViewModel.cs
More file actions
527 lines (462 loc) · 18.8 KB
/
Copy pathFileSyncListViewModel.cs
File metadata and controls
527 lines (462 loc) · 18.8 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
525
526
527
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage.Pickers;
using Coder.Desktop.App.Models;
using Coder.Desktop.App.Services;
using Coder.Desktop.App.Views;
using Coder.Desktop.CoderSdk.Agent;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using WinRT.Interop;
namespace Coder.Desktop.App.ViewModels;
public partial class FileSyncListViewModel : ObservableObject
{
private Window? _window;
private DispatcherQueue? _dispatcherQueue;
private DirectoryPickerWindow? _remotePickerWindow;
private readonly ISyncSessionController _syncSessionController;
private readonly IRpcController _rpcController;
private readonly ICredentialManager _credentialManager;
private readonly IAgentApiClientFactory _agentApiClientFactory;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowUnavailable))]
[NotifyPropertyChangedFor(nameof(ShowLoading))]
[NotifyPropertyChangedFor(nameof(ShowError))]
[NotifyPropertyChangedFor(nameof(ShowSessions))]
public partial string? UnavailableMessage { get; set; } = null;
// Initially we use the current cached state, the loading screen is only
// shown when the user clicks "Reload" on the error screen.
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowLoading))]
[NotifyPropertyChangedFor(nameof(ShowSessions))]
public partial bool Loading { get; set; } = false;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowLoading))]
[NotifyPropertyChangedFor(nameof(ShowError))]
[NotifyPropertyChangedFor(nameof(ShowSessions))]
public partial string? Error { get; set; } = null;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanOpenLocalPath))]
[NotifyPropertyChangedFor(nameof(NewSessionRemoteHostEnabled))]
[NotifyPropertyChangedFor(nameof(NewSessionRemotePathDialogEnabled))]
public partial bool OperationInProgress { get; set; } = false;
[ObservableProperty] public partial IReadOnlyList<SyncSessionViewModel> Sessions { get; set; } = [];
[ObservableProperty] public partial bool CreatingNewSession { get; set; } = false;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NewSessionCreateEnabled))]
public partial string NewSessionLocalPath { get; set; } = "";
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NewSessionCreateEnabled))]
[NotifyPropertyChangedFor(nameof(CanOpenLocalPath))]
public partial bool NewSessionLocalPathDialogOpen { get; set; } = false;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NewSessionRemoteHostEnabled))]
public partial IReadOnlyList<string> AvailableHosts { get; set; } = [];
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NewSessionCreateEnabled))]
[NotifyPropertyChangedFor(nameof(NewSessionRemotePathDialogEnabled))]
public partial string? NewSessionRemoteHost { get; set; } = null;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NewSessionCreateEnabled))]
public partial string NewSessionRemotePath { get; set; } = "";
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NewSessionCreateEnabled))]
[NotifyPropertyChangedFor(nameof(NewSessionRemotePathDialogEnabled))]
public partial bool NewSessionRemotePathDialogOpen { get; set; } = false;
public bool CanOpenLocalPath => !NewSessionLocalPathDialogOpen && !OperationInProgress;
public bool NewSessionRemoteHostEnabled => AvailableHosts.Count > 0 && !OperationInProgress;
public bool NewSessionRemotePathDialogEnabled =>
!string.IsNullOrWhiteSpace(NewSessionRemoteHost) && !NewSessionRemotePathDialogOpen && !OperationInProgress;
[ObservableProperty] public partial string NewSessionStatus { get; set; } = "";
public bool NewSessionCreateEnabled
{
get
{
if (string.IsNullOrWhiteSpace(NewSessionLocalPath)) return false;
if (NewSessionLocalPathDialogOpen) return false;
if (string.IsNullOrWhiteSpace(NewSessionRemoteHost)) return false;
if (string.IsNullOrWhiteSpace(NewSessionRemotePath)) return false;
if (NewSessionRemotePathDialogOpen) return false;
return true;
}
}
// TODO: this could definitely be improved
public bool ShowUnavailable => UnavailableMessage != null;
public bool ShowLoading => Loading && UnavailableMessage == null && Error == null;
public bool ShowError => UnavailableMessage == null && Error != null;
public bool ShowSessions => !Loading && UnavailableMessage == null && Error == null;
public FileSyncListViewModel(ISyncSessionController syncSessionController, IRpcController rpcController,
ICredentialManager credentialManager, IAgentApiClientFactory agentApiClientFactory)
{
_syncSessionController = syncSessionController;
_rpcController = rpcController;
_credentialManager = credentialManager;
_agentApiClientFactory = agentApiClientFactory;
}
public void Initialize(Window window, DispatcherQueue dispatcherQueue)
{
_window = window;
_dispatcherQueue = dispatcherQueue;
if (!_dispatcherQueue.HasThreadAccess)
throw new InvalidOperationException("Initialize must be called from the UI thread");
_rpcController.StateChanged += RpcControllerStateChanged;
_credentialManager.CredentialsChanged += CredentialManagerCredentialsChanged;
_syncSessionController.StateChanged += SyncSessionStateChanged;
_window.Closed += (_, _) =>
{
_remotePickerWindow?.Close();
_rpcController.StateChanged -= RpcControllerStateChanged;
_credentialManager.CredentialsChanged -= CredentialManagerCredentialsChanged;
_syncSessionController.StateChanged -= SyncSessionStateChanged;
};
var rpcModel = _rpcController.GetState();
var credentialModel = _credentialManager.GetCachedCredentials();
MaybeSetUnavailableMessage(rpcModel, credentialModel);
var syncSessionState = _syncSessionController.GetState();
UpdateSyncSessionState(syncSessionState);
}
private void RpcControllerStateChanged(object? sender, RpcModel rpcModel)
{
// Ensure we're on the UI thread.
if (_dispatcherQueue == null) return;
if (!_dispatcherQueue.HasThreadAccess)
{
_dispatcherQueue.TryEnqueue(() => RpcControllerStateChanged(sender, rpcModel));
return;
}
var credentialModel = _credentialManager.GetCachedCredentials();
MaybeSetUnavailableMessage(rpcModel, credentialModel);
}
private void CredentialManagerCredentialsChanged(object? sender, CredentialModel credentialModel)
{
// Ensure we're on the UI thread.
if (_dispatcherQueue == null) return;
if (!_dispatcherQueue.HasThreadAccess)
{
_dispatcherQueue.TryEnqueue(() => CredentialManagerCredentialsChanged(sender, credentialModel));
return;
}
var rpcModel = _rpcController.GetState();
MaybeSetUnavailableMessage(rpcModel, credentialModel);
}
private void SyncSessionStateChanged(object? sender, SyncSessionControllerStateModel syncSessionState)
{
// Ensure we're on the UI thread.
if (_dispatcherQueue == null) return;
if (!_dispatcherQueue.HasThreadAccess)
{
_dispatcherQueue.TryEnqueue(() => SyncSessionStateChanged(sender, syncSessionState));
return;
}
UpdateSyncSessionState(syncSessionState);
}
private void MaybeSetUnavailableMessage(RpcModel rpcModel, CredentialModel credentialModel, SyncSessionControllerStateModel? syncSessionState = null)
{
var oldMessage = UnavailableMessage;
if (rpcModel.RpcLifecycle != RpcLifecycle.Connected)
{
UnavailableMessage =
"Disconnected from the Windows service. Please see the tray window for more information.";
}
else if (credentialModel.State != CredentialState.Valid)
{
UnavailableMessage = "Please sign in to access file sync.";
}
else if (rpcModel.VpnLifecycle != VpnLifecycle.Started)
{
UnavailableMessage = "Please start Coder Connect from the tray window to access file sync.";
}
else if (syncSessionState != null && syncSessionState.Lifecycle == SyncSessionControllerLifecycle.Uninitialized)
{
UnavailableMessage = "Sync session controller is not initialized. Please wait...";
}
else
{
UnavailableMessage = null;
// Reload if we transitioned from unavailable to available.
if (oldMessage != null) ReloadSessions();
}
// When transitioning from available to unavailable:
if (oldMessage == null && UnavailableMessage != null)
ClearNewForm();
}
private void UpdateSyncSessionState(SyncSessionControllerStateModel syncSessionState)
{
// This should never happen.
if (syncSessionState == null)
return;
if (syncSessionState.Lifecycle == SyncSessionControllerLifecycle.Uninitialized)
{
MaybeSetUnavailableMessage(_rpcController.GetState(), _credentialManager.GetCachedCredentials(), syncSessionState);
}
Error = syncSessionState.DaemonError;
Sessions = syncSessionState.SyncSessions.Select(s => new SyncSessionViewModel(this, s)).ToList();
}
private void ClearNewForm()
{
CreatingNewSession = false;
NewSessionLocalPath = "";
NewSessionRemoteHost = "";
NewSessionRemotePath = "";
NewSessionStatus = "";
_remotePickerWindow?.Close();
}
[RelayCommand]
private void ReloadSessions()
{
Loading = true;
Error = null;
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
_syncSessionController.RefreshState(cts.Token).ContinueWith(HandleRefresh, CancellationToken.None);
}
private void HandleRefresh(Task<SyncSessionControllerStateModel> t)
{
// Ensure we're on the UI thread.
if (_dispatcherQueue == null) return;
if (!_dispatcherQueue.HasThreadAccess)
{
_dispatcherQueue.TryEnqueue(() => HandleRefresh(t));
return;
}
if (t.IsCompletedSuccessfully)
{
Sessions = t.Result.SyncSessions.Select(s => new SyncSessionViewModel(this, s)).ToList();
Loading = false;
Error = t.Result.DaemonError;
return;
}
Error = "Could not list sync sessions: ";
if (t.IsCanceled) Error += new TaskCanceledException();
else if (t.IsFaulted) Error += t.Exception;
else Error += "no successful result or error";
Loading = false;
}
// Overriding AvailableHosts seems to make the ComboBox clear its value, so
// we only do this while the create form is not open.
// Must be called in UI thread.
private void SetAvailableHostsFromRpcModel(RpcModel rpcModel)
{
var hosts = new List<string>(rpcModel.Agents.Count);
// Agents will only contain started agents.
foreach (var agent in rpcModel.Agents)
{
var fqdn = agent.Fqdn
.Select(a => a.Trim('.'))
.Where(a => !string.IsNullOrWhiteSpace(a))
.Aggregate((a, b) => a.Count(c => c == '.') < b.Count(c => c == '.') ? a : b);
if (string.IsNullOrWhiteSpace(fqdn))
continue;
hosts.Add(fqdn);
}
NewSessionRemoteHost = null;
AvailableHosts = hosts;
}
[RelayCommand]
private void StartCreatingNewSession()
{
ClearNewForm();
// Ensure we have a fresh hosts list before we open the form. We don't
// bind directly to the list on RPC state updates as updating the list
// while in use seems to break it.
SetAvailableHostsFromRpcModel(_rpcController.GetState());
CreatingNewSession = true;
}
[RelayCommand]
public async Task OpenLocalPathSelectDialog()
{
if (_window is null) return;
var picker = new FolderPicker
{
SuggestedStartLocation = PickerLocationId.ComputerFolder,
};
var hwnd = WindowNative.GetWindowHandle(_window);
InitializeWithWindow.Initialize(picker, hwnd);
NewSessionLocalPathDialogOpen = true;
try
{
var path = await picker.PickSingleFolderAsync();
if (path == null) return;
NewSessionLocalPath = path.Path;
}
catch
{
// ignored
}
finally
{
NewSessionLocalPathDialogOpen = false;
}
}
[RelayCommand]
public void OpenRemotePathSelectDialog()
{
if (string.IsNullOrWhiteSpace(NewSessionRemoteHost))
return;
if (_remotePickerWindow is not null)
{
_remotePickerWindow.Activate();
return;
}
NewSessionRemotePathDialogOpen = true;
var pickerViewModel = new DirectoryPickerViewModel(_agentApiClientFactory, NewSessionRemoteHost);
pickerViewModel.PathSelected += OnRemotePathSelected;
_remotePickerWindow = new DirectoryPickerWindow(pickerViewModel);
if (_window is not null)
_remotePickerWindow.SetParent(_window);
_remotePickerWindow.Closed += (_, _) =>
{
_remotePickerWindow = null;
NewSessionRemotePathDialogOpen = false;
};
_remotePickerWindow.Activate();
}
private void OnRemotePathSelected(object? sender, string? path)
{
if (sender is not DirectoryPickerViewModel pickerViewModel) return;
pickerViewModel.PathSelected -= OnRemotePathSelected;
if (path == null) return;
NewSessionRemotePath = path;
}
[RelayCommand]
private void CancelNewSession()
{
ClearNewForm();
}
private void OnCreateSessionProgress(string message)
{
// Ensure we're on the UI thread.
if (_dispatcherQueue == null) return;
if (!_dispatcherQueue.HasThreadAccess)
{
_dispatcherQueue.TryEnqueue(() => OnCreateSessionProgress(message));
return;
}
NewSessionStatus = message;
}
[RelayCommand]
private async Task ConfirmNewSession()
{
if (OperationInProgress || !NewSessionCreateEnabled) return;
OperationInProgress = true;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(120));
try
{
// The controller will send us a state changed event.
await _syncSessionController.CreateSyncSession(new CreateSyncSessionRequest
{
Alpha = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = NewSessionLocalPath,
},
Beta = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Ssh,
Host = NewSessionRemoteHost!,
Path = NewSessionRemotePath,
},
}, OnCreateSessionProgress, cts.Token);
ClearNewForm();
}
catch (Exception e)
{
var dialog = new ContentDialog
{
Title = "Failed to create sync session",
Content = $"{e}",
CloseButtonText = "Ok",
XamlRoot = _window?.Content.XamlRoot,
};
_ = await dialog.ShowAsync();
}
finally
{
OperationInProgress = false;
NewSessionStatus = "";
}
}
public async Task PauseOrResumeSession(string identifier)
{
if (OperationInProgress) return;
OperationInProgress = true;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var actionString = "resume/pause";
try
{
if (Sessions.FirstOrDefault(s => s.Model.Identifier == identifier) is not { } session)
throw new InvalidOperationException("Session not found");
// The controller will send us a state changed event.
if (session.Model.Paused)
{
actionString = "resume";
await _syncSessionController.ResumeSyncSession(session.Model.Identifier, cts.Token);
}
else
{
actionString = "pause";
await _syncSessionController.PauseSyncSession(session.Model.Identifier, cts.Token);
}
}
catch (Exception e)
{
var dialog = new ContentDialog
{
Title = $"Failed to {actionString} sync session",
Content = $"Identifier: {identifier}\n{e}",
CloseButtonText = "Ok",
XamlRoot = _window?.Content.XamlRoot,
};
_ = await dialog.ShowAsync();
}
finally
{
OperationInProgress = false;
}
}
public async Task TerminateSession(string identifier)
{
if (OperationInProgress) return;
OperationInProgress = true;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
try
{
if (Sessions.FirstOrDefault(s => s.Model.Identifier == identifier) is not { } session)
throw new InvalidOperationException("Session not found");
var confirmDialog = new ContentDialog
{
Title = "Terminate sync session",
Content = "Are you sure you want to terminate this sync session?",
PrimaryButtonText = "Terminate",
CloseButtonText = "Cancel",
DefaultButton = ContentDialogButton.Close,
XamlRoot = _window?.Content.XamlRoot,
};
var res = await confirmDialog.ShowAsync();
if (res is not ContentDialogResult.Primary)
return;
// The controller will send us a state changed event.
await _syncSessionController.TerminateSyncSession(session.Model.Identifier, cts.Token);
}
catch (Exception e)
{
var dialog = new ContentDialog
{
Title = "Failed to terminate sync session",
Content = $"Identifier: {identifier}\n{e}",
CloseButtonText = "Ok",
XamlRoot = _window?.Content.XamlRoot,
};
_ = await dialog.ShowAsync();
}
finally
{
OperationInProgress = false;
}
}
}