Revert "File scoped namespaces"

This reverts commit d31d8f574e.
This commit is contained in:
Burak Kaan Köse
2025-02-16 11:43:30 +01:00
parent d31d8f574e
commit cf9869b71e
617 changed files with 32097 additions and 31478 deletions

View File

@@ -20,246 +20,248 @@ using Wino.Server.Core;
using Wino.Server.MessageHandlers;
using Wino.Services;
namespace Wino.Server;
/// <summary>
/// Single instance Wino Server.
/// Instancing is done using Mutex.
/// App will not start if another instance is already running.
/// App will let running server know that server execution is triggered, which will
/// led server to start new connection to requesting UWP app.
/// </summary>
public partial class App : Application
namespace Wino.Server
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
private const string FRAME_WINDOW = "ApplicationFrameWindow";
public const string WinoMailLaunchProtocol = "wino.mail.launch";
public const string WinoCalendarLaunchProtocol = "wino.calendar.launch";
private const string NotifyIconResourceKey = "NotifyIcon";
private const string WinoMailServerAppName = "Wino.Mail.Server";
private const string WinoMailServerActivatedName = "Wino.Mail.Server.Activated";
private const string WinoCalendarServerAppName = "Wino.Calendar.Server";
private const string WinoCalendarServerActivatedName = "Wino.Calendar.Server.Activated";
public new static App Current => (App)Application.Current;
public WinoAppType WinoServerType { get; private set; }
private TaskbarIcon? notifyIcon;
private static Mutex _mutex = null;
private EventWaitHandle _eventWaitHandle;
public IServiceProvider Services { get; private set; }
private IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services.AddTransient<ServerContext>();
services.AddTransient<ServerViewModel>();
services.RegisterCoreServices();
services.RegisterSharedServices();
// Below services belongs to UWP.Core package and some APIs are not available for WPF.
// We register them here to avoid compilation errors.
services.AddSingleton<IConfigurationService, ConfigurationService>();
services.AddSingleton<INativeAppService, NativeAppService>();
services.AddSingleton<IPreferencesService, PreferencesService>();
services.AddTransient<INotificationBuilder, NotificationBuilder>();
services.AddTransient<IUnderlyingThemeService, UnderlyingThemeService>();
services.AddSingleton<IApplicationConfiguration, ApplicationConfiguration>();
// Register server message handler factory.
var serverMessageHandlerFactory = new ServerMessageHandlerFactory();
serverMessageHandlerFactory.Setup(services);
services.AddSingleton<IServerMessageHandlerFactory>(serverMessageHandlerFactory);
// Server type related services.
// TODO: Better abstraction.
if (WinoServerType == WinoAppType.Mail)
{
services.AddSingleton<IAuthenticatorConfig, MailAuthenticatorConfiguration>();
}
else
{
services.AddSingleton<IAuthenticatorConfig, CalendarAuthenticatorConfig>();
}
return services.BuildServiceProvider();
}
private async Task<ServerViewModel> InitializeNewServerAsync()
{
// Make sure app config is setup before anything else.
var applicationFolderConfiguration = Services.GetService<IApplicationConfiguration>();
applicationFolderConfiguration.ApplicationDataFolderPath = ApplicationData.Current.LocalFolder.Path;
applicationFolderConfiguration.PublisherSharedFolderPath = ApplicationData.Current.GetPublisherCacheFolder(ApplicationConfiguration.SharedFolderName).Path;
applicationFolderConfiguration.ApplicationTempFolderPath = ApplicationData.Current.TemporaryFolder.Path;
// Setup logger
var logInitializer = Services.GetService<ILogInitializer>();
var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, Constants.ServerLogFile);
logInitializer.SetupLogger(logFilePath);
// Make sure the database is ready.
var databaseService = Services.GetService<IDatabaseService>();
await databaseService.InitializeAsync();
// Setup core window handler for native app service.
// WPF app uses UWP app's window handle to display authentication dialog.
var nativeAppService = Services.GetService<INativeAppService>();
nativeAppService.GetCoreWindowHwnd = FindUWPClientWindowHandle;
// Initialize translations.
var translationService = Services.GetService<ITranslationService>();
await translationService.InitializeAsync();
// Make sure all accounts have synchronizers.
var synchronizerFactory = Services.GetService<ISynchronizerFactory>();
await synchronizerFactory.InitializeAsync();
// Load up the server view model.
var serverViewModel = Services.GetRequiredService<ServerViewModel>();
await serverViewModel.InitializeAsync();
return serverViewModel;
}
/// <summary>
/// OutlookAuthenticator for WAM requires window handle to display the dialog.
/// Since server app is windowless, we need to find the UWP app window handle.
/// Single instance Wino Server.
/// Instancing is done using Mutex.
/// App will not start if another instance is already running.
/// App will let running server know that server execution is triggered, which will
/// led server to start new connection to requesting UWP app.
/// </summary>
/// <param name="proc"></param>
/// <returns>Pointer to running UWP app's hwnd.</returns>
private IntPtr FindUWPClientWindowHandle()
public partial class App : Application
{
string processName = WinoServerType == WinoAppType.Mail ? "Wino.Mail" : "Wino.Calendar";
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
var processs = Process.GetProcesses();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
var proc = Process.GetProcessesByName(processName).FirstOrDefault() ?? throw new Exception($"{processName} client is not running.");
private const string FRAME_WINDOW = "ApplicationFrameWindow";
for (IntPtr appWindow = FindWindowEx(IntPtr.Zero, IntPtr.Zero, FRAME_WINDOW, null); appWindow != IntPtr.Zero;
appWindow = FindWindowEx(IntPtr.Zero, appWindow, FRAME_WINDOW, null))
public const string WinoMailLaunchProtocol = "wino.mail.launch";
public const string WinoCalendarLaunchProtocol = "wino.calendar.launch";
private const string NotifyIconResourceKey = "NotifyIcon";
private const string WinoMailServerAppName = "Wino.Mail.Server";
private const string WinoMailServerActivatedName = "Wino.Mail.Server.Activated";
private const string WinoCalendarServerAppName = "Wino.Calendar.Server";
private const string WinoCalendarServerActivatedName = "Wino.Calendar.Server.Activated";
public new static App Current => (App)Application.Current;
public WinoAppType WinoServerType { get; private set; }
private TaskbarIcon? notifyIcon;
private static Mutex _mutex = null;
private EventWaitHandle _eventWaitHandle;
public IServiceProvider Services { get; private set; }
private IServiceProvider ConfigureServices()
{
IntPtr coreWindow = FindWindowEx(appWindow, IntPtr.Zero, "Windows.UI.Core.CoreWindow", null);
if (coreWindow != IntPtr.Zero)
var services = new ServiceCollection();
services.AddTransient<ServerContext>();
services.AddTransient<ServerViewModel>();
services.RegisterCoreServices();
services.RegisterSharedServices();
// Below services belongs to UWP.Core package and some APIs are not available for WPF.
// We register them here to avoid compilation errors.
services.AddSingleton<IConfigurationService, ConfigurationService>();
services.AddSingleton<INativeAppService, NativeAppService>();
services.AddSingleton<IPreferencesService, PreferencesService>();
services.AddTransient<INotificationBuilder, NotificationBuilder>();
services.AddTransient<IUnderlyingThemeService, UnderlyingThemeService>();
services.AddSingleton<IApplicationConfiguration, ApplicationConfiguration>();
// Register server message handler factory.
var serverMessageHandlerFactory = new ServerMessageHandlerFactory();
serverMessageHandlerFactory.Setup(services);
services.AddSingleton<IServerMessageHandlerFactory>(serverMessageHandlerFactory);
// Server type related services.
// TODO: Better abstraction.
if (WinoServerType == WinoAppType.Mail)
{
GetWindowThreadProcessId(coreWindow, out var corePid);
if (corePid == proc.Id)
services.AddSingleton<IAuthenticatorConfig, MailAuthenticatorConfiguration>();
}
else
{
services.AddSingleton<IAuthenticatorConfig, CalendarAuthenticatorConfig>();
}
return services.BuildServiceProvider();
}
private async Task<ServerViewModel> InitializeNewServerAsync()
{
// Make sure app config is setup before anything else.
var applicationFolderConfiguration = Services.GetService<IApplicationConfiguration>();
applicationFolderConfiguration.ApplicationDataFolderPath = ApplicationData.Current.LocalFolder.Path;
applicationFolderConfiguration.PublisherSharedFolderPath = ApplicationData.Current.GetPublisherCacheFolder(ApplicationConfiguration.SharedFolderName).Path;
applicationFolderConfiguration.ApplicationTempFolderPath = ApplicationData.Current.TemporaryFolder.Path;
// Setup logger
var logInitializer = Services.GetService<ILogInitializer>();
var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, Constants.ServerLogFile);
logInitializer.SetupLogger(logFilePath);
// Make sure the database is ready.
var databaseService = Services.GetService<IDatabaseService>();
await databaseService.InitializeAsync();
// Setup core window handler for native app service.
// WPF app uses UWP app's window handle to display authentication dialog.
var nativeAppService = Services.GetService<INativeAppService>();
nativeAppService.GetCoreWindowHwnd = FindUWPClientWindowHandle;
// Initialize translations.
var translationService = Services.GetService<ITranslationService>();
await translationService.InitializeAsync();
// Make sure all accounts have synchronizers.
var synchronizerFactory = Services.GetService<ISynchronizerFactory>();
await synchronizerFactory.InitializeAsync();
// Load up the server view model.
var serverViewModel = Services.GetRequiredService<ServerViewModel>();
await serverViewModel.InitializeAsync();
return serverViewModel;
}
/// <summary>
/// OutlookAuthenticator for WAM requires window handle to display the dialog.
/// Since server app is windowless, we need to find the UWP app window handle.
/// </summary>
/// <param name="proc"></param>
/// <returns>Pointer to running UWP app's hwnd.</returns>
private IntPtr FindUWPClientWindowHandle()
{
string processName = WinoServerType == WinoAppType.Mail ? "Wino.Mail" : "Wino.Calendar";
var processs = Process.GetProcesses();
var proc = Process.GetProcessesByName(processName).FirstOrDefault() ?? throw new Exception($"{processName} client is not running.");
for (IntPtr appWindow = FindWindowEx(IntPtr.Zero, IntPtr.Zero, FRAME_WINDOW, null); appWindow != IntPtr.Zero;
appWindow = FindWindowEx(IntPtr.Zero, appWindow, FRAME_WINDOW, null))
{
IntPtr coreWindow = FindWindowEx(appWindow, IntPtr.Zero, "Windows.UI.Core.CoreWindow", null);
if (coreWindow != IntPtr.Zero)
{
return appWindow;
GetWindowThreadProcessId(coreWindow, out var corePid);
if (corePid == proc.Id)
{
return appWindow;
}
}
}
return IntPtr.Zero;
}
protected override async void OnStartup(StartupEventArgs e)
{
// Same server code runs for both Mail and Calendar.
string winoAppTypeParameter = e.Args.Length > 0 ? e.Args[e.Args.Length - 1] : "Mail";
WinoServerType = winoAppTypeParameter == "Mail" ? WinoAppType.Mail : WinoAppType.Calendar;
// TODO: Better abstraction.
string serverName = WinoServerType == WinoAppType.Mail ? WinoMailServerAppName : WinoCalendarServerAppName;
string serverActivatedName = WinoServerType == WinoAppType.Mail ? WinoMailServerActivatedName : WinoCalendarServerActivatedName;
_mutex = new Mutex(true, serverName, out bool isCreatedNew);
_eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, serverActivatedName);
if (isCreatedNew)
{
AppDomain.CurrentDomain.UnhandledException += ServerCrashed;
Application.Current.DispatcherUnhandledException += UIThreadCrash;
TaskScheduler.UnobservedTaskException += TaskCrashed;
// Ensure proper encodings are available for MimeKit
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Spawn a thread which will be waiting for our event
var thread = new Thread(() =>
{
while (_eventWaitHandle.WaitOne())
{
if (notifyIcon == null) return;
Current.Dispatcher.BeginInvoke(async () =>
{
if (notifyIcon.DataContext is ServerViewModel trayIconViewModel)
{
await trayIconViewModel.ReconnectAsync();
}
});
}
});
// It is important mark it as background otherwise it will prevent app from exiting.
thread.IsBackground = true;
thread.Start();
Services = ConfigureServices();
base.OnStartup(e);
var serverViewModel = await InitializeNewServerAsync();
// Create taskbar icon for the new server.
notifyIcon = (TaskbarIcon)FindResource(NotifyIconResourceKey);
notifyIcon.DataContext = serverViewModel;
notifyIcon.ForceCreate(enablesEfficiencyMode: true);
// Hide the icon if user has set it to invisible.
var preferencesService = Services.GetService<IPreferencesService>();
ChangeNotifyIconVisiblity(preferencesService.ServerTerminationBehavior != ServerBackgroundMode.Invisible);
}
else
{
// Notify other instance so it could reconnect to UWP app if needed.
_eventWaitHandle.Set();
// Terminate this instance.
Shutdown();
}
}
return IntPtr.Zero;
}
private void TaskCrashed(object sender, UnobservedTaskExceptionEventArgs e) => Log.Error(e.Exception, "Server task crashed.");
protected override async void OnStartup(StartupEventArgs e)
{
// Same server code runs for both Mail and Calendar.
private void UIThreadCrash(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) => Log.Error(e.Exception, "Server UI thread crashed.");
string winoAppTypeParameter = e.Args.Length > 0 ? e.Args[e.Args.Length - 1] : "Mail";
private void ServerCrashed(object sender, UnhandledExceptionEventArgs e) => Log.Error((Exception)e.ExceptionObject, "Server crashed.");
WinoServerType = winoAppTypeParameter == "Mail" ? WinoAppType.Mail : WinoAppType.Calendar;
// TODO: Better abstraction.
string serverName = WinoServerType == WinoAppType.Mail ? WinoMailServerAppName : WinoCalendarServerAppName;
string serverActivatedName = WinoServerType == WinoAppType.Mail ? WinoMailServerActivatedName : WinoCalendarServerActivatedName;
_mutex = new Mutex(true, serverName, out bool isCreatedNew);
_eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, serverActivatedName);
if (isCreatedNew)
protected override void OnExit(ExitEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += ServerCrashed;
Application.Current.DispatcherUnhandledException += UIThreadCrash;
TaskScheduler.UnobservedTaskException += TaskCrashed;
// Ensure proper encodings are available for MimeKit
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
notifyIcon?.Dispose();
base.OnExit(e);
}
// Spawn a thread which will be waiting for our event
var thread = new Thread(() =>
public void ChangeNotifyIconVisiblity(bool isVisible)
{
if (notifyIcon == null) return;
Current.Dispatcher.BeginInvoke(() =>
{
while (_eventWaitHandle.WaitOne())
{
if (notifyIcon == null) return;
Current.Dispatcher.BeginInvoke(async () =>
{
if (notifyIcon.DataContext is ServerViewModel trayIconViewModel)
{
await trayIconViewModel.ReconnectAsync();
}
});
}
notifyIcon.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
});
// It is important mark it as background otherwise it will prevent app from exiting.
thread.IsBackground = true;
thread.Start();
Services = ConfigureServices();
base.OnStartup(e);
var serverViewModel = await InitializeNewServerAsync();
// Create taskbar icon for the new server.
notifyIcon = (TaskbarIcon)FindResource(NotifyIconResourceKey);
notifyIcon.DataContext = serverViewModel;
notifyIcon.ForceCreate(enablesEfficiencyMode: true);
// Hide the icon if user has set it to invisible.
var preferencesService = Services.GetService<IPreferencesService>();
ChangeNotifyIconVisiblity(preferencesService.ServerTerminationBehavior != ServerBackgroundMode.Invisible);
}
else
{
// Notify other instance so it could reconnect to UWP app if needed.
_eventWaitHandle.Set();
// Terminate this instance.
Shutdown();
}
}
private void TaskCrashed(object sender, UnobservedTaskExceptionEventArgs e) => Log.Error(e.Exception, "Task crashed.");
private void UIThreadCrash(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) => Log.Error(e.Exception, "UI thread crashed.");
private void ServerCrashed(object sender, UnhandledExceptionEventArgs e) => Log.Error((Exception)e.ExceptionObject, "Server crashed.");
protected override void OnExit(ExitEventArgs e)
{
notifyIcon?.Dispose();
base.OnExit(e);
}
public void ChangeNotifyIconVisiblity(bool isVisible)
{
if (notifyIcon == null) return;
Current.Dispatcher.BeginInvoke(() =>
{
notifyIcon.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
});
}
}

