Delegating changes to UI and triggering new background synchronization.

This commit is contained in:
Burak Kaan Köse
2024-07-18 20:03:58 +02:00
parent 7ef045a0ad
commit 38f44a8b39
25 changed files with 331 additions and 104 deletions

View File

@@ -1,8 +0,0 @@
namespace Wino.Core.Domain.Interfaces
{
public interface IAppInitializerService
{
string GetApplicationDataFolder();
string GetPublisherSharedFolder();
}
}

View File

@@ -0,0 +1,21 @@
namespace Wino.Core.Domain.Interfaces
{
/// <summary>
/// Singleton object that holds the application data folder path and the publisher shared folder path.
/// Load the values before calling any service.
/// App data folder is used for storing files.
/// Pubhlisher cache folder is only used for database file so other apps can access it in the same package by same publisher.
/// </summary>
public interface IApplicationConfiguration
{
/// <summary>
/// Application data folder.
/// </summary>
string ApplicationDataFolderPath { get; set; }
/// <summary>
/// Publisher shared folder path.
/// </summary>
string PublisherSharedFolderPath { get; set; }
}
}

View File

@@ -11,6 +11,7 @@ namespace Wino.Core.Domain.Interfaces
Task<string> GetEditorBundlePathAsync();
Task LaunchFileAsync(string filePath);
Task LaunchUriAsync(Uri uri);
bool IsAppRunning();
string GetFullAppVersion();

View File

@@ -20,7 +20,7 @@ namespace Wino.Core.UWP
services.AddSingleton<IStoreManagementService, StoreManagementService>();
services.AddSingleton<IBackgroundTaskService, BackgroundTaskService>();
services.AddTransient<IAppInitializerService, AppInitializerService>();
services.AddTransient<IConfigurationService, ConfigurationService>();
services.AddTransient<IFileService, FileService>();
services.AddTransient<IStoreRatingService, StoreRatingService>();

View File

@@ -1,13 +0,0 @@
using Windows.Storage;
using Wino.Core.Domain.Interfaces;
namespace Wino.Core.UWP.Services
{
public class AppInitializerService : IAppInitializerService
{
public const string SharedFolderName = "WinoShared";
public string GetPublisherSharedFolder() => ApplicationData.Current.GetPublisherCacheFolder(SharedFolderName).Path;
public string GetApplicationDataFolder() => ApplicationData.Current.LocalFolder.Path;
}
}

View File

