-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
286 lines (244 loc) · 11.4 KB
/
Copy pathApp.xaml.cs
File metadata and controls
286 lines (244 loc) · 11.4 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Coder.Desktop.App.Models;
using Coder.Desktop.App.Services;
using Coder.Desktop.App.ViewModels;
using Coder.Desktop.App.Views;
using Coder.Desktop.App.Views.Pages;
using Coder.Desktop.CoderSdk.Agent;
using Coder.Desktop.CoderSdk.Coder;
using Coder.Desktop.Vpn;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml;
using Microsoft.Win32;
using Microsoft.Windows.AppLifecycle;
using Microsoft.Windows.AppNotifications;
using Serilog;
using LaunchActivatedEventArgs = Microsoft.UI.Xaml.LaunchActivatedEventArgs;
namespace Coder.Desktop.App;
public partial class App : Application
{
private readonly IServiceProvider _services;
private bool _handleWindowClosed = true;
private const string MutagenControllerConfigSection = "MutagenController";
#if !DEBUG
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\App";
private const string logFilename = "app.log";
#else
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\DebugApp";
private const string logFilename = "debug-app.log";
#endif
private readonly ILogger<App> _logger;
private readonly IUriHandler _uriHandler;
private readonly ISettingsManager<CoderConnectSettings> _settingsManager;
private readonly IHostApplicationLifetime _appLifetime;
public App()
{
var builder = Host.CreateApplicationBuilder();
var configBuilder = builder.Configuration as IConfigurationBuilder;
// Add config in increasing order of precedence: first builtin defaults, then HKLM, finally HKCU
// so that the user's settings in the registry take precedence.
AddDefaultConfig(configBuilder);
configBuilder.Add(
new RegistryConfigurationSource(Registry.LocalMachine, ConfigSubKey));
configBuilder.Add(
new RegistryConfigurationSource(Registry.CurrentUser, ConfigSubKey));
var services = builder.Services;
// Logging
builder.Services.AddSerilog((_, loggerConfig) =>
{
loggerConfig.ReadFrom.Configuration(builder.Configuration);
});
services.AddSingleton<ICoderApiClientFactory, CoderApiClientFactory>();
services.AddSingleton<IAgentApiClientFactory, AgentApiClientFactory>();
services.AddSingleton<ICredentialBackend>(_ =>
new WindowsCredentialBackend(WindowsCredentialBackend.CoderCredentialsTargetName));
services.AddSingleton<ICredentialManager, CredentialManager>();
services.AddSingleton<IRpcController, RpcController>();
services.AddSingleton<IHostnameSuffixGetter, HostnameSuffixGetter>();
services.AddOptions<MutagenControllerConfig>()
.Bind(builder.Configuration.GetSection(MutagenControllerConfigSection));
services.AddSingleton<ISyncSessionController, MutagenController>();
services.AddSingleton<IUserNotifier, UserNotifier>();
services.AddSingleton<IRdpConnector, RdpConnector>();
services.AddSingleton<IUriHandler, UriHandler>();
// SignInWindow views and view models
services.AddTransient<SignInViewModel>();
services.AddTransient<SignInWindow>();
// FileSyncListWindow views and view models
services.AddTransient<FileSyncListViewModel>();
// FileSyncListMainPage is created by FileSyncListWindow.
services.AddTransient<FileSyncListWindow>();
services.AddSingleton<ISettingsManager<CoderConnectSettings>, SettingsManager<CoderConnectSettings>>();
services.AddSingleton<IStartupManager, StartupManager>();
// SettingsWindow views and view models
services.AddTransient<SettingsViewModel>();
// SettingsMainPage is created by SettingsWindow.
services.AddTransient<SettingsWindow>();
// DirectoryPickerWindow views and view models are created by FileSyncListViewModel.
// TrayWindow views and view models
services.AddTransient<TrayWindowLoadingPage>();
services.AddTransient<TrayWindowDisconnectedViewModel>();
services.AddTransient<TrayWindowDisconnectedPage>();
services.AddTransient<TrayWindowLoginRequiredViewModel>();
services.AddTransient<TrayWindowLoginRequiredPage>();
services.AddTransient<TrayWindowLoginRequiredViewModel>();
services.AddTransient<TrayWindowLoginRequiredPage>();
services.AddSingleton<IAgentAppViewModelFactory, AgentAppViewModelFactory>();
services.AddSingleton<IAgentViewModelFactory, AgentViewModelFactory>();
services.AddTransient<TrayWindowViewModel>();
services.AddTransient<TrayWindowMainPage>();
services.AddTransient<TrayWindow>();
_services = services.BuildServiceProvider();
_logger = _services.GetRequiredService<ILogger<App>>();
_uriHandler = _services.GetRequiredService<IUriHandler>();
_settingsManager = _services.GetRequiredService<ISettingsManager<CoderConnectSettings>>();
_appLifetime = _services.GetRequiredService<IHostApplicationLifetime>();
InitializeComponent();
}
public async Task ExitApplication()
{
_logger.LogDebug("exiting app");
_handleWindowClosed = false;
Exit();
var syncController = _services.GetRequiredService<ISyncSessionController>();
await syncController.DisposeAsync();
var rpcController = _services.GetRequiredService<IRpcController>();
// TODO: send a StopRequest if we're connected???
await rpcController.DisposeAsync();
Environment.Exit(0);
}
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
_logger.LogInformation("new instance launched");
_ = InitializeServicesAsync(_appLifetime.ApplicationStopping);
// Prevent the TrayWindow from closing, just hide it.
var trayWindow = _services.GetRequiredService<TrayWindow>();
trayWindow.Closed += (_, closedArgs) =>
{
if (!_handleWindowClosed) return;
closedArgs.Handled = true;
trayWindow.AppWindow.Hide();
};
}
/// <summary>
/// Loads stored VPN credentials, reconnects the RPC controller,
/// and (optionally) starts the VPN tunnel on application launch.
/// </summary>
private async Task InitializeServicesAsync(CancellationToken cancellationToken = default)
{
var credentialManager = _services.GetRequiredService<ICredentialManager>();
var rpcController = _services.GetRequiredService<IRpcController>();
using var credsCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
credsCts.CancelAfter(TimeSpan.FromSeconds(15));
var loadCredsTask = credentialManager.LoadCredentials(credsCts.Token);
var reconnectTask = rpcController.Reconnect(cancellationToken);
var settingsTask = _settingsManager.Read(cancellationToken);
var dependenciesLoaded = true;
try
{
await Task.WhenAll(loadCredsTask, reconnectTask, settingsTask);
}
catch (Exception)
{
if (loadCredsTask.IsFaulted)
_logger.LogError(loadCredsTask.Exception!.GetBaseException(),
"Failed to load credentials");
if (reconnectTask.IsFaulted)
_logger.LogError(reconnectTask.Exception!.GetBaseException(),
"Failed to connect to VPN service");
if (settingsTask.IsFaulted)
_logger.LogError(settingsTask.Exception!.GetBaseException(),
"Failed to fetch Coder Connect settings");
// Don't attempt to connect if we failed to load credentials or reconnect.
// This will prevent the app from trying to connect to the VPN service.
dependenciesLoaded = false;
}
var attemptCoderConnection = settingsTask.Result?.ConnectOnLaunch ?? false;
if (dependenciesLoaded && attemptCoderConnection)
{
try
{
await rpcController.StartVpn(cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to connect on launch");
}
}
// Initialize file sync.
var syncSessionCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var syncSessionController = _services.GetRequiredService<ISyncSessionController>();
try
{
await syncSessionController.RefreshState(syncSessionCts.Token);
}
catch (Exception ex)
{
_logger.LogError($"Failed to refresh sync session state {ex.Message}", ex);
}
}
public void OnActivated(object? sender, AppActivationArguments args)
{
switch (args.Kind)
{
case ExtendedActivationKind.Protocol:
var protoArgs = args.Data as IProtocolActivatedEventArgs;
if (protoArgs == null)
{
_logger.LogWarning("URI activation with null data");
return;
}
// don't need to wait for it to complete.
_uriHandler.HandleUri(protoArgs.Uri).ContinueWith(t =>
{
if (t.Exception != null)
{
// don't log query params, as they contain secrets.
_logger.LogError(t.Exception,
"unhandled exception while processing URI coder://{authority}{path}",
protoArgs.Uri.Authority, protoArgs.Uri.AbsolutePath);
}
});
break;
case ExtendedActivationKind.AppNotification:
var notificationArgs = (args.Data as AppNotificationActivatedEventArgs)!;
HandleNotification(null, notificationArgs);
break;
default:
_logger.LogWarning("activation for {kind}, which is unhandled", args.Kind);
break;
}
}
public void HandleNotification(AppNotificationManager? sender, AppNotificationActivatedEventArgs args)
{
// right now, we don't do anything other than log
_logger.LogInformation("handled notification activation");
}
private static void AddDefaultConfig(IConfigurationBuilder builder)
{
var logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CoderDesktop",
logFilename);
builder.AddInMemoryCollection(new Dictionary<string, string?>
{
[MutagenControllerConfigSection + ":MutagenExecutablePath"] = @"C:\mutagen.exe",
["Serilog:Using:0"] = "Serilog.Sinks.File",
["Serilog:MinimumLevel"] = "Information",
["Serilog:Enrich:0"] = "FromLogContext",
["Serilog:WriteTo:0:Name"] = "File",
["Serilog:WriteTo:0:Args:path"] = logPath,
["Serilog:WriteTo:0:Args:outputTemplate"] =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}",
["Serilog:WriteTo:0:Args:rollingInterval"] = "Day",
});
}
}