file scoped namespaces (#565)
This commit is contained in:
@@ -20,248 +20,247 @@ using Wino.Server.Core;
|
||||
using Wino.Server.MessageHandlers;
|
||||
using Wino.Services;
|
||||
|
||||
namespace Wino.Server
|
||||
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
|
||||
{
|
||||
/// <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
|
||||
[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()
|
||||
{
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
|
||||
var services = new ServiceCollection();
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
services.AddTransient<ServerContext>();
|
||||
services.AddTransient<ServerViewModel>();
|
||||
|
||||
private const string FRAME_WINDOW = "ApplicationFrameWindow";
|
||||
services.RegisterCoreServices();
|
||||
services.RegisterSharedServices();
|
||||
|
||||
public const string WinoMailLaunchProtocol = "wino.mail.launch";
|
||||
public const string WinoCalendarLaunchProtocol = "wino.calendar.launch";
|
||||
// Below services belongs to UWP.Core package and some APIs are not available for WPF.
|
||||
// We register them here to avoid compilation errors.
|
||||
|
||||
private const string NotifyIconResourceKey = "NotifyIcon";
|
||||
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);
|
||||
|
||||
private const string WinoMailServerAppName = "Wino.Mail.Server";
|
||||
private const string WinoMailServerActivatedName = "Wino.Mail.Server.Activated";
|
||||
services.AddSingleton<IServerMessageHandlerFactory>(serverMessageHandlerFactory);
|
||||
|
||||
private const string WinoCalendarServerAppName = "Wino.Calendar.Server";
|
||||
private const string WinoCalendarServerActivatedName = "Wino.Calendar.Server.Activated";
|
||||
public new static App Current => (App)Application.Current;
|
||||
// Server type related services.
|
||||
// TODO: Better abstraction.
|
||||
|
||||
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()
|
||||
if (WinoServerType == WinoAppType.Mail)
|
||||
{
|
||||
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();
|
||||
services.AddSingleton<IAuthenticatorConfig, MailAuthenticatorConfiguration>();
|
||||
}
|
||||
else
|
||||
{
|
||||
services.AddSingleton<IAuthenticatorConfig, CalendarAuthenticatorConfig>();
|
||||
}
|
||||
|
||||
private async Task<ServerViewModel> InitializeNewServerAsync()
|
||||
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))
|
||||
{
|
||||
// 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)
|
||||
{
|
||||
IntPtr coreWindow = FindWindowEx(appWindow, IntPtr.Zero, "Windows.UI.Core.CoreWindow", null);
|
||||
if (coreWindow != IntPtr.Zero)
|
||||
GetWindowThreadProcessId(coreWindow, out var corePid);
|
||||
if (corePid == proc.Id)
|
||||
{
|
||||
GetWindowThreadProcessId(coreWindow, out var corePid);
|
||||
if (corePid == proc.Id)
|
||||
{
|
||||
return appWindow;
|
||||
}
|
||||
return appWindow;
|
||||
}
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
protected override async void OnStartup(StartupEventArgs e)
|
||||
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)
|
||||
{
|
||||
// Same server code runs for both Mail and Calendar.
|
||||
AppDomain.CurrentDomain.UnhandledException += ServerCrashed;
|
||||
Application.Current.DispatcherUnhandledException += UIThreadCrash;
|
||||
TaskScheduler.UnobservedTaskException += TaskCrashed;
|
||||
|
||||
string winoAppTypeParameter = e.Args.Length > 0 ? e.Args[e.Args.Length - 1] : "Mail";
|
||||
// Ensure proper encodings are available for MimeKit
|
||||
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||
|
||||
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)
|
||||
// Spawn a thread which will be waiting for our event
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
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())
|
||||
{
|
||||
while (_eventWaitHandle.WaitOne())
|
||||
if (notifyIcon == null) return;
|
||||
|
||||
Current.Dispatcher.BeginInvoke(async () =>
|
||||
{
|
||||
if (notifyIcon == null) return;
|
||||
|
||||
Current.Dispatcher.BeginInvoke(async () =>
|
||||
if (notifyIcon.DataContext is ServerViewModel trayIconViewModel)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
private void TaskCrashed(object sender, UnobservedTaskExceptionEventArgs e) => Log.Error(e.Exception, "Server task crashed.");
|
||||
|
||||
private void UIThreadCrash(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) => Log.Error(e.Exception, "Server 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;
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
private void TaskCrashed(object sender, UnobservedTaskExceptionEventArgs e) => Log.Error(e.Exception, "Server task crashed.");
|
||||
|
||||
private void UIThreadCrash(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) => Log.Error(e.Exception, "Server 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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,68 +8,67 @@ using Wino.Core.Domain.Interfaces;
|
||||
using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging;
|
||||
|
||||
namespace Wino.Server.Core
|
||||
namespace Wino.Server.Core;
|
||||
|
||||
public abstract class ServerMessageHandlerBase
|
||||
{
|
||||
public abstract class ServerMessageHandlerBase
|
||||
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 string HandlingRequestType { get; }
|
||||
WinoServerResponse<TResponse> response = default;
|
||||
|
||||
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)
|
||||
try
|
||||
{
|
||||
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)
|
||||
{
|
||||
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()
|
||||
{
|
||||
var valueSet = new ValueSet()
|
||||
{
|
||||
{ MessageConstants.MessageDataKey, JsonSerializer.Serialize(response) }
|
||||
};
|
||||
{ MessageConstants.MessageDataKey, JsonSerializer.Serialize(response) }
|
||||
};
|
||||
|
||||
await request.SendResponseAsync(valueSet);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
@@ -5,42 +5,41 @@ using Wino.Core.Domain.Models.Synchronization;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.MessageHandlers;
|
||||
|
||||
namespace Wino.Server.Core
|
||||
namespace Wino.Server.Core;
|
||||
|
||||
public class ServerMessageHandlerFactory : IServerMessageHandlerFactory
|
||||
{
|
||||
public class ServerMessageHandlerFactory : IServerMessageHandlerFactory
|
||||
public ServerMessageHandlerBase GetHandler(string typeName)
|
||||
{
|
||||
public ServerMessageHandlerBase GetHandler(string typeName)
|
||||
return typeName switch
|
||||
{
|
||||
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."),
|
||||
};
|
||||
}
|
||||
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>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
{
|
||||
public interface IServerMessageHandlerFactory
|
||||
{
|
||||
void Setup(IServiceCollection serviceCollection);
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
ServerMessageHandlerBase GetHandler(string typeName);
|
||||
}
|
||||
public interface IServerMessageHandlerFactory
|
||||
{
|
||||
void Setup(IServiceCollection serviceCollection);
|
||||
|
||||
ServerMessageHandlerBase GetHandler(string typeName);
|
||||
}
|
||||
|
||||
@@ -7,50 +7,49 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class AuthenticationHandler : ServerMessageHandler<AuthorizationRequested, TokenInformationEx>
|
||||
{
|
||||
public class AuthenticationHandler : ServerMessageHandler<AuthorizationRequested, TokenInformationEx>
|
||||
private readonly IAuthenticationProvider _authenticationProvider;
|
||||
|
||||
public override WinoServerResponse<TokenInformationEx> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<TokenInformationEx>.CreateErrorResponse(ex.Message);
|
||||
|
||||
public AuthenticationHandler(IAuthenticationProvider authenticationProvider)
|
||||
{
|
||||
private readonly IAuthenticationProvider _authenticationProvider;
|
||||
_authenticationProvider = authenticationProvider;
|
||||
}
|
||||
|
||||
public override WinoServerResponse<TokenInformationEx> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<TokenInformationEx>.CreateErrorResponse(ex.Message);
|
||||
protected override async Task<WinoServerResponse<TokenInformationEx>> HandleAsync(AuthorizationRequested message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var authenticator = _authenticationProvider.GetAuthenticator(message.MailProviderType);
|
||||
|
||||
public AuthenticationHandler(IAuthenticationProvider authenticationProvider)
|
||||
// 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)
|
||||
{
|
||||
_authenticationProvider = authenticationProvider;
|
||||
gmailAuthenticator.ProposeCopyAuthURL = true;
|
||||
}
|
||||
|
||||
protected override async Task<WinoServerResponse<TokenInformationEx>> HandleAsync(AuthorizationRequested message,
|
||||
CancellationToken cancellationToken = default)
|
||||
TokenInformationEx generatedToken = null;
|
||||
|
||||
if (message.CreatedAccount != null)
|
||||
{
|
||||
var authenticator = _authenticationProvider.GetAuthenticator(message.MailProviderType);
|
||||
|
||||
// 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)
|
||||
{
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,34 +7,33 @@ using Wino.Core.Domain.Models.Synchronization;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class CalendarSynchronizationRequestHandler : ServerMessageHandler<NewCalendarSynchronizationRequested, CalendarSynchronizationResult>
|
||||
{
|
||||
public class CalendarSynchronizationRequestHandler : ServerMessageHandler<NewCalendarSynchronizationRequested, CalendarSynchronizationResult>
|
||||
public override WinoServerResponse<CalendarSynchronizationResult> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<CalendarSynchronizationResult>.CreateErrorResponse(ex.Message);
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
|
||||
public CalendarSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
public override WinoServerResponse<CalendarSynchronizationResult> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<CalendarSynchronizationResult>.CreateErrorResponse(ex.Message);
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
protected override async Task<WinoServerResponse<CalendarSynchronizationResult>> HandleAsync(NewCalendarSynchronizationRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.Options.AccountId);
|
||||
|
||||
public CalendarSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory)
|
||||
try
|
||||
{
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
var synchronizationResult = await synchronizer.SynchronizeCalendarEventsAsync(message.Options, cancellationToken);
|
||||
|
||||
return WinoServerResponse<CalendarSynchronizationResult>.CreateSuccessResponse(synchronizationResult);
|
||||
}
|
||||
|
||||
protected override async Task<WinoServerResponse<CalendarSynchronizationResult>> HandleAsync(NewCalendarSynchronizationRequested message, CancellationToken cancellationToken = default)
|
||||
catch (Exception ex)
|
||||
{
|
||||
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;
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,43 +8,42 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class ImapConnectivityTestHandler : ServerMessageHandler<ImapConnectivityTestRequested, ImapConnectivityTestResults>
|
||||
{
|
||||
public class ImapConnectivityTestHandler : ServerMessageHandler<ImapConnectivityTestRequested, ImapConnectivityTestResults>
|
||||
private readonly IImapTestService _imapTestService;
|
||||
|
||||
public override WinoServerResponse<ImapConnectivityTestResults> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<ImapConnectivityTestResults>.CreateErrorResponse(ex.Message);
|
||||
|
||||
public ImapConnectivityTestHandler(IImapTestService imapTestService)
|
||||
{
|
||||
private readonly IImapTestService _imapTestService;
|
||||
_imapTestService = imapTestService;
|
||||
}
|
||||
|
||||
public override WinoServerResponse<ImapConnectivityTestResults> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<ImapConnectivityTestResults>.CreateErrorResponse(ex.Message);
|
||||
|
||||
public ImapConnectivityTestHandler(IImapTestService imapTestService)
|
||||
protected override async Task<WinoServerResponse<ImapConnectivityTestResults>> HandleAsync(ImapConnectivityTestRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
_imapTestService = imapTestService;
|
||||
await _imapTestService.TestImapConnectionAsync(message.ServerInformation, message.IsSSLHandshakeAllowed);
|
||||
|
||||
return WinoServerResponse<ImapConnectivityTestResults>.CreateSuccessResponse(ImapConnectivityTestResults.Success());
|
||||
}
|
||||
|
||||
protected override async Task<WinoServerResponse<ImapConnectivityTestResults>> HandleAsync(ImapConnectivityTestRequested message, CancellationToken cancellationToken = default)
|
||||
catch (ImapTestSSLCertificateException sslTestException)
|
||||
{
|
||||
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));
|
||||
}
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,25 +6,24 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class KillAccountSynchronizerHandler : ServerMessageHandler<KillAccountSynchronizerRequested, bool>
|
||||
{
|
||||
public class KillAccountSynchronizerHandler : ServerMessageHandler<KillAccountSynchronizerRequested, bool>
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
|
||||
public KillAccountSynchronizerHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
protected override async Task<WinoServerResponse<bool>> HandleAsync(KillAccountSynchronizerRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _synchronizerFactory.DeleteSynchronizerAsync(message.AccountId);
|
||||
|
||||
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);
|
||||
}
|
||||
return WinoServerResponse<bool>.CreateSuccessResponse(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,99 +11,98 @@ using Wino.Messaging.Server;
|
||||
using Wino.Messaging.UI;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for NewMailSynchronizationRequested from the client.
|
||||
/// </summary>
|
||||
public class MailSynchronizationRequestHandler : ServerMessageHandler<NewMailSynchronizationRequested, MailSynchronizationResult>
|
||||
{
|
||||
/// <summary>
|
||||
/// Handler for NewMailSynchronizationRequested from the client.
|
||||
/// </summary>
|
||||
public class MailSynchronizationRequestHandler : ServerMessageHandler<NewMailSynchronizationRequested, MailSynchronizationResult>
|
||||
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)
|
||||
{
|
||||
public override WinoServerResponse<MailSynchronizationResult> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<MailSynchronizationResult>.CreateErrorResponse(ex.Message);
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
_notificationBuilder = notificationBuilder;
|
||||
_folderService = folderService;
|
||||
}
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
private readonly INotificationBuilder _notificationBuilder;
|
||||
private readonly IFolderService _folderService;
|
||||
protected override async Task<WinoServerResponse<MailSynchronizationResult>> HandleAsync(NewMailSynchronizationRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.Options.AccountId);
|
||||
|
||||
public MailSynchronizationRequestHandler(ISynchronizerFactory synchronizerFactory,
|
||||
INotificationBuilder notificationBuilder,
|
||||
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
|
||||
{
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
_notificationBuilder = notificationBuilder;
|
||||
_folderService = 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);
|
||||
}
|
||||
// TODO: Following cases might always be thrown from server. Handle them properly.
|
||||
|
||||
protected override async Task<WinoServerResponse<MailSynchronizationResult>> HandleAsync(NewMailSynchronizationRequested message, CancellationToken cancellationToken = default)
|
||||
//catch (AuthenticationAttentionException)
|
||||
//{
|
||||
// // TODO
|
||||
// // await SetAccountAttentionAsync(accountId, AccountAttentionReason.InvalidCredentials);
|
||||
//}
|
||||
//catch (SystemFolderConfigurationMissingException)
|
||||
//{
|
||||
// // TODO
|
||||
// // await SetAccountAttentionAsync(accountId, AccountAttentionReason.MissingSystemFolderConfiguration);
|
||||
//}
|
||||
catch (Exception)
|
||||
{
|
||||
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;
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,17 +6,16 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class ServerTerminationModeHandler : ServerMessageHandler<ServerTerminationModeChanged, bool>
|
||||
{
|
||||
public class ServerTerminationModeHandler : ServerMessageHandler<ServerTerminationModeChanged, bool>
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
|
||||
protected override Task<WinoServerResponse<bool>> HandleAsync(ServerTerminationModeChanged message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
WeakReferenceMessenger.Default.Send(message);
|
||||
|
||||
protected override Task<WinoServerResponse<bool>> HandleAsync(ServerTerminationModeChanged message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send(message);
|
||||
|
||||
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
|
||||
}
|
||||
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,26 +6,25 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class SingleMimeDownloadHandler : ServerMessageHandler<DownloadMissingMessageRequested, bool>
|
||||
{
|
||||
public class SingleMimeDownloadHandler : ServerMessageHandler<DownloadMissingMessageRequested, bool>
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
public SingleMimeDownloadHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
public SingleMimeDownloadHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
protected override async Task<WinoServerResponse<bool>> HandleAsync(DownloadMissingMessageRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
|
||||
|
||||
protected override async Task<WinoServerResponse<bool>> HandleAsync(DownloadMissingMessageRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
|
||||
// TODO: ITransferProgress support is lost.
|
||||
await synchronizer.DownloadMissingMimeMessageAsync(message.MailItem, null, cancellationToken);
|
||||
|
||||
// TODO: ITransferProgress support is lost.
|
||||
await synchronizer.DownloadMissingMimeMessageAsync(message.MailItem, null, cancellationToken);
|
||||
|
||||
return WinoServerResponse<bool>.CreateSuccessResponse(true);
|
||||
}
|
||||
return WinoServerResponse<bool>.CreateSuccessResponse(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,25 +6,24 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Core.Domain.Models.Synchronization;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class SyncExistenceHandler : ServerMessageHandler<SynchronizationExistenceCheckRequest, bool>
|
||||
{
|
||||
public class SyncExistenceHandler : ServerMessageHandler<SynchronizationExistenceCheckRequest, bool>
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
|
||||
public SyncExistenceHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex)
|
||||
=> WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
protected override async Task<WinoServerResponse<bool>> HandleAsync(SynchronizationExistenceCheckRequest message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(message.AccountId);
|
||||
|
||||
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);
|
||||
}
|
||||
return WinoServerResponse<bool>.CreateSuccessResponse(synchronizer.State != Wino.Core.Domain.Enums.AccountSynchronizerState.Idle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,21 +6,20 @@ using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Messaging.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class TerminateServerRequestHandler : ServerMessageHandler<TerminateServerRequested, bool>
|
||||
{
|
||||
public class TerminateServerRequestHandler : ServerMessageHandler<TerminateServerRequested, bool>
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
|
||||
protected override Task<WinoServerResponse<bool>> HandleAsync(TerminateServerRequested message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
// 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.
|
||||
|
||||
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.
|
||||
Log.Information("Terminate server is requested by client. Killing server.");
|
||||
|
||||
Log.Information("Terminate server is requested by client. Killing server.");
|
||||
|
||||
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
|
||||
}
|
||||
return Task.FromResult(WinoServerResponse<bool>.CreateSuccessResponse(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,36 +6,35 @@ using Wino.Core.Domain.Models.Requests;
|
||||
using Wino.Core.Domain.Models.Server;
|
||||
using Wino.Server.Core;
|
||||
|
||||
namespace Wino.Server.MessageHandlers
|
||||
namespace Wino.Server.MessageHandlers;
|
||||
|
||||
public class UserActionRequestHandler : ServerMessageHandler<ServerRequestPackage, bool>
|
||||
{
|
||||
public class UserActionRequestHandler : ServerMessageHandler<ServerRequestPackage, bool>
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
|
||||
public UserActionRequestHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
private readonly ISynchronizerFactory _synchronizerFactory;
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
|
||||
public override WinoServerResponse<bool> FailureDefaultResponse(Exception ex) => WinoServerResponse<bool>.CreateErrorResponse(ex.Message);
|
||||
protected override async Task<WinoServerResponse<bool>> HandleAsync(ServerRequestPackage package, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(package.AccountId);
|
||||
synchronizer.QueueRequest(package.Request);
|
||||
|
||||
public UserActionRequestHandler(ISynchronizerFactory synchronizerFactory)
|
||||
{
|
||||
_synchronizerFactory = synchronizerFactory;
|
||||
}
|
||||
//if (package.QueueSynchronization)
|
||||
//{
|
||||
// var options = new SynchronizationOptions
|
||||
// {
|
||||
// AccountId = package.AccountId,
|
||||
// Type = Wino.Core.Domain.Enums.SynchronizationType.ExecuteRequests
|
||||
// };
|
||||
|
||||
protected override async Task<WinoServerResponse<bool>> HandleAsync(ServerRequestPackage package, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var synchronizer = await _synchronizerFactory.GetAccountSynchronizerAsync(package.AccountId);
|
||||
synchronizer.QueueRequest(package.Request);
|
||||
// WeakReferenceMessenger.Default.Send(new NewSynchronizationRequested(options));
|
||||
//}
|
||||
|
||||
//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);
|
||||
}
|
||||
return WinoServerResponse<bool>.CreateSuccessResponse(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,363 +20,362 @@ using Wino.Messaging.UI;
|
||||
using Wino.Server.MessageHandlers;
|
||||
using Wino.Services;
|
||||
|
||||
namespace Wino.Server
|
||||
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>
|
||||
{
|
||||
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>
|
||||
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
|
||||
{
|
||||
private readonly System.Timers.Timer _timer;
|
||||
private static object connectionLock = new object();
|
||||
TypeInfoResolver = new ServerRequestTypeInfoResolver()
|
||||
};
|
||||
|
||||
private AppServiceConnection connection = null;
|
||||
public ServerContext(IDatabaseService databaseService,
|
||||
IApplicationConfiguration applicationFolderConfiguration,
|
||||
ISynchronizerFactory synchronizerFactory,
|
||||
IServerMessageHandlerFactory serverMessageHandlerFactory,
|
||||
IAccountService accountService)
|
||||
{
|
||||
// Setup timer for synchronization.
|
||||
|
||||
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
|
||||
_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)
|
||||
{
|
||||
TypeInfoResolver = new ServerRequestTypeInfoResolver()
|
||||
};
|
||||
|
||||
public ServerContext(IDatabaseService databaseService,
|
||||
IApplicationConfiguration applicationFolderConfiguration,
|
||||
ISynchronizerFactory synchronizerFactory,
|
||||
IServerMessageHandlerFactory serverMessageHandlerFactory,
|
||||
IAccountService accountService)
|
||||
{
|
||||
// Setup timer for synchronization.
|
||||
|
||||
_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)
|
||||
var options = new MailSynchronizationOptions
|
||||
{
|
||||
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()
|
||||
AccountId = account.Id,
|
||||
Type = MailSynchronizationType.InboxOnly,
|
||||
};
|
||||
|
||||
connection.RequestReceived += OnWinRTMessageReceived;
|
||||
connection.ServiceClosed += OnConnectionClosed;
|
||||
var request = new NewMailSynchronizationRequested(options, SynchronizationSource.Server);
|
||||
|
||||
AppServiceConnectionStatus status = await connection.OpenAsync();
|
||||
|
||||
if (status != AppServiceConnectionStatus.Success)
|
||||
{
|
||||
Log.Error("Opening server connection failed. Status: {status}", status);
|
||||
|
||||
DisposeConnection();
|
||||
}
|
||||
await ExecuteServerMessageSafeAsync(null, request);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes current connection to UWP app service.
|
||||
/// </summary>
|
||||
private void DisposeConnection()
|
||||
#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
|
||||
{
|
||||
lock (connectionLock)
|
||||
{
|
||||
if (connection == null) return;
|
||||
|
||||
connection.RequestReceived -= OnWinRTMessageReceived;
|
||||
connection.ServiceClosed -= OnConnectionClosed;
|
||||
|
||||
connection.Dispose();
|
||||
connection = null;
|
||||
}
|
||||
return Package.Current.Id.FamilyName;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return "Debug.Wino.Server.FamilyName";
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
/// <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;
|
||||
|
||||
if (message is not IUIMessage serverMessage)
|
||||
throw new ArgumentException("Server message must be a type of IUIMessage");
|
||||
connection.RequestReceived -= OnWinRTMessageReceived;
|
||||
connection.ServiceClosed -= OnConnectionClosed;
|
||||
|
||||
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)
|
||||
{
|
||||
if (!args.Request.Message.TryGetValue(MessageConstants.MessageDataTypeKey, out object dataTypeObject) || dataTypeObject is not string dataTypeName)
|
||||
throw new ArgumentException("Message data type is missing.");
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleServerMessageAsync(string messageJson, string typeName, AppServiceRequestReceivedEventArgs args)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
private void KillServer()
|
||||
{
|
||||
DisposeConnection();
|
||||
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
Application.Current.Shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
try
|
||||
{
|
||||
var messageName = message.GetType().Name;
|
||||
|
||||
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);
|
||||
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;
|
||||
|
||||
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)
|
||||
{
|
||||
if (!args.Request.Message.TryGetValue(MessageConstants.MessageDataTypeKey, out object dataTypeObject) || dataTypeObject is not string dataTypeName)
|
||||
throw new ArgumentException("Message data type is missing.");
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleServerMessageAsync(string messageJson, string typeName, AppServiceRequestReceivedEventArgs args)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
private void KillServer()
|
||||
{
|
||||
DisposeConnection();
|
||||
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
Application.Current.Shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
try
|
||||
{
|
||||
var messageName = message.GetType().Name;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,58 +9,57 @@ using Windows.ApplicationModel;
|
||||
using Windows.System;
|
||||
using Wino.Core.Domain.Interfaces;
|
||||
|
||||
namespace Wino.Server
|
||||
namespace Wino.Server;
|
||||
|
||||
public partial class ServerViewModel : ObservableObject, IInitializeAsync
|
||||
{
|
||||
public partial class ServerViewModel : ObservableObject, IInitializeAsync
|
||||
private readonly INotificationBuilder _notificationBuilder;
|
||||
|
||||
public ServerContext Context { get; }
|
||||
|
||||
public ServerViewModel(ServerContext serverContext, INotificationBuilder notificationBuilder)
|
||||
{
|
||||
private readonly INotificationBuilder _notificationBuilder;
|
||||
|
||||
public ServerContext Context { get; }
|
||||
|
||||
public ServerViewModel(ServerContext serverContext, INotificationBuilder notificationBuilder)
|
||||
{
|
||||
Context = serverContext;
|
||||
_notificationBuilder = notificationBuilder;
|
||||
}
|
||||
|
||||
[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)
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
public async Task ReconnectAsync() => await Context.InitializeAppServiceConnectionAsync();
|
||||
|
||||
public Task InitializeAsync() => Context.InitializeAppServiceConnectionAsync();
|
||||
Context = serverContext;
|
||||
_notificationBuilder = notificationBuilder;
|
||||
}
|
||||
|
||||
[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)
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
public async Task ReconnectAsync() => await Context.InitializeAppServiceConnectionAsync();
|
||||
|
||||
public Task InitializeAsync() => Context.InitializeAppServiceConnectionAsync();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user