@@ -9,11 +9,14 @@ using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI.Shell;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Authorization;
#if WINDOWS_UWP
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#endif
namespace Wino.Services
{
public class NativeAppService : INativeAppService
@@ -21,7 +24,14 @@ namespace Wino.Services
private string _mimeMessagesFolder;
private string _editorBundlePath;
public string GetWebAuthenticationBrokerUri() => WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;
public string GetWebAuthenticationBrokerUri()
{
#if WINDOWS_UWP
return WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;
#endif
return string.Empty;
}
public async Task<string> GetMimeMessageStoragePath()
{
@@ -91,7 +101,15 @@ namespace Wino.Services
return _editorBundlePath;
}
public bool IsAppRunning() => (Window.Current?.Content as Frame)?.Content != null;
public bool IsAppRunning()
{
#if WINDOWS_UWP
return (Window.Current?.Content as Frame)?.Content != null;
#endif
return true;
}
public async Task LaunchFileAsync(string filePath)
{

View File

@@ -7,7 +7,7 @@ using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Reader;
using Wino.Core.Services;
namespace Wino.Services
namespace Wino.Core.UWP.Services
{
public class PreferencesService : ObservableObject, IPreferencesService
{

View File

@@ -2,7 +2,6 @@
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.AppCenter.Crashes;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Messages.Shell;
@@ -116,17 +115,10 @@ namespace Wino.Services
private void UpdateAppCoreWindowTitle()
{
try
{
var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
if (appView != null)
appView.Title = CoreWindowTitle;
}
catch (System.Exception ex)
{
Crashes.TrackError(ex);
}
if (appView != null)
appView.Title = CoreWindowTitle;
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Text.Json;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
@@ -140,6 +141,8 @@ namespace Wino.Core.UWP.Services
/// <param name="messageJson">Message data in json format.</param>
private void HandleUIMessage(string messageJson, string typeName)
{
Debug.WriteLine($"C: UImessage ({typeName})");
switch (typeName)
{
case nameof(MailAddedMessage):

View File

@@ -128,7 +128,8 @@
<Compile Include="Models\Personalization\PreDefinedAppTheme.cs" />
<Compile Include="Models\Personalization\SystemAppTheme.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\AppInitializerService.cs" />
<Compile Include="Services\PreferencesService.cs" />
<Compile Include="Services\StatePersistenceService.cs" />
<Compile Include="Services\WinoServerConnectionManager.cs" />
<Compile Include="Services\BackgroundTaskService.cs" />
<Compile Include="Services\ClipboardService.cs" />

View File

@@ -29,10 +29,17 @@ namespace Wino.Core.Authenticators
{
var authenticationRedirectUri = nativeAppService.GetWebAuthenticationBrokerUri();
_publicClientApplication = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(Authority)
.WithRedirectUri(authenticationRedirectUri)
.Build();
var outlookAppBuilder = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(Authority);
#if WINDOWS_UWP
outlookAppBuilder.WithRedirectUri(authenticationRedirectUri);
#else
outlookAppBuilder.WithDefaultRedirectUri();
#endif
_publicClientApplication = outlookAppBuilder.Build();
}
#pragma warning disable S1133 // Deprecated code should be removed

View File

@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Serilog.Core;
using Wino.Core.Authenticators;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Integration.Processors;
using Wino.Core.Integration.Threading;
@@ -16,6 +17,7 @@ namespace Wino.Core
services.AddSingleton(loggerLevelSwitcher);
services.AddSingleton<ILogInitializer, LogInitializer>();
services.AddSingleton<IApplicationConfiguration, ApplicationConfiguration>();
services.AddSingleton<ITranslationService, TranslationService>();
services.AddSingleton<IDatabaseService, DatabaseService>();
services.AddSingleton<IThreadingStrategyProvider, ThreadingStrategyProvider>();
@@ -41,6 +43,10 @@ namespace Wino.Core
services.AddTransient<IFontService, FontService>();
services.AddTransient<IUnsubscriptionService, UnsubscriptionService>();
services.AddTransient<OutlookAuthenticator>();
services.AddTransient<GmailAuthenticator>();
services.AddTransient<CustomAuthenticator>();
services.AddTransient<OutlookThreadingStrategy>();
services.AddTransient<GmailThreadingStrategy>();
services.AddTransient<ImapThreadStrategy>();

View File

@@ -0,0 +1,13 @@
using Wino.Core.Domain.Interfaces;
namespace Wino.Core.Services
{
public class ApplicationConfiguration : IApplicationConfiguration
{
public const string SharedFolderName = "WinoShared";
public string ApplicationDataFolderPath { get; set; }
public string PublisherSharedFolderPath { get; set; }
}
}

View File

@@ -14,16 +14,16 @@ namespace Wino.Core.Services
public class DatabaseService : IDatabaseService
{
private string DatabaseName => "Wino172.db";
private const string DatabaseName = "Wino172.db";
private bool _isInitialized = false;
private readonly IAppInitializerService _appInitializerService;
private readonly IApplicationConfiguration _folderConfiguration;
public SQLiteAsyncConnection Connection { get; private set; }
public DatabaseService(IAppInitializerService appInitializerService)
public DatabaseService(IApplicationConfiguration folderConfiguration)
{
_appInitializerService = appInitializerService;
_folderConfiguration = folderConfiguration;
}
public async Task InitializeAsync()
@@ -31,8 +31,8 @@ namespace Wino.Core.Services
if (_isInitialized)
return;
var applicationData = _appInitializerService.GetPublisherSharedFolder();
var databaseFileName = Path.Combine(applicationData, DatabaseName);
var publisherCacheFolder = _folderConfiguration.PublisherSharedFolderPath;
var databaseFileName = Path.Combine(publisherCacheFolder, DatabaseName);
Connection = new SQLiteAsyncConnection(databaseFileName)
{
@@ -45,7 +45,6 @@ namespace Wino.Core.Services
})
};
await CreateTablesAsync();
_isInitialized = true;

View File

@@ -11,11 +11,11 @@ namespace Wino.Core.Services
public const string ProtocolLogFileName = "ImapProtocolLog.log";
private readonly IPreferencesService _preferencesService;
private readonly IAppInitializerService _appInitializerService;
private readonly IApplicationConfiguration _appInitializerService;
private Stream _protocolLogStream;
public ImapTestService(IPreferencesService preferencesService, IAppInitializerService appInitializerService)
public ImapTestService(IPreferencesService preferencesService, IApplicationConfiguration appInitializerService)
{
_preferencesService = preferencesService;
_appInitializerService = appInitializerService;
@@ -24,7 +24,7 @@ namespace Wino.Core.Services
private void EnsureProtocolLogFileExists()
{
// Create new file for protocol logger.
var localAppFolderPath = _appInitializerService.GetApplicationDataFolder();
var localAppFolderPath = _appInitializerService.ApplicationDataFolderPath;
var logFile = Path.Combine(localAppFolderPath, ProtocolLogFileName);

View File

@@ -12,7 +12,7 @@ namespace Wino.Mail.ViewModels
{
private readonly IStoreRatingService _storeRatingService;
private readonly INativeAppService _nativeAppService;
private readonly IAppInitializerService _appInitializerService;
private readonly IApplicationConfiguration _appInitializerService;
private readonly IFileService _fileService;
private readonly ILogInitializer _logInitializer;
@@ -31,7 +31,7 @@ namespace Wino.Mail.ViewModels
IDialogService dialogService,
INativeAppService nativeAppService,
IPreferencesService preferencesService,
IAppInitializerService appInitializerService,
IApplicationConfiguration appInitializerService,
IFileService fileService,
ILogInitializer logInitializer) : base(dialogService)
{
@@ -77,7 +77,7 @@ namespace Wino.Mail.ViewModels
private async Task SaveLogInternalAsync(string sourceFileName)
{
var appDataFolder = _appInitializerService.GetApplicationDataFolder();
var appDataFolder = _appInitializerService.ApplicationDataFolderPath;
var logFile = Path.Combine(appDataFolder, sourceFileName);

View File

@@ -4,6 +4,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.AppCenter.Crashes;
using MoreLinq;
@@ -129,6 +130,9 @@ namespace Wino.Mail.ViewModels
_winoRequestDelegator = winoRequestDelegator;
}
[RelayCommand]
private Task ReconnectServerAsync() => ServerConnectionManager.ConnectAsync();
protected override void OnDispatcherAssigned()
{
base.OnDispatcherAssigned();

View File

@@ -45,8 +45,9 @@ namespace Wino
private readonly ILogInitializer _logInitializer;
private readonly IThemeService _themeService;
private readonly IDatabaseService _databaseService;
private readonly IAppInitializerService _appInitializerService;
private readonly IApplicationConfiguration _appInitializerService;
private readonly ITranslationService _translationService;
private readonly IApplicationConfiguration _applicationFolderConfiguration;
// Order matters.
private List<IInitializeAsync> initializeServices => new List<IInitializeAsync>()
@@ -77,10 +78,16 @@ namespace Wino
ConfigurePrelaunch();
ConfigureXbox();
_applicationFolderConfiguration = Services.GetService<IApplicationConfiguration>();
// Make sure the paths are setup on app start.
_applicationFolderConfiguration.ApplicationDataFolderPath = ApplicationData.Current.LocalFolder.Path;
_applicationFolderConfiguration.PublisherSharedFolderPath = ApplicationData.Current.GetPublisherCacheFolder(ApplicationConfiguration.SharedFolderName).Path;
_appServiceConnectionManager = Services.GetService<IWinoServerConnectionManager<AppServiceConnection>>();
_themeService = Services.GetService<IThemeService>();
_databaseService = Services.GetService<IDatabaseService>();
_appInitializerService = Services.GetService<IAppInitializerService>();
_appInitializerService = Services.GetService<IApplicationConfiguration>();
_translationService = Services.GetService<ITranslationService>();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

View File

@@ -521,7 +521,7 @@
Padding="14"
HorizontalAlignment="Right"
VerticalAlignment="Bottom">
<TextBlock Text="{x:Bind ViewModel.ActiveConnectionStatus, Mode=OneWay}" />
<Button Content="{x:Bind ViewModel.ActiveConnectionStatus, Mode=OneWay}" Command="{x:Bind ViewModel.ReconnectServerCommand}" />
</Grid>
</Grid>
</muxc:NavigationView>

View File

@@ -336,8 +336,6 @@
<Compile Include="Services\ApplicationResourceManager.cs" />
<Compile Include="Services\DialogService.cs" />
<Compile Include="Services\LaunchProtocolService.cs" />
<Compile Include="Services\PreferencesService.cs" />
<Compile Include="Services\StatePersistenceService.cs" />
<Compile Include="Services\ToastActivationService.cs" />
<Compile Include="Services\WinoNavigationService.cs" />
<Compile Include="Styles\CommandBarItems.xaml.cs">

View File

@@ -57,6 +57,44 @@
<AppxPackageSigningEnabled>false</AppxPackageSigningEnabled>
<NoWarn>$(NoWarn);NU1702</NoWarn>
<EntryPointProjectUniqueName>..\Wino.Mail\Wino.Mail.csproj</EntryPointProjectUniqueName>
<GenerateAppInstallerFile>False</GenerateAppInstallerFile>
<AppxPackageSigningTimestampDigestAlgorithm>SHA256</AppxPackageSigningTimestampDigestAlgorithm>
<AppxAutoIncrementPackageRevision>False</AppxAutoIncrementPackageRevision>
<AppxPackageDir>C:\Users\bkaan\Desktop\Packages\</AppxPackageDir>
<GenerateTestArtifacts>True</GenerateTestArtifacts>
<AppxBundlePlatforms>x64</AppxBundlePlatforms>
<GenerateTemporaryStoreCertificate>True</GenerateTemporaryStoreCertificate>
<HoursBetweenUpdateChecks>0</HoursBetweenUpdateChecks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<AppxBundle>Always</AppxBundle>
</PropertyGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
@@ -115,6 +153,7 @@
<Content Include="Images\Wide310x150Logo.scale-150.png" />
<Content Include="Images\Wide310x150Logo.scale-200.png" />
<Content Include="Images\Wide310x150Logo.scale-400.png" />
<None Include="Package.StoreAssociation.xml" />
</ItemGroup>
<Import Project="$(WapProjPath)\Microsoft.DesktopBridge.targets" />
<ItemGroup>

View File

@@ -1,9 +1,15 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using H.NotifyIcon;
using Microsoft.Extensions.DependencyInjection;
using Windows.Storage;
using Wino.Core;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Services;
using Wino.Core.UWP.Services;
using Wino.Services;
namespace Wino.Server
{
@@ -16,6 +22,7 @@ namespace Wino.Server
/// </summary>
public partial class App : Application
{
private const string NotifyIconResourceKey = "NotifyIcon";
private const string WinoServerAppName = "Wino.Server";
private const string WinoServerActiatedName = "Wino.Server.Activated";
@@ -32,18 +39,42 @@ namespace Wino.Server
var services = new ServiceCollection();
services.AddTransient<ServerContext>();
services.AddTransient<TrayIconViewModel>();
services.AddTransient<ServerViewModel>();
services.RegisterCoreServices();
// 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>();
return services.BuildServiceProvider();
}
private async Task<ServerViewModel> InitializeNewServerAsync()
{
// TODO: Error handling.
var databaseService = Services.GetService<IDatabaseService>();
var applicationFolderConfiguration = Services.GetService<IApplicationConfiguration>();
applicationFolderConfiguration.ApplicationDataFolderPath = ApplicationData.Current.LocalFolder.Path;
applicationFolderConfiguration.PublisherSharedFolderPath = ApplicationData.Current.GetPublisherCacheFolder(ApplicationConfiguration.SharedFolderName).Path;
await databaseService.InitializeAsync();
var serverViewModel = Services.GetRequiredService<ServerViewModel>();
await serverViewModel.InitializeAsync();
return serverViewModel;
}
protected override async void OnStartup(StartupEventArgs e)
{
bool isCreatedNew;
_mutex = new Mutex(true, WinoServerAppName, out isCreatedNew);
_mutex = new Mutex(true, WinoServerAppName, out bool isCreatedNew);
_eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, WinoServerActiatedName);
if (isCreatedNew)
@@ -57,7 +88,7 @@ namespace Wino.Server
Current.Dispatcher.BeginInvoke(async () =>
{
if (notifyIcon.DataContext is TrayIconViewModel trayIconViewModel)
if (notifyIcon.DataContext is ServerViewModel trayIconViewModel)
{
await trayIconViewModel.ReconnectAsync();
}
@@ -73,18 +104,16 @@ namespace Wino.Server
base.OnStartup(e);
var serverViewModel = await InitializeNewServerAsync();
// Create taskbar icon for the new server.
notifyIcon = (TaskbarIcon)FindResource("NotifyIcon");
var viewModel = Services.GetRequiredService<TrayIconViewModel>();
await viewModel.Context.InitializeAsync();
notifyIcon.DataContext = viewModel;
notifyIcon = (TaskbarIcon)FindResource(NotifyIconResourceKey);
notifyIcon.DataContext = serverViewModel;
notifyIcon.ForceCreate(enablesEfficiencyMode: true);
}
else
{
// Notify other instance so it could bring itself to foreground.
// Notify other instance so it could reconnect to UWP app if needed.
_eventWaitHandle.Set();
// Terminate this instance.

View File

@@ -1,44 +1,84 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Windows.ApplicationModel;
using Windows.ApplicationModel.AppService;
using Windows.Foundation.Collections;
using Wino.Core.Authenticators;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Synchronization;
using Wino.Core.Integration.Processors;
using Wino.Core.Services;
using Wino.Core.Synchronizers;
using Wino.Messaging;
using Wino.Messaging.Enums;
using Wino.Messaging.Server;
namespace Wino.Server
{
public class ServerContext : IInitializeAsync
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>
{
private static object connectionLock = new object();
private AppServiceConnection connection = null;
private readonly IDatabaseService _databaseService;
public ServerContext(IDatabaseService databaseService)
private readonly IDatabaseService _databaseService;
private readonly IApplicationConfiguration _applicationFolderConfiguration;
public ServerContext(IDatabaseService databaseService, IApplicationConfiguration applicationFolderConfiguration)
{
_databaseService = databaseService;
_applicationFolderConfiguration = applicationFolderConfiguration;
WeakReferenceMessenger.Default.RegisterAll(this);
}
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.
#region Message Handlers
try
{
return Package.Current.Id.FamilyName;
}
catch (Exception)
{
return "Debug.Wino.Server.FamilyName";
}
}
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);
#endregion
/// <summary>
/// Open connection to UWP app service
/// </summary>
@@ -65,6 +105,51 @@ namespace Wino.Server
}
}
public async Task TestOutlookSynchronizer()
{
var accountService = App.Current.Services.GetService<IAccountService>();
var accs = await accountService.GetAccountsAsync();
var acc = accs.ElementAt(0);
var authenticator = App.Current.Services.GetService<OutlookAuthenticator>();
var processor = App.Current.Services.GetService<IOutlookChangeProcessor>();
var sync = new OutlookSynchronizer(acc, authenticator, processor);
var options = new SynchronizationOptions()
{
AccountId = acc.Id,
Type = Core.Domain.Enums.SynchronizationType.Full
};
var result = await sync.SynchronizeAsync(options);
}
/// <summary>
/// Disposes current connection to UWP app service.
/// </summary>
private void DisposeConnection()
{
lock (connectionLock)
{
if (connection == null) return;
connection.RequestReceived -= OnWinRTMessageReceived;
connection.ServiceClosed -= OnConnectionClosed;
connection.Dispose();
connection = null;
}
}
/// <summary>
/// Sends a serialized object to UWP application if connection exists with given type.
/// </summary>
/// <param name="messageType">Type of the message.</param>
/// <param name="message">IServerMessage object that will be serialized.</param>
/// <returns></returns>
/// <exception cref="ArgumentException">When the message is not IServerMessage.</exception>
private async Task SendMessageAsync(MessageType messageType, object message)
{
if (connection == null) return;
@@ -81,6 +166,7 @@ namespace Wino.Server
{ MessageConstants.MessageDataTypeKey, message.GetType().Name }
};
Debug.WriteLine($"S: {messageType} ({message.GetType().Name})");
await connection.SendMessageAsync(set);
}
@@ -98,26 +184,38 @@ namespace Wino.Server
private void OnWinRTMessageReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
// TODO: Handle incoming messages from UWP/WINUI Application.
}
private void DisposeConnection()
#region Init
private string GetAppPackagFamilyName()
{
lock (connectionLock)
// 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
{
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";
}
}
public async Task InitializeAsync()
{
await InitializeAppServiceConnectionAsync();
await _databaseService.InitializeAsync();
}
#endregion
}
}

View File

@@ -2,22 +2,23 @@
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Wino.Core.Domain.Interfaces;
namespace Wino.Server
{
public partial class TrayIconViewModel : ObservableObject
public partial class ServerViewModel : ObservableObject, IInitializeAsync
{
public ServerContext Context { get; }
public TrayIconViewModel(ServerContext serverContext)
public ServerViewModel(ServerContext serverContext)
{
Context = serverContext;
}
[RelayCommand]
public void LaunchWino()
public async Task LaunchWinoAsync()
{
await Context.TestOutlookSynchronizer();
// ServerContext.SendTestMessageAsync();
}
@@ -33,5 +34,7 @@ namespace Wino.Server
}
public async Task ReconnectAsync() => await Context.InitializeAppServiceConnectionAsync();
public Task InitializeAsync() => Context.InitializeAppServiceConnectionAsync();
}
}

View File

@@ -16,6 +16,12 @@
<ItemGroup>
<None Remove="Images\Wino_Icon.ico" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Wino.Core.UWP\Services\ConfigurationService.cs" Link="Services\ConfigurationService.cs" />
<Compile Include="..\Wino.Core.UWP\Services\NativeAppService.cs" Link="Services\NativeAppService.cs" />
<Compile Include="..\Wino.Core.UWP\Services\NotificationBuilder.cs" Link="Services\NotificationBuilder.cs" />
<Compile Include="..\Wino.Core.UWP\Services\PreferencesService.cs" Link="Services\PreferencesService.cs" />
</ItemGroup>
<ItemGroup>
<Resource Include="Images\Wino_Icon.ico">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
@@ -30,4 +36,7 @@
<ProjectReference Include="..\Wino.Core\Wino.Core.csproj" />
<ProjectReference Include="..\Wino.Messages\Wino.Messaging.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
</Project>