View File

@@ -8,67 +8,68 @@ using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Server;
using Wino.Messaging;
namespace Wino.Server.Core;
public abstract class ServerMessageHandlerBase
namespace Wino.Server.Core
{
public string HandlingRequestType { get; }
public abstract Task ExecuteAsync(IClientMessage message, AppServiceRequest request = null, CancellationToken cancellationToken = default);
}
public abstract class ServerMessageHandler<TClientMessage, TResponse> : ServerMessageHandlerBase where TClientMessage : IClientMessage
{
/// <summary>
/// Response to return when server encounters and exception while executing code.
/// </summary>
/// <param name="ex">Exception that target threw.</param>
/// <returns>Default response on failure object.</returns>
public abstract WinoServerResponse<TResponse> FailureDefaultResponse(Exception ex);
/// <summary>
/// Safely executes the handler code and returns the response.
/// This call will never crash the server. Exceptions encountered will be handled and returned as response.
/// </summary>
/// <param name="message">IClientMessage that client asked the response for from the server.</param>
/// <param name="request">optional AppServiceRequest to return response for.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Response object that server executes for the given method.</returns>
public override async Task ExecuteAsync(IClientMessage message, AppServiceRequest request = null, CancellationToken cancellationToken = default)
public abstract class ServerMessageHandlerBase
{
WinoServerResponse<TResponse> response = default;
public string HandlingRequestType { get; }
try
{
response = await HandleAsync((TClientMessage)message, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
response = FailureDefaultResponse(ex);
}
finally
{
// No need to send response if request is null.
// Handler might've been called directly from the server itself.
if (request != null)
{
var valueSet = new ValueSet()
{
{ MessageConstants.MessageDataKey, JsonSerializer.Serialize(response) }
};
await request.SendResponseAsync(valueSet);
}
}
public abstract Task ExecuteAsync(IClientMessage message, AppServiceRequest request = null, CancellationToken cancellationToken = default);
}
/// <summary>
/// Code that will be executed directly on the server.
/// All handlers must implement this method.
/// Response is wrapped with WinoServerResponse.
/// </summary>
/// <param name="message">IClientMessage that client asked the response for from the server.</param>
/// <param name="cancellationToken">Cancellation token.</param>
protected abstract Task<WinoServerResponse<TResponse>> HandleAsync(TClientMessage message, CancellationToken cancellationToken = default);
public abstract class ServerMessageHandler<TClientMessage, TResponse> : ServerMessageHandlerBase where TClientMessage : IClientMessage
{
/// <summary>
/// Response to return when server encounters and exception while executing code.
/// </summary>
/// <param name="ex">Exception that target threw.</param>
/// <returns>Default response on failure object.</returns>
public abstract WinoServerResponse<TResponse> FailureDefaultResponse(Exception ex);
/// <summary>
/// Safely executes the handler code and returns the response.
/// This call will never crash the server. Exceptions encountered will be handled and returned as response.
/// </summary>
/// <param name="message">IClientMessage that client asked the response for from the server.</param>
/// <param name="request">optional AppServiceRequest to return response for.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Response object that server executes for the given method.</returns>
public override async Task ExecuteAsync(IClientMessage message, AppServiceRequest request = null, CancellationToken cancellationToken = default)
{
WinoServerResponse<TResponse> response = default;
try
{
response = await HandleAsync((TClientMessage)message, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
response = FailureDefaultResponse(ex);
}
finally
{
// No need to send response if request is null.
// Handler might've been called directly from the server itself.
if (request != null)
{
var valueSet = new ValueSet()
{
{ MessageConstants.MessageDataKey, JsonSerializer.Serialize(response) }
};
await request.SendResponseAsync(valueSet);
}
}
}
/// <summary>
/// Code that will be executed directly on the server.
/// All handlers must implement this method.
/// Response is wrapped with WinoServerResponse.
/// </summary>
/// <param name="message">IClientMessage that client asked the response for from the server.</param>
/// <param name="cancellationToken">Cancellation token.</param>
protected abstract Task<WinoServerResponse<TResponse>> HandleAsync(TClientMessage message, CancellationToken cancellationToken = default);
}
}

View File

@@ -5,41 +5,42 @@ using Wino.Core.Domain.Models.Synchronization;
using Wino.Messaging.Server;
using Wino.Server.MessageHandlers;
namespace Wino.Server.Core;
public class ServerMessageHandlerFactory : IServerMessageHandlerFactory
namespace Wino.Server.Core
{
public ServerMessageHandlerBase GetHandler(string typeName)
public class ServerMessageHandlerFactory : IServerMessageHandlerFactory
{
return typeName switch
public ServerMessageHandlerBase GetHandler(string typeName)
{
nameof(NewMailSynchronizationRequested) => App.Current.Services.GetService<MailSynchronizationRequestHandler>(),
nameof(NewCalendarSynchronizationRequested) => App.Current.Services.GetService<CalendarSynchronizationRequestHandler>(),
nameof(ServerRequestPackage) => App.Current.Services.GetService<UserActionRequestHandler>(),
nameof(DownloadMissingMessageRequested) => App.Current.Services.GetService<SingleMimeDownloadHandler>(),
nameof(AuthorizationRequested) => App.Current.Services.GetService<AuthenticationHandler>(),
nameof(SynchronizationExistenceCheckRequest) => App.Current.Services.GetService<SyncExistenceHandler>(),
nameof(ServerTerminationModeChanged) => App.Current.Services.GetService<ServerTerminationModeHandler>(),
nameof(TerminateServerRequested) => App.Current.Services.GetService<TerminateServerRequestHandler>(),
nameof(ImapConnectivityTestRequested) => App.Current.Services.GetService<ImapConnectivityTestHandler>(),
nameof(KillAccountSynchronizerRequested) => App.Current.Services.GetService<KillAccountSynchronizerHandler>(),
_ => throw new Exception($"Server handler for {typeName} is not registered."),
};
}
return typeName switch
{
nameof(NewMailSynchronizationRequested) => App.Current.Services.GetService<MailSynchronizationRequestHandler>(),
nameof(NewCalendarSynchronizationRequested) => App.Current.Services.GetService<CalendarSynchronizationRequestHandler>(),
nameof(ServerRequestPackage) => App.Current.Services.GetService<UserActionRequestHandler>(),
nameof(DownloadMissingMessageRequested) => App.Current.Services.GetService<SingleMimeDownloadHandler>(),
nameof(AuthorizationRequested) => App.Current.Services.GetService<AuthenticationHandler>(),
nameof(SynchronizationExistenceCheckRequest) => App.Current.Services.GetService<SyncExistenceHandler>(),
nameof(ServerTerminationModeChanged) => App.Current.Services.GetService<ServerTerminationModeHandler>(),
nameof(TerminateServerRequested) => App.Current.Services.GetService<TerminateServerRequestHandler>(),
nameof(ImapConnectivityTestRequested) => App.Current.Services.GetService<ImapConnectivityTestHandler>(),
nameof(KillAccountSynchronizerRequested) => App.Current.Services.GetService<KillAccountSynchronizerHandler>(),
_ => throw new Exception($"Server handler for {typeName} is not registered."),
};
}
public void Setup(IServiceCollection serviceCollection)
{
// Register all known handlers.
public void Setup(IServiceCollection serviceCollection)
{
// Register all known handlers.
serviceCollection.AddTransient<MailSynchronizationRequestHandler>();
serviceCollection.AddTransient<CalendarSynchronizationRequestHandler>();
serviceCollection.AddTransient<UserActionRequestHandler>();
serviceCollection.AddTransient<SingleMimeDownloadHandler>();
serviceCollection.AddTransient<AuthenticationHandler>();
serviceCollection.AddTransient<SyncExistenceHandler>();
serviceCollection.AddTransient<ServerTerminationModeHandler>();
serviceCollection.AddTransient<TerminateServerRequestHandler>();
serviceCollection.AddTransient<ImapConnectivityTestHandler>();
serviceCollection.AddTransient<KillAccountSynchronizerHandler>();
serviceCollection.AddTransient<MailSynchronizationRequestHandler>();
serviceCollection.AddTransient<CalendarSynchronizationRequestHandler>();
serviceCollection.AddTransient<UserActionRequestHandler>();
serviceCollection.AddTransient<SingleMimeDownloadHandler>();
serviceCollection.AddTransient<AuthenticationHandler>();
serviceCollection.AddTransient<SyncExistenceHandler>();
serviceCollection.AddTransient<ServerTerminationModeHandler>();
serviceCollection.AddTransient<TerminateServerRequestHandler>();
serviceCollection.AddTransient<ImapConnectivityTestHandler>();
serviceCollection.AddTransient<KillAccountSynchronizerHandler>();
}
}
}

View File

@@ -1,11 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public interface IServerMessageHandlerFactory
namespace Wino.Server.MessageHandlers
{
void Setup(IServiceCollection serviceCollection);
public interface IServerMessageHandlerFactory
{
void Setup(IServiceCollection serviceCollection);
ServerMessageHandlerBase GetHandler(string typeName);
ServerMessageHandlerBase GetHandler(string typeName);
}
}

View File

@@ -7,49 +7,50 @@ using Wino.Core.Domain.Models.Server;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class AuthenticationHandler : ServerMessageHandler<AuthorizationRequested, TokenInformationEx>
namespace Wino.Server.MessageHandlers
{
private readonly IAuthenticationProvider _authenticationProvider;
public override WinoServerResponse<TokenInformationEx> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<TokenInformationEx>.CreateErrorResponse(ex.Message);
public AuthenticationHandler(IAuthenticationProvider authenticationProvider)
public class AuthenticationHandler : ServerMessageHandler<AuthorizationRequested, TokenInformationEx>
{
_authenticationProvider = authenticationProvider;
}
private readonly IAuthenticationProvider _authenticationProvider;
protected override async Task<WinoServerResponse<TokenInformationEx>> HandleAsync(AuthorizationRequested message,
CancellationToken cancellationToken = default)
{
var authenticator = _authenticationProvider.GetAuthenticator(message.MailProviderType);
public override WinoServerResponse<TokenInformationEx> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<TokenInformationEx>.CreateErrorResponse(ex.Message);
// Some users are having issues with Gmail authentication.
// Their browsers may never launch to complete authentication.
// Offer to copy auth url for them to complete it manually.
// Redirection will occur to the app and the token will be saved.
if (message.ProposeCopyAuthorizationURL && authenticator is IGmailAuthenticator gmailAuthenticator)
public AuthenticationHandler(IAuthenticationProvider authenticationProvider)
{
gmailAuthenticator.ProposeCopyAuthURL = true;
_authenticationProvider = authenticationProvider;
}
TokenInformationEx generatedToken = null;
if (message.CreatedAccount != null)
protected override async Task<WinoServerResponse<TokenInformationEx>> HandleAsync(AuthorizationRequested message,
CancellationToken cancellationToken = default)
{
generatedToken = await authenticator.GetTokenInformationAsync(message.CreatedAccount);
}
else
{
// Initial authentication request.
// There is no account to get token for.
var authenticator = _authenticationProvider.GetAuthenticator(message.MailProviderType);
generatedToken = await authenticator.GenerateTokenInformationAsync(message.CreatedAccount);
}
// Some users are having issues with Gmail authentication.
// Their browsers may never launch to complete authentication.
// Offer to copy auth url for them to complete it manually.
// Redirection will occur to the app and the token will be saved.
return WinoServerResponse<TokenInformationEx>.CreateSuccessResponse(generatedToken);
if (message.ProposeCopyAuthorizationURL && authenticator is IGmailAuthenticator gmailAuthenticator)
{
gmailAuthenticator.ProposeCopyAuthURL = true;
}
TokenInformationEx generatedToken = null;
if (message.CreatedAccount != null)
{
generatedToken = await authenticator.GetTokenInformationAsync(message.CreatedAccount);
}
else
{
// Initial authentication request.
// There is no account to get token for.
generatedToken = await authenticator.GenerateTokenInformationAsync(message.CreatedAccount);
}
return WinoServerResponse<TokenInformationEx>.CreateSuccessResponse(generatedToken);
}
}
}

