-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
295 lines (259 loc) · 12.2 KB
/
Copy pathApp.xaml.cs
File metadata and controls
295 lines (259 loc) · 12.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 NetSparkleUpdater.Interfaces;
using Serilog;
using LaunchActivatedEventArgs = Microsoft.UI.Xaml.LaunchActivatedEventArgs;
namespace Coder.Desktop.App;
public partial class App : Application
{
private const string MutagenControllerConfigSection = "MutagenController";
private const string UpdaterConfigSection = "Updater";
#if !DEBUG
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\App";
private const string LogFilename = "app.log";
private const string DefaultLogLevel = "Information";
#else
private const string ConfigSubKey = @"SOFTWARE\Coder Desktop\DebugApp";
private const string LogFilename = "debug-app.log";
private const string DefaultLogLevel = "Debug";
#endif
// HACK: This is exposed for dispatcher queue access. The notifier uses
// this to ensure action callbacks run in the UI thread (as
// activation events aren't in the main thread).
public TrayWindow? TrayWindow;
private readonly IServiceProvider _services;
private readonly ILogger<App> _logger;
private readonly IUriHandler _uriHandler;
private readonly IUserNotifier _userNotifier;
private bool _handleWindowClosed = true;
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,
// Block "Updater:" configuration from HKCU, so that updater
// settings can only be set at the HKLM level.
//
// HACK: This isn't super robust, but the security risk is
// minor anyway. Malicious apps running as the user could
// likely override this setting by altering the memory of
// this app.
UpdaterConfigSection + ":"));
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>();
services.AddOptions<UpdaterConfig>()
.Bind(builder.Configuration.GetSection(UpdaterConfigSection));
services.AddSingleton<IUpdaterUpdateAvailableViewModelFactory, UpdaterUpdateAvailableViewModelFactory>();
services.AddSingleton<IUIFactory, CoderSparkleUIFactory>();
services.AddSingleton<IUpdateController, SparkleUpdateController>();
// 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>();
// 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>();
_userNotifier = _services.GetRequiredService<IUserNotifier>();
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");
// Prevent the TrayWindow from closing, just hide it.
if (TrayWindow != null)
throw new InvalidOperationException("OnLaunched was called multiple times? TrayWindow is already set");
TrayWindow = _services.GetRequiredService<TrayWindow>();
TrayWindow.Closed += (_, closedArgs) =>
{
if (!_handleWindowClosed) return;
closedArgs.Handled = true;
TrayWindow.AppWindow.Hide();
};
// Start connecting to the manager in the background.
var rpcController = _services.GetRequiredService<IRpcController>();
if (rpcController.GetState().RpcLifecycle == RpcLifecycle.Disconnected)
// Passing in a CT with no cancellation is desired here, because
// the named pipe open will block until the pipe comes up.
_logger.LogDebug("reconnecting with VPN service");
_ = rpcController.Reconnect(CancellationToken.None).ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(t.Exception, "failed to connect to VPN service");
#if DEBUG
Debug.WriteLine(t.Exception);
Debugger.Break();
#endif
}
});
// Load the credentials in the background.
var credentialManagerCts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var credentialManager = _services.GetRequiredService<ICredentialManager>();
_ = credentialManager.LoadCredentials(credentialManagerCts.Token).ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(t.Exception, "failed to load credentials");
#if DEBUG
Debug.WriteLine(t.Exception);
Debugger.Break();
#endif
}
credentialManagerCts.Dispose();
}, CancellationToken.None);
// Initialize file sync.
// We're adding a 5s delay here to avoid race conditions when loading the mutagen binary.
_ = Task.Delay(5000).ContinueWith((_) =>
{
var syncSessionCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var syncSessionController = _services.GetRequiredService<ISyncSessionController>();
syncSessionController.RefreshState(syncSessionCts.Token).ContinueWith(
t =>
{
if (t.IsCanceled || t.Exception != null)
{
_logger.LogError(t.Exception, "failed to refresh sync state (canceled = {canceled})", t.IsCanceled);
}
syncSessionCts.Dispose();
}, CancellationToken.None);
});
}
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)
{
_logger.LogInformation("handled notification activation: {Argument}", args.Argument);
_userNotifier.HandleActivation(args);
}
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"] = DefaultLogLevel,
["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",
#if DEBUG
["Serilog:Using:1"] = "Serilog.Sinks.Debug",
["Serilog:Enrich:1"] = "FromLogContext",
["Serilog:WriteTo:1:Name"] = "Debug",
["Serilog:WriteTo:1:Args:outputTemplate"] =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}",
#endif
});
}
}