View File

@@ -7,33 +7,34 @@ using Wino.Core.Domain.Models.Synchronization;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class CalendarSynchronizationRequestHandler : ServerMessageHandler<NewCalendarSynchronizationRequested, CalendarSynchronizationResult>
namespace Wino.Server.MessageHandlers
{
public override WinoServerResponse<CalendarSynchronizationResult> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<CalendarSynchronizationResult>.CreateErrorResponse(ex.Message);
private readonly ISynchronizerFactory _synchronizerFactory;
public CalendarSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory)
public class CalendarSynchronizationRequestHandler : ServerMessageHandler<NewCalendarSynchronizationRequested, CalendarSynchronizationResult>
{
_synchronizerFactory = synchronizerFactory;
}
public override WinoServerResponse<CalendarSynchronizationResult> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<CalendarSynchronizationResult>.CreateErrorResponse(ex.Message);
protected override async Task<WinoServerResponse<CalendarSynchronizationResult>> HandleAsync(NewCalendarSynchronizationRequested message, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.Options.AccountId);
private readonly ISynchronizerFactory _synchronizerFactory;
try
public CalendarSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory)
{
var synchronizationResult = await synchronizer.SynchronizeCalendarEventsAsync(message.Options, cancellationToken);
return WinoServerResponse<CalendarSynchronizationResult>.CreateSuccessResponse(synchronizationResult);
_synchronizerFactory = synchronizerFactory;
}
catch (Exception ex)
protected override async Task<WinoServerResponse<CalendarSynchronizationResult>> HandleAsync(NewCalendarSynchronizationRequested message, CancellationToken cancellationToken = default)
{
throw;
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.Options.AccountId);
try
{
var synchronizationResult = await synchronizer.SynchronizeCalendarEventsAsync(message.Options, cancellationToken);
return WinoServerResponse<CalendarSynchronizationResult>.CreateSuccessResponse(synchronizationResult);
}
catch (Exception ex)
{
throw;
}
}
}
}

View File

@@ -8,42 +8,43 @@ using Wino.Core.Domain.Models.Server;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class ImapConnectivityTestHandler : ServerMessageHandler<ImapConnectivityTestRequested, ImapConnectivityTestResults>
namespace Wino.Server.MessageHandlers
{
private readonly IImapTestService _imapTestService;
public override WinoServerResponse<ImapConnectivityTestResults> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<ImapConnectivityTestResults>.CreateErrorResponse(ex.Message);
public ImapConnectivityTestHandler(IImapTestService imapTestService)
public class ImapConnectivityTestHandler : ServerMessageHandler<ImapConnectivityTestRequested, ImapConnectivityTestResults>
{
_imapTestService = imapTestService;
}
private readonly IImapTestService _imapTestService;
protected override async Task<WinoServerResponse<ImapConnectivityTestResults>> HandleAsync(ImapConnectivityTestRequested message, CancellationToken cancellationToken = default)
{
try
{
await _imapTestService.TestImapConnectionAsync(message.ServerInformation, message.IsSSLHandshakeAllowed);
public override WinoServerResponse<ImapConnectivityTestResults> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<ImapConnectivityTestResults>.CreateErrorResponse(ex.Message);
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Success());
}
catch (ImapTestSSLCertificateException sslTestException)
public ImapConnectivityTestHandler(IImapTestService imapTestService)
{
// User must confirm to continue ignoring the SSL certificate.
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.CertificateUIRequired(sslTestException.Issuer, sslTestException.ExpirationDateString, sslTestException.ValidFromDateString));
_imapTestService = imapTestService;
}
catch (ImapClientPoolException clientPoolException)
protected override async Task<WinoServerResponse<ImapConnectivityTestResults>> HandleAsync(ImapConnectivityTestRequested message, CancellationToken cancellationToken = default)
{
// Connectivity failed with protocol log.
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Failure(clientPoolException, clientPoolException.ProtocolLog));
}
catch (Exception exception)
{
// Unknown error
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Failure(exception, string.Empty));
try
{
await _imapTestService.TestImapConnectionAsync(message.ServerInformation, message.IsSSLHandshakeAllowed);
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Success());
}
catch (ImapTestSSLCertificateException sslTestException)
{
// User must confirm to continue ignoring the SSL certificate.
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.CertificateUIRequired(sslTestException.Issuer, sslTestException.ExpirationDateString, sslTestException.ValidFromDateString));
}
catch (ImapClientPoolException clientPoolException)
{
// Connectivity failed with protocol log.
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Failure(clientPoolException, clientPoolException.ProtocolLog));
}
catch (Exception exception)
{
// Unknown error
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Failure(exception, string.Empty));
}
}
}
}

View File

@@ -6,24 +6,25 @@ using Wino.Core.Domain.Models.Server;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class KillAccountSynchronizerHandler : ServerMessageHandler<KillAccountSynchronizerRequested, bool>
namespace Wino.Server.MessageHandlers
{
private readonly ISynchronizerFactory _synchronizerFactory;
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
public KillAccountSynchronizerHandler(ISynchronizerFactory synchronizerFactory)
public class KillAccountSynchronizerHandler : ServerMessageHandler<KillAccountSynchronizerRequested, bool>
{
_synchronizerFactory = synchronizerFactory;
}
private readonly ISynchronizerFactory _synchronizerFactory;
protected override async Task<WinoServerResponse<bool>> HandleAsync(KillAccountSynchronizerRequested message, CancellationToken cancellationToken = default)
{
await _synchronizerFactory.DeleteSynchronizerAsync(message.AccountId);
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
return WinoServerResponse<bool>.CreateSuccessResponse(true);
public KillAccountSynchronizerHandler(ISynchronizerFactory synchronizerFactory)
{
_synchronizerFactory = synchronizerFactory;
}
protected override async Task<WinoServerResponse<bool>> HandleAsync(KillAccountSynchronizerRequested message, CancellationToken cancellationToken = default)
{
await _synchronizerFactory.DeleteSynchronizerAsync(message.AccountId);
return WinoServerResponse<bool>.CreateSuccessResponse(true);
}
}
}

View File

@@ -11,98 +11,99 @@ using Wino.Messaging.Server;
using Wino.Messaging.UI;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
/// <summary>
/// Handler for NewMailSynchronizationRequested from the client.
/// </summary>
public class MailSynchronizationRequestHandler : ServerMessageHandler<NewMailSynchronizationRequested, MailSynchronizationResult>
namespace Wino.Server.MessageHandlers
{
public override WinoServerResponse<MailSynchronizationResult> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<MailSynchronizationResult>.CreateErrorResponse(ex.Message);
private readonly ISynchronizerFactory _synchronizerFactory;
private readonly INotificationBuilder _notificationBuilder;
private readonly IFolderService _folderService;
public MailSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory,
INotificationBuilder notificationBuilder,
IFolderService folderService)
/// <summary>
/// Handler for NewMailSynchronizationRequested from the client.
/// </summary>
public class MailSynchronizationRequestHandler : ServerMessageHandler<NewMailSynchronizationRequested, MailSynchronizationResult>
{
_synchronizerFactory = synchronizerFactory;
_notificationBuilder = notificationBuilder;
_folderService = folderService;
}
public override WinoServerResponse<MailSynchronizationResult> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<MailSynchronizationResult>.CreateErrorResponse(ex.Message);
protected override async Task<WinoServerResponse<MailSynchronizationResult>> HandleAsync(NewMailSynchronizationRequested message, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.Options.AccountId);
private readonly ISynchronizerFactory _synchronizerFactory;
private readonly INotificationBuilder _notificationBuilder;
private readonly IFolderService _folderService;
// 1. Don't send message for sync completion when we execute requests.
// People are usually interested in seeing the notification after they trigger the synchronization.
// 2. Don't send message for sync completion when we are synchronizing from the server.
// It happens very common and there is no need to send a message for each synchronization.
bool shouldReportSynchronizationResult =
message.Options.Type != MailSynchronizationType.ExecuteRequests &&
message.Options.Type != MailSynchronizationType.IMAPIdle &&
message.Source == SynchronizationSource.Client;
try
public MailSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory,
INotificationBuilder notificationBuilder,
IFolderService folderService)
{
var synchronizationResult = await synchronizer.SynchronizeMailsAsync(message.Options, cancellationToken).ConfigureAwait(false);
if (synchronizationResult.DownloadedMessages?.Any() ?? false || !synchronizer.Account.Preferences.IsNotificationsEnabled)
{
var accountInboxFolder = await _folderService.GetSpecialFolderByAccountIdAsync(message.Options.AccountId, SpecialFolderType.Inbox);
if (accountInboxFolder != null)
{
await _notificationBuilder.CreateNotificationsAsync(accountInboxFolder.Id, synchronizationResult.DownloadedMessages);
}
}
var isSynchronizationSucceeded = synchronizationResult.CompletedState == SynchronizationCompletedState.Success;
// IDLE requests might be canceled successfully.
if (message.Options.Type == MailSynchronizationType.IMAPIdle && synchronizationResult.CompletedState == SynchronizationCompletedState.Canceled)
{
isSynchronizationSucceeded = true;
}
// Update badge count of the notification task.
if (isSynchronizationSucceeded)
{
await _notificationBuilder.UpdateTaskbarIconBadgeAsync();
}
if (shouldReportSynchronizationResult)
{
var completedMessage = new AccountSynchronizationCompleted(message.Options.AccountId,
isSynchronizationSucceeded ? SynchronizationCompletedState.Success : SynchronizationCompletedState.Failed,
message.Options.GroupedSynchronizationTrackingId);
WeakReferenceMessenger.Default.Send(completedMessage);
}
return WinoServerResponse<MailSynchronizationResult>.CreateSuccessResponse(synchronizationResult);
_synchronizerFactory = synchronizerFactory;
_notificationBuilder = notificationBuilder;
_folderService = folderService;
}
// TODO: Following cases might always be thrown from server. Handle them properly.
//catch (AuthenticationAttentionException)
//{
// // TODO
// // await SetAccountAttentionAsync(accountId, AccountAttentionReason.InvalidCredentials);
//}
//catch (SystemFolderConfigurationMissingException)
//{
// // TODO
// // await SetAccountAttentionAsync(accountId, AccountAttentionReason.MissingSystemFolderConfiguration);
//}
catch (Exception)
protected override async Task<WinoServerResponse<MailSynchronizationResult>> HandleAsync(NewMailSynchronizationRequested message, CancellationToken cancellationToken = default)
{
throw;
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.Options.AccountId);
// 1. Don't send message for sync completion when we execute requests.
// People are usually interested in seeing the notification after they trigger the synchronization.
// 2. Don't send message for sync completion when we are synchronizing from the server.
// It happens very common and there is no need to send a message for each synchronization.
bool shouldReportSynchronizationResult =
message.Options.Type != MailSynchronizationType.ExecuteRequests &&
message.Options.Type != MailSynchronizationType.IMAPIdle &&
message.Source == SynchronizationSource.Client;
try
{
var synchronizationResult = await synchronizer.SynchronizeMailsAsync(message.Options, cancellationToken).ConfigureAwait(false);
if (synchronizationResult.DownloadedMessages?.Any() ?? false || !synchronizer.Account.Preferences.IsNotificationsEnabled)
{
var accountInboxFolder = await _folderService.GetSpecialFolderByAccountIdAsync(message.Options.AccountId, SpecialFolderType.Inbox);
if (accountInboxFolder != null)
{
await _notificationBuilder.CreateNotificationsAsync(accountInboxFolder.Id, synchronizationResult.DownloadedMessages);
}
}
var isSynchronizationSucceeded = synchronizationResult.CompletedState == SynchronizationCompletedState.Success;
// IDLE requests might be canceled successfully.
if (message.Options.Type == MailSynchronizationType.IMAPIdle && synchronizationResult.CompletedState == SynchronizationCompletedState.Canceled)
{
isSynchronizationSucceeded = true;
}
// Update badge count of the notification task.
if (isSynchronizationSucceeded)
{
await _notificationBuilder.UpdateTaskbarIconBadgeAsync();
}
if (shouldReportSynchronizationResult)
{
var completedMessage = new AccountSynchronizationCompleted(message.Options.AccountId,
isSynchronizationSucceeded ? SynchronizationCompletedState.Success : SynchronizationCompletedState.Failed,
message.Options.GroupedSynchronizationTrackingId);
WeakReferenceMessenger.Default.Send(completedMessage);
}
return WinoServerResponse<MailSynchronizationResult>.CreateSuccessResponse(synchronizationResult);
}
// TODO: Following cases might always be thrown from server. Handle them properly.
//catch (AuthenticationAttentionException)
//{
// // TODO
// // await SetAccountAttentionAsync(accountId, AccountAttentionReason.InvalidCredentials);
//}
//catch (SystemFolderConfigurationMissingException)
//{
// // TODO
// // await SetAccountAttentionAsync(accountId, AccountAttentionReason.MissingSystemFolderConfiguration);
//}
catch (Exception)
{
throw;
}
}
}
}

View File

@@ -6,16 +6,17 @@ using Wino.Core.Domain.Models.Server;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class ServerTerminationModeHandler : ServerMessageHandler<ServerTerminationModeChanged, bool>
namespace Wino.Server.MessageHandlers
{
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
protected override Task<WinoServerResponse<bool>> HandleAsync(ServerTerminationModeChanged message, CancellationToken cancellationToken = default)
public class ServerTerminationModeHandler : ServerMessageHandler<ServerTerminationModeChanged, bool>
{
WeakReferenceMessenger.Default.Send(message);
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
protected override Task<WinoServerResponse<bool>> HandleAsync(ServerTerminationModeChanged message, CancellationToken cancellationToken = default)
{
WeakReferenceMessenger.Default.Send(message);
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
}
}
}

View File

@@ -6,25 +6,26 @@ using Wino.Core.Domain.Models.Server;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class SingleMimeDownloadHandler : ServerMessageHandler<DownloadMissingMessageRequested, bool>
namespace Wino.Server.MessageHandlers
{
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
private readonly ISynchronizerFactory _synchronizerFactory;
public SingleMimeDownloadHandler(ISynchronizerFactory synchronizerFactory)
public class SingleMimeDownloadHandler : ServerMessageHandler<DownloadMissingMessageRequested, bool>
{
_synchronizerFactory = synchronizerFactory;
}
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
protected override async Task<WinoServerResponse<bool>> HandleAsync(DownloadMissingMessageRequested message, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
private readonly ISynchronizerFactory _synchronizerFactory;
public SingleMimeDownloadHandler(ISynchronizerFactory synchronizerFactory)
{
_synchronizerFactory = synchronizerFactory;
}
// TODO: ITransferProgress support is lost.
await synchronizer.DownloadMissingMimeMessageAsync(message.MailItem, null, cancellationToken);
protected override async Task<WinoServerResponse<bool>> HandleAsync(DownloadMissingMessageRequested message, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
return WinoServerResponse<bool>.CreateSuccessResponse(true);
// TODO: ITransferProgress support is lost.
await synchronizer.DownloadMissingMimeMessageAsync(message.MailItem, null, cancellationToken);
return WinoServerResponse<bool>.CreateSuccessResponse(true);
}
}
}

View File

@@ -6,24 +6,25 @@ using Wino.Core.Domain.Models.Server;
using Wino.Core.Domain.Models.Synchronization;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class SyncExistenceHandler : ServerMessageHandler<SynchronizationExistenceCheckRequest, bool>
namespace Wino.Server.MessageHandlers
{
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
private readonly ISynchronizerFactory _synchronizerFactory;
public SyncExistenceHandler(ISynchronizerFactory synchronizerFactory)
public class SyncExistenceHandler : ServerMessageHandler<SynchronizationExistenceCheckRequest, bool>
{
_synchronizerFactory = synchronizerFactory;
}
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
protected override async Task<WinoServerResponse<bool>> HandleAsync(SynchronizationExistenceCheckRequest message, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
private readonly ISynchronizerFactory _synchronizerFactory;
return WinoServerResponse<bool>.CreateSuccessResponse(synchronizer.State != Wino.Core.Domain.Enums.AccountSynchronizerState.Idle);
public SyncExistenceHandler(ISynchronizerFactory synchronizerFactory)
{
_synchronizerFactory = synchronizerFactory;
}
protected override async Task<WinoServerResponse<bool>> HandleAsync(SynchronizationExistenceCheckRequest message, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
return WinoServerResponse<bool>.CreateSuccessResponse(synchronizer.State != Wino.Core.Domain.Enums.AccountSynchronizerState.Idle);
}
}
}

View File

@@ -6,20 +6,21 @@ using Wino.Core.Domain.Models.Server;
using Wino.Messaging.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class TerminateServerRequestHandler : ServerMessageHandler<TerminateServerRequested, bool>
namespace Wino.Server.MessageHandlers
{
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
protected override Task<WinoServerResponse<bool>> HandleAsync(TerminateServerRequested message, CancellationToken cancellationToken = default)
public class TerminateServerRequestHandler : ServerMessageHandler<TerminateServerRequested, bool>
{
// This handler is only doing the logging right now.
// Client will always expect success response.
// Server will be terminated in the server context once the client gets the response.
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
Log.Information("Terminate server is requested by client. Killing server.");
protected override Task<WinoServerResponse<bool>> HandleAsync(TerminateServerRequested message, CancellationToken cancellationToken = default)
{
// This handler is only doing the logging right now.
// Client will always expect success response.
// Server will be terminated in the server context once the client gets the response.
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
Log.Information("Terminate server is requested by client. Killing server.");
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
}
}
}

View File

@@ -6,35 +6,36 @@ using Wino.Core.Domain.Models.Requests;
using Wino.Core.Domain.Models.Server;
using Wino.Server.Core;
namespace Wino.Server.MessageHandlers;
public class UserActionRequestHandler : ServerMessageHandler<ServerRequestPackage, bool>
namespace Wino.Server.MessageHandlers
{
private readonly ISynchronizerFactory _synchronizerFactory;
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
public UserActionRequestHandler(ISynchronizerFactory synchronizerFactory)
public class UserActionRequestHandler : ServerMessageHandler<ServerRequestPackage, bool>
{
_synchronizerFactory = synchronizerFactory;
}
private readonly ISynchronizerFactory _synchronizerFactory;
protected override async Task<WinoServerResponse<bool>> HandleAsync(ServerRequestPackage package, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(package.AccountId);
synchronizer.QueueRequest(package.Request);
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
//if (package.QueueSynchronization)
//{
// var options = new SynchronizationOptions
// {
// AccountId = package.AccountId,
// Type = Wino.Core.Domain.Enums.SynchronizationType.ExecuteRequests
// };
public UserActionRequestHandler(ISynchronizerFactory synchronizerFactory)
{
_synchronizerFactory = synchronizerFactory;
}
// WeakReferenceMessenger.Default.Send(new NewSynchronizationRequested(options));
//}
protected override async Task<WinoServerResponse<bool>> HandleAsync(ServerRequestPackage package, CancellationToken cancellationToken = default)
{
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(package.AccountId);
synchronizer.QueueRequest(package.Request);
return WinoServerResponse<bool>.CreateSuccessResponse(true);
//if (package.QueueSynchronization)
//{
// var options = new SynchronizationOptions
// {
// AccountId = package.AccountId,
// Type = Wino.Core.Domain.Enums.SynchronizationType.ExecuteRequests
// };
// WeakReferenceMessenger.Default.Send(new NewSynchronizationRequested(options));
//}
return WinoServerResponse<bool>.CreateSuccessResponse(true);
}
}
}

View File

@@ -20,362 +20,363 @@ using Wino.Messaging.UI;
using Wino.Server.MessageHandlers;
using Wino.Services;
namespace Wino.Server;
public class ServerContext :
IRecipient<AccountCreatedMessage>,
IRecipient<AccountUpdatedMessage>,
IRecipient<AccountRemovedMessage>,
IRecipient<DraftCreated>,
IRecipient<DraftFailed>,
IRecipient<DraftMapped>,
IRecipient<FolderRenamed>,
IRecipient<FolderSynchronizationEnabled>,
IRecipient<MailAddedMessage>,
IRecipient<MailDownloadedMessage>,
IRecipient<MailRemovedMessage>,
IRecipient<MailUpdatedMessage>,
IRecipient<MergedInboxRenamed>,
IRecipient<AccountSynchronizationCompleted>,
IRecipient<AccountSynchronizerStateChanged>,
IRecipient<RefreshUnreadCountsMessage>,
IRecipient<ServerTerminationModeChanged>,
IRecipient<AccountSynchronizationProgressUpdatedMessage>,
IRecipient<AccountFolderConfigurationUpdated>,
IRecipient<CopyAuthURLRequested>,
IRecipient<NewMailSynchronizationRequested>
namespace Wino.Server
{
private readonly System.Timers.Timer _timer;
private static object connectionLock = new object();
private AppServiceConnection connection = null;
private readonly IDatabaseService _databaseService;
private readonly IApplicationConfiguration _applicationFolderConfiguration;
private readonly ISynchronizerFactory _synchronizerFactory;
private readonly IServerMessageHandlerFactory _serverMessageHandlerFactory;
private readonly IAccountService _accountService;
private readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions
public class ServerContext :
IRecipient<AccountCreatedMessage>,
IRecipient<AccountUpdatedMessage>,
IRecipient<AccountRemovedMessage>,
IRecipient<DraftCreated>,
IRecipient<DraftFailed>,
IRecipient<DraftMapped>,
IRecipient<FolderRenamed>,
IRecipient<FolderSynchronizationEnabled>,
IRecipient<MailAddedMessage>,
IRecipient<MailDownloadedMessage>,
IRecipient<MailRemovedMessage>,
IRecipient<MailUpdatedMessage>,
IRecipient<MergedInboxRenamed>,
IRecipient<AccountSynchronizationCompleted>,
IRecipient<AccountSynchronizerStateChanged>,
IRecipient<RefreshUnreadCountsMessage>,
IRecipient<ServerTerminationModeChanged>,
IRecipient<AccountSynchronizationProgressUpdatedMessage>,
IRecipient<AccountFolderConfigurationUpdated>,
IRecipient<CopyAuthURLRequested>,
IRecipient<NewMailSynchronizationRequested>
{
TypeInfoResolver = new ServerRequestTypeInfoResolver()
};
private readonly System.Timers.Timer _timer;
private static object connectionLock = new object();
public ServerContext(IDatabaseService databaseService,
IApplicationConfiguration applicationFolderConfiguration,
ISynchronizerFactory synchronizerFactory,
IServerMessageHandlerFactory serverMessageHandlerFactory,
IAccountService accountService)
{
// Setup timer for synchronization.
private AppServiceConnection connection = null;
_timer = new System.Timers.Timer(1000 * 60 * 3); // 1 minute
_timer.Elapsed += SynchronizationTimerTriggered;
_databaseService = databaseService;
_applicationFolderConfiguration = applicationFolderConfiguration;
_synchronizerFactory = synchronizerFactory;
_serverMessageHandlerFactory = serverMessageHandlerFactory;
_accountService = accountService;
WeakReferenceMessenger.Default.RegisterAll(this);
_timer.Start();
}
private async void SynchronizationTimerTriggered(object sender, System.Timers.ElapsedEventArgs e)
{
// Send sync request for all accounts.
var accounts = await _accountService.GetAccountsAsync();
foreach (var account in accounts)
private readonly IDatabaseService _databaseService;
private readonly IApplicationConfiguration _applicationFolderConfiguration;
private readonly ISynchronizerFactory _synchronizerFactory;
private readonly IServerMessageHandlerFactory _serverMessageHandlerFactory;
private readonly IAccountService _accountService;
private readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions
{
var options = new MailSynchronizationOptions
{
AccountId = account.Id,
Type = MailSynchronizationType.InboxOnly,
};
var request = new NewMailSynchronizationRequested(options, SynchronizationSource.Server);
await ExecuteServerMessageSafeAsync(null, request);
}
}
#region Message Handlers
public async void Receive(MailAddedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountCreatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountUpdatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountRemovedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(DraftCreated message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(DraftFailed message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(DraftMapped message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(FolderRenamed message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(FolderSynchronizationEnabled message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MailDownloadedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MailRemovedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MailUpdatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MergedInboxRenamed message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountSynchronizationCompleted message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(RefreshUnreadCountsMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountSynchronizerStateChanged message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountSynchronizationProgressUpdatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountFolderConfigurationUpdated message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(CopyAuthURLRequested message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(NewMailSynchronizationRequested message) => await SendMessageAsync(MessageType.UIMessage, message);
#endregion
private string GetAppPackagFamilyName()
{
// If running as a standalone app, Package will throw exception.
// Return hardcoded value for debugging purposes.
// Connection will not be available in this case.
try
{
return Package.Current.Id.FamilyName;
}
catch (Exception)
{
return "Debug.Wino.Server.FamilyName";
}
}
/// <summary>
/// Open connection to UWP app service
/// </summary>
public async Task InitializeAppServiceConnectionAsync()
{
if (connection != null) DisposeConnection();
connection = new AppServiceConnection
{
AppServiceName = "WinoInteropService",
PackageFamilyName = GetAppPackagFamilyName()
TypeInfoResolver = new ServerRequestTypeInfoResolver()
};
connection.RequestReceived += OnWinRTMessageReceived;
connection.ServiceClosed += OnConnectionClosed;
AppServiceConnectionStatus status = await connection.OpenAsync();
if (status != AppServiceConnectionStatus.Success)
public ServerContext(IDatabaseService databaseService,
IApplicationConfiguration applicationFolderConfiguration,
ISynchronizerFactory synchronizerFactory,
IServerMessageHandlerFactory serverMessageHandlerFactory,
IAccountService accountService)
{
Log.Error("Opening server connection failed. Status: {status}", status);
// Setup timer for synchronization.
DisposeConnection();
_timer = new System.Timers.Timer(1000 * 60 * 3); // 1 minute
_timer.Elapsed += SynchronizationTimerTriggered;
_databaseService = databaseService;
_applicationFolderConfiguration = applicationFolderConfiguration;
_synchronizerFactory = synchronizerFactory;
_serverMessageHandlerFactory = serverMessageHandlerFactory;
_accountService = accountService;
WeakReferenceMessenger.Default.RegisterAll(this);
_timer.Start();
}
}
/// <summary>
/// Disposes current connection to UWP app service.
/// </summary>
private void DisposeConnection()
{
lock (connectionLock)
private async void SynchronizationTimerTriggered(object sender, System.Timers.ElapsedEventArgs e)
{
// Send sync request for all accounts.
var accounts = await _accountService.GetAccountsAsync();
foreach (var account in accounts)
{
var options = new MailSynchronizationOptions
{
AccountId = account.Id,
Type = MailSynchronizationType.InboxOnly,
};
var request = new NewMailSynchronizationRequested(options, SynchronizationSource.Server);
await ExecuteServerMessageSafeAsync(null, request);
}
}
#region Message Handlers
public async void Receive(MailAddedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountCreatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountUpdatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountRemovedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(DraftCreated message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(DraftFailed message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(DraftMapped message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(FolderRenamed message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(FolderSynchronizationEnabled message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MailDownloadedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MailRemovedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MailUpdatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(MergedInboxRenamed message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountSynchronizationCompleted message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(RefreshUnreadCountsMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountSynchronizerStateChanged message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountSynchronizationProgressUpdatedMessage message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(AccountFolderConfigurationUpdated message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(CopyAuthURLRequested message) => await SendMessageAsync(MessageType.UIMessage, message);
public async void Receive(NewMailSynchronizationRequested message) => await SendMessageAsync(MessageType.UIMessage, message);
#endregion
private string GetAppPackagFamilyName()
{
// If running as a standalone app, Package will throw exception.
// Return hardcoded value for debugging purposes.
// Connection will not be available in this case.
try
{
return Package.Current.Id.FamilyName;
}
catch (Exception)
{
return "Debug.Wino.Server.FamilyName";
}
}
/// <summary>
/// Open connection to UWP app service
/// </summary>
public async Task InitializeAppServiceConnectionAsync()
{
if (connection != null) DisposeConnection();
connection = new AppServiceConnection
{
AppServiceName = "WinoInteropService",
PackageFamilyName = GetAppPackagFamilyName()
};
connection.RequestReceived += OnWinRTMessageReceived;
connection.ServiceClosed += OnConnectionClosed;
AppServiceConnectionStatus status = await connection.OpenAsync();
if (status != AppServiceConnectionStatus.Success)
{
Log.Error("Opening server connection failed. Status: {status}", status);
DisposeConnection();
}
}
/// <summary>
/// Disposes current connection to UWP app service.
/// </summary>
private void DisposeConnection()
{
lock (connectionLock)
{
if (connection == null) return;
connection.RequestReceived -= OnWinRTMessageReceived;
connection.ServiceClosed -= OnConnectionClosed;
connection.Dispose();
connection = null;
}
}
/// <summary>
/// Sends a serialized object to UWP application if connection exists with given type.
/// </summary>
/// <param name="messageType">Type of the message.</param>
/// <param name="message">IServerMessage object that will be serialized.</param>
/// <returns></returns>
/// <exception cref="ArgumentException">When the message is not IServerMessage.</exception>
private async Task SendMessageAsync(MessageType messageType, object message)
{
if (connection == null) return;
connection.RequestReceived -= OnWinRTMessageReceived;
connection.ServiceClosed -= OnConnectionClosed;
if (message is not IUIMessage serverMessage)
throw new ArgumentException("Server message must be a type of IUIMessage");
connection.Dispose();
connection = null;
}
}
string json = JsonSerializer.Serialize(message);
/// <summary>
/// Sends a serialized object to UWP application if connection exists with given type.
/// </summary>
/// <param name="messageType">Type of the message.</param>
/// <param name="message">IServerMessage object that will be serialized.</param>
/// <returns></returns>
/// <exception cref="ArgumentException">When the message is not IServerMessage.</exception>
private async Task SendMessageAsync(MessageType messageType, object message)
{
if (connection == null) return;
if (message is not IUIMessage serverMessage)
throw new ArgumentException("Server message must be a type of IUIMessage");
string json = JsonSerializer.Serialize(message);
var set = new ValueSet
{
{ MessageConstants.MessageTypeKey, (int)messageType },
{ MessageConstants.MessageDataKey, json },
{ MessageConstants.MessageDataTypeKey, message.GetType().Name }
};
try
{
await connection.SendMessageAsync(set);
}
catch (InvalidOperationException)
{
// Connection might've been disposed during the SendMessageAsync call.
// This is a safe way to handle the exception.
// We don't lock the connection since this request may take sometime to complete.
}
catch (Exception exception)
{
Log.Error(exception, "SendMessageAsync threw an exception");
}
}
private void OnConnectionClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
{
// UWP app might've been terminated or suspended.
// At this point, we must keep active synchronizations going, but connection is lost.
// As long as this process is alive, database will be kept updated, but no messages will be sent.
DisposeConnection();
}
private async void OnWinRTMessageReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
if (args.Request.Message.TryGetValue(MessageConstants.MessageTypeKey, out object messageTypeObject) && messageTypeObject is int messageTypeInt)
{
var messageType = (MessageType)messageTypeInt;
if (args.Request.Message.TryGetValue(MessageConstants.MessageDataKey, out object messageDataObject) && messageDataObject is string messageJson)
var set = new ValueSet
{
if (!args.Request.Message.TryGetValue(MessageConstants.MessageDataTypeKey, out object dataTypeObject) || dataTypeObject is not string dataTypeName)
throw new ArgumentException("Message data type is missing.");
{ MessageConstants.MessageTypeKey, (int)messageType },
{ MessageConstants.MessageDataKey, json },
{ MessageConstants.MessageDataTypeKey, message.GetType().Name }
};
if (messageType == MessageType.ServerMessage)
{
// Client is awaiting a response from server.
// ServerMessage calls are awaited on the server and response is returned back in the args.
await HandleServerMessageAsync(messageJson, dataTypeName, args).ConfigureAwait(false);
}
else if (messageType == MessageType.UIMessage)
throw new Exception("Received UIMessage from UWP. This is not expected.");
try
{
await connection.SendMessageAsync(set);
}
catch (InvalidOperationException)
{
// Connection might've been disposed during the SendMessageAsync call.
// This is a safe way to handle the exception.
// We don't lock the connection since this request may take sometime to complete.
}
catch (Exception exception)
{
Log.Error(exception, "SendMessageAsync threw an exception");
}
}
}
private async Task HandleServerMessageAsync(string messageJson, string typeName, AppServiceRequestReceivedEventArgs args)
{
switch (typeName)
private void OnConnectionClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
{
case nameof(NewMailSynchronizationRequested):
Debug.WriteLine($"New mail synchronization requested.");
// UWP app might've been terminated or suspended.
// At this point, we must keep active synchronizations going, but connection is lost.
// As long as this process is alive, database will be kept updated, but no messages will be sent.
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<NewMailSynchronizationRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(NewCalendarSynchronizationRequested):
Debug.WriteLine($"New calendar synchronization requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<NewCalendarSynchronizationRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(DownloadMissingMessageRequested):
Debug.WriteLine($"Download missing message requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<DownloadMissingMessageRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(ServerRequestPackage):
var serverPackage = JsonSerializer.Deserialize<ServerRequestPackage>(messageJson, _jsonSerializerOptions);
Debug.WriteLine(serverPackage);
await ExecuteServerMessageSafeAsync(args, serverPackage);
break;
case nameof(AuthorizationRequested):
Debug.WriteLine($"Authorization requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<AuthorizationRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(SynchronizationExistenceCheckRequest):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<SynchronizationExistenceCheckRequest>(messageJson, _jsonSerializerOptions));
break;
case nameof(ServerTerminationModeChanged):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<ServerTerminationModeChanged>(messageJson, _jsonSerializerOptions));
break;
case nameof(ImapConnectivityTestRequested):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<ImapConnectivityTestRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(TerminateServerRequested):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<TerminateServerRequested>(messageJson, _jsonSerializerOptions));
KillServer();
break;
case nameof(KillAccountSynchronizerRequested):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<KillAccountSynchronizerRequested>(messageJson, _jsonSerializerOptions));
break;
default:
Debug.WriteLine($"Missing handler for {typeName} in the server. Check ServerContext.cs - HandleServerMessageAsync.");
break;
DisposeConnection();
}
}
private void KillServer()
{
DisposeConnection();
Application.Current.Dispatcher.Invoke(() =>
private async void OnWinRTMessageReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
Application.Current.Shutdown();
});
}
if (args.Request.Message.TryGetValue(MessageConstants.MessageTypeKey, out object messageTypeObject) && messageTypeObject is int messageTypeInt)
{
var messageType = (MessageType)messageTypeInt;
/// <summary>
/// Executes ServerMessage coming from the UWP.
/// These requests are awaited and expected to return a response.
/// </summary>
/// <param name="args">App service request args.</param>
/// <param name="message">Message that client sent to server.</param>
private async Task ExecuteServerMessageSafeAsync(AppServiceRequestReceivedEventArgs args, IClientMessage message)
{
AppServiceDeferral deferral = args?.GetDeferral() ?? null;
if (args.Request.Message.TryGetValue(MessageConstants.MessageDataKey, out object messageDataObject) && messageDataObject is string messageJson)
{
if (!args.Request.Message.TryGetValue(MessageConstants.MessageDataTypeKey, out object dataTypeObject) || dataTypeObject is not string dataTypeName)
throw new ArgumentException("Message data type is missing.");
try
{
var messageName = message.GetType().Name;
if (messageType == MessageType.ServerMessage)
{
// Client is awaiting a response from server.
// ServerMessage calls are awaited on the server and response is returned back in the args.
var handler = _serverMessageHandlerFactory.GetHandler(messageName);
await handler.ExecuteAsync(message, args?.Request ?? null).ConfigureAwait(false);
await HandleServerMessageAsync(messageJson, dataTypeName, args).ConfigureAwait(false);
}
else if (messageType == MessageType.UIMessage)
throw new Exception("Received UIMessage from UWP. This is not expected.");
}
}
}
catch (Exception ex)
private async Task HandleServerMessageAsync(string messageJson, string typeName, AppServiceRequestReceivedEventArgs args)
{
Log.Error(ex, "ExecuteServerMessageSafeAsync crashed.");
Debugger.Break();
switch (typeName)
{
case nameof(NewMailSynchronizationRequested):
Debug.WriteLine($"New mail synchronization requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<NewMailSynchronizationRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(NewCalendarSynchronizationRequested):
Debug.WriteLine($"New calendar synchronization requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<NewCalendarSynchronizationRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(DownloadMissingMessageRequested):
Debug.WriteLine($"Download missing message requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<DownloadMissingMessageRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(ServerRequestPackage):
var serverPackage = JsonSerializer.Deserialize<ServerRequestPackage>(messageJson, _jsonSerializerOptions);
Debug.WriteLine(serverPackage);
await ExecuteServerMessageSafeAsync(args, serverPackage);
break;
case nameof(AuthorizationRequested):
Debug.WriteLine($"Authorization requested.");
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<AuthorizationRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(SynchronizationExistenceCheckRequest):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<SynchronizationExistenceCheckRequest>(messageJson, _jsonSerializerOptions));
break;
case nameof(ServerTerminationModeChanged):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<ServerTerminationModeChanged>(messageJson, _jsonSerializerOptions));
break;
case nameof(ImapConnectivityTestRequested):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<ImapConnectivityTestRequested>(messageJson, _jsonSerializerOptions));
break;
case nameof(TerminateServerRequested):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<TerminateServerRequested>(messageJson, _jsonSerializerOptions));
KillServer();
break;
case nameof(KillAccountSynchronizerRequested):
await ExecuteServerMessageSafeAsync(args, JsonSerializer.Deserialize<KillAccountSynchronizerRequested>(messageJson, _jsonSerializerOptions));
break;
default:
Debug.WriteLine($"Missing handler for {typeName} in the server. Check ServerContext.cs - HandleServerMessageAsync.");
break;
}
}
finally
private void KillServer()
{
deferral?.Complete();
DisposeConnection();
Application.Current.Dispatcher.Invoke(() =>
{
Application.Current.Shutdown();
});
}
}
public void Receive(ServerTerminationModeChanged message)
{
var backgroundMode = message.ServerBackgroundMode;
/// <summary>
/// Executes ServerMessage coming from the UWP.
/// These requests are awaited and expected to return a response.
/// </summary>
/// <param name="args">App service request args.</param>
/// <param name="message">Message that client sent to server.</param>
private async Task ExecuteServerMessageSafeAsync(AppServiceRequestReceivedEventArgs args, IClientMessage message)
{
AppServiceDeferral deferral = args?.GetDeferral() ?? null;
bool isServerTrayIconVisible = backgroundMode == ServerBackgroundMode.MinimizedTray || backgroundMode == ServerBackgroundMode.Terminate;
try
{
var messageName = message.GetType().Name;
App.Current.ChangeNotifyIconVisiblity(isServerTrayIconVisible);
var handler = _serverMessageHandlerFactory.GetHandler(messageName);
await handler.ExecuteAsync(message, args?.Request ?? null).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Error(ex, "ExecuteServerMessageSafeAsync crashed.");
Debugger.Break();
}
finally
{
deferral?.Complete();
}
}
public void Receive(ServerTerminationModeChanged message)
{
var backgroundMode = message.ServerBackgroundMode;
bool isServerTrayIconVisible = backgroundMode == ServerBackgroundMode.MinimizedTray || backgroundMode == ServerBackgroundMode.Terminate;
App.Current.ChangeNotifyIconVisiblity(isServerTrayIconVisible);
}
}
}

View File

@@ -9,57 +9,58 @@ using Windows.ApplicationModel;
using Windows.System;
using Wino.Core.Domain.Interfaces;
namespace Wino.Server;
public partial class ServerViewModel : ObservableObject, IInitializeAsync
namespace Wino.Server
{
private readonly INotificationBuilder _notificationBuilder;
public ServerContext Context { get; }
public ServerViewModel(ServerContext serverContext, INotificationBuilder notificationBuilder)
public partial class ServerViewModel : ObservableObject, IInitializeAsync
{
Context = serverContext;
_notificationBuilder = notificationBuilder;
}
private readonly INotificationBuilder _notificationBuilder;
[RelayCommand]
public Task LaunchWinoAsync()
{
return Launcher.LaunchUriAsync(new Uri($"{App.WinoMailLaunchProtocol}:")).AsTask();
}
public ServerContext Context { get; }
/// <summary>
/// Shuts down the application.
/// </summary>
[RelayCommand]
public async Task ExitApplication()
{
// Find the running UWP app by AppDiagnosticInfo API and terminate it if possible.
var appDiagnosticInfos = await AppDiagnosticInfo.RequestInfoForPackageAsync(Package.Current.Id.FamilyName);
var clientDiagnosticInfo = appDiagnosticInfos.FirstOrDefault();
if (clientDiagnosticInfo == null)
public ServerViewModel(ServerContext serverContext, INotificationBuilder notificationBuilder)
{
Debug.WriteLine($"Wino Mail client is not running. Termination is skipped.");
Context = serverContext;
_notificationBuilder = notificationBuilder;
}
else
{
var appResourceGroupInfo = clientDiagnosticInfo.GetResourceGroups().FirstOrDefault();
if (appResourceGroupInfo != null)
[RelayCommand]
public Task LaunchWinoAsync()
{
return Launcher.LaunchUriAsync(new Uri($"{App.WinoMailLaunchProtocol}:")).AsTask();
}
/// <summary>
/// Shuts down the application.
/// </summary>
[RelayCommand]
public async Task ExitApplication()
{
// Find the running UWP app by AppDiagnosticInfo API and terminate it if possible.
var appDiagnosticInfos = await AppDiagnosticInfo.RequestInfoForPackageAsync(Package.Current.Id.FamilyName);
var clientDiagnosticInfo = appDiagnosticInfos.FirstOrDefault();
if (clientDiagnosticInfo == null)
{
await appResourceGroupInfo.StartTerminateAsync();
Debug.WriteLine($"Wino Mail client is terminated succesfully.");
Debug.WriteLine($"Wino Mail client is not running. Termination is skipped.");
}
else
{
var appResourceGroupInfo = clientDiagnosticInfo.GetResourceGroups().FirstOrDefault();
if (appResourceGroupInfo != null)
{
await appResourceGroupInfo.StartTerminateAsync();
Debug.WriteLine($"Wino Mail client is terminated succesfully.");
}
}
Application.Current.Shutdown();
}
Application.Current.Shutdown();
public async Task ReconnectAsync() => await Context.InitializeAppServiceConnectionAsync();
public Task InitializeAsync() => Context.InitializeAppServiceConnectionAsync();
}
public async Task ReconnectAsync() => await Context.InitializeAppServiceConnectionAsync();
public Task InitializeAsync() => Context.InitializeAppServiceConnectionAsync();
}