Skip to content

Commit

Permalink
Merge pull request #214 from stayintarkov/More-Improvements
Browse files Browse the repository at this point in the history
More improvements
  • Loading branch information
artehe authored Apr 27, 2024
2 parents a4f1b55 + f59079c commit 92f6886
Show file tree
Hide file tree
Showing 12 changed files with 125 additions and 63 deletions.
6 changes: 1 addition & 5 deletions SIT.Manager/Interfaces/ICachingService.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
using SIT.Manager.Services.Caching;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SIT.Manager.Interfaces;

public interface ICachingService
{
public ICachingProvider InMemory { get; }
Expand Down
1 change: 1 addition & 0 deletions SIT.Manager/Localization/en-US.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@
<!-- Install - Configure Sit View Model -->
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorTitle">Location Selection Error</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorDescription">You've selected the same folder as the BSG install of EFT, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionSPTErrorDescription">You've selected the same folder as an existing SPT install, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorOk">Ok</system:String>

<!-- Install - Install View -->
Expand Down
1 change: 1 addition & 0 deletions SIT.Manager/Localization/ru-RU.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@
<!-- Install - Configure Sit View Model -->
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorTitle">Ошибка выбора местоположения</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorDescription">Вы выбрали ту же папку, что и установка BSG EFT, выберите другое местоположение для установки SIT</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionSPTErrorDescription">You've selected the same folder as an existing SPT install, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorOk">Ок</system:String>

<!-- Install - Install View -->
Expand Down
1 change: 1 addition & 0 deletions SIT.Manager/Localization/uk-UA.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@
<!-- Install - Configure Sit View Model -->
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorTitle">Помилка вибору місця розташування</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorDescription">Ви вибрали ту саму теку, що і встановлення BSG EFT, оберіть інше місце для встановлення SIT</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionSPTErrorDescription">You've selected the same folder as an existing SPT install, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorOk">Ok</system:String>

<!-- Install - Install View -->
Expand Down
1 change: 1 addition & 0 deletions SIT.Manager/Localization/zh-CN.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@
<!-- Install - Configure Sit View Model -->
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorTitle">位置选择错误</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorDescription">您选择了与 BSG EFT 安装相同的目录,请选择另一个位置以安装 SIT</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionSPTErrorDescription">You've selected the same folder as an existing SPT install, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorOk">好的</system:String>

<!-- Install - Install View -->
Expand Down
1 change: 1 addition & 0 deletions SIT.Manager/Localization/zh-HK.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@
<!-- Install - Configure Sit View Model -->
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorTitle">位置選擇錯誤</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorDescription">您選擇了與 BSG EFT 安裝相同的目錄,請選擇另一個位置以安裝 SIT</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionSPTErrorDescription">You've selected the same folder as an existing SPT install, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorOk">好的</system:String>

<!-- Install - Install View -->
Expand Down
1 change: 1 addition & 0 deletions SIT.Manager/Localization/zh-TW.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@
<!-- Install - Configure Sit View Model -->
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorTitle">位置選擇錯誤</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorDescription">您選擇了與 BSG EFT 安裝相同的目錄,請選擇另一個位置以安裝 SIT</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionSPTErrorDescription">You've selected the same folder as an existing SPT install, please choose a different location to install SIT to</system:String>
<system:String x:Key="ConfigureSitViewModelLocationSelectionErrorOk">好的</system:String>

<!-- Install - Install View -->
Expand Down
7 changes: 1 addition & 6 deletions SIT.Manager/Services/Caching/CachingService.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using SIT.Manager.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SIT.Manager.Services.Caching;

public class CachingService(IServiceProvider provider) : ICachingService
{
private const string CACHE_PATH = "Cache";
Expand Down
100 changes: 51 additions & 49 deletions SIT.Manager/Services/Caching/OnDiskCachingProvider.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using Avalonia.Controls.ApplicationLifetimes;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using PeNet;
using SIT.Manager.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand All @@ -12,6 +9,7 @@
using System.Text.Json;

namespace SIT.Manager.Services.Caching;

internal class OnDiskCachingProvider(string cachePath, ILogger<OnDiskCachingProvider> logger) : CachingProviderBase(cachePath)
{
private const string RESTORE_FILE_NAME = "fileCache.dat";
Expand All @@ -20,10 +18,10 @@ internal class OnDiskCachingProvider(string cachePath, ILogger<OnDiskCachingProv

protected override void RemoveExpiredKey(string key)
{
if(_cacheMap.TryGetValue(key, out CacheEntry? cacheEntry))
if (_cacheMap.TryGetValue(key, out CacheEntry? cacheEntry))
{
string cacheFilePath = cacheEntry.GetValue<string>() ?? string.Empty;
if(File.Exists(cacheFilePath))
if (File.Exists(cacheFilePath))
File.Delete(cacheFilePath);
}
base.RemoveExpiredKey(key);
Expand Down Expand Up @@ -53,28 +51,30 @@ public override bool Add<T>(string key, T value, TimeSpan? expiryTime = null)

string filename = MD5.HashData(Encoding.UTF8.GetBytes(key)).ToHexString();
string filePath = Path.Combine(_cachePath.FullName, filename);
using FileStream fs = File.OpenWrite(filePath);
if (value is Stream inputStream)
{
if (inputStream.CanSeek)
inputStream.Seek(0, SeekOrigin.Begin);

inputStream.CopyTo(fs);
}
else
using (FileStream fs = File.OpenWrite(filePath))
{
byte[] buffer;
if (typeof(T) == typeof(byte[]))
if (value is Stream inputStream)
{
buffer = value as byte[] ?? [];
if (inputStream.CanSeek)
inputStream.Seek(0, SeekOrigin.Begin);

inputStream.CopyTo(fs);
}
else
{
string serializedData = JsonSerializer.Serialize(value);
buffer = Encoding.UTF8.GetBytes(serializedData);
}
byte[] buffer;
if (typeof(T) == typeof(byte[]))
{
buffer = value as byte[] ?? [];
}
else
{
string serializedData = JsonSerializer.Serialize(value);
buffer = Encoding.UTF8.GetBytes(serializedData);
}

fs.Write(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
}

DateTime expiryDate = DateTime.UtcNow + (expiryTime ?? TimeSpan.FromMinutes(15));
Expand Down Expand Up @@ -107,41 +107,43 @@ public override CacheValue<T> Get<T>(string key)
return CacheValue<T>.Null;

Type tType = typeof(T);
FileStream fs = File.OpenRead(filePath);
if (tType == typeof(FileStream))
using (FileStream fs = File.OpenRead(filePath))
{
return new CacheValue<T>((T) (object) fs, true);
}

byte[] fileBytes;
MemoryStream ms = new MemoryStream();
try
{
byte[] buffer = new byte[1024 * 8];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
if (tType == typeof(FileStream))
{
ms.Write(buffer, 0, bytesRead);
return new CacheValue<T>((T) (object) fs, true);
}

fileBytes = ms.ToArray();
if (tType == typeof(byte[]))
byte[] fileBytes;
MemoryStream ms = new MemoryStream();
try
{
return new CacheValue<T>((T) (object) fileBytes, true);
byte[] buffer = new byte[1024 * 8];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}

fileBytes = ms.ToArray();
if (tType == typeof(byte[]))
{
return new CacheValue<T>((T) (object) fileBytes, true);
}
}
catch (Exception ex)
{
ms.Dispose();
_logger.LogError(ex, "Error occured during reading or casting file bytes.");
return CacheValue<T>.Null;
}
}
catch (Exception ex)
{
ms.Dispose();
_logger.LogError(ex, "Error occured during reading or casting file bytes.");
return CacheValue<T>.Null;
}

if (tType == typeof(string))
{
return new CacheValue<T>((T) (object) Encoding.UTF8.GetString(fileBytes), true);
if (tType == typeof(string))
{
return new CacheValue<T>((T) (object) Encoding.UTF8.GetString(fileBytes), true);
}
return new CacheValue<T>(JsonSerializer.Deserialize<T>(fileBytes), true);
}
return new CacheValue<T>(JsonSerializer.Deserialize<T>(fileBytes), true);
}
catch (Exception ex)
{
Expand Down
40 changes: 39 additions & 1 deletion SIT.Manager/ViewModels/Installation/ConfigureSitViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

Expand Down Expand Up @@ -80,6 +81,7 @@ private async Task ChangeEftInstallLocation()
IStorageFolder? directorySelected = await _pickerDialogService.GetDirectoryFromPickerAsync();
if (directorySelected != null)
{
bool usingInvalidLocatiion = false;
if (directorySelected.Path.LocalPath == CurrentInstallProcessState.BsgInstallPath)
{
// Using the same location as the current BSG install and we don't want this the same as the SIT install.
Expand All @@ -89,8 +91,22 @@ private async Task ChangeEftInstallLocation()
Content = _localizationService.TranslateSource("ConfigureSitViewModelLocationSelectionErrorDescription"),
PrimaryButtonText = _localizationService.TranslateSource("ConfigureSitViewModelLocationSelectionErrorOk")
}.ShowAsync();
usingInvalidLocatiion = true;
}
else

if (HasSelectedSPTInstallPath(directorySelected.Path.LocalPath))
{
// Using the same location as an existing SPT install and we don't want this the same as the SIT install.
await new ContentDialog()
{
Title = _localizationService.TranslateSource("ConfigureSitViewModelLocationSelectionErrorTitle"),
Content = _localizationService.TranslateSource("ConfigureSitViewModelLocationSelectionSPTErrorDescription"),
PrimaryButtonText = _localizationService.TranslateSource("ConfigureSitViewModelLocationSelectionErrorOk")
}.ShowAsync();
usingInvalidLocatiion = true;
}

if (!usingInvalidLocatiion)
{
CurrentInstallProcessState.EftInstallPath = directorySelected.Path.LocalPath;
OverridenBsgInstallPath = true;
Expand Down Expand Up @@ -163,6 +179,21 @@ private async Task FetchVersionAndMirrorMatrix()
ValidateConfiguration();
}

/// <summary>
/// Check if the currently selected EFT diretory has indicators of an SPT install and if so return true, otherwise return false
/// </summary>
/// <returns>True if this is an SPT install directory otherwise false</returns>
private bool HasSelectedSPTInstallPath(string requestedDirectory)
{
string sptLauncherPath = Path.Combine(requestedDirectory, "Aki.Launcher.exe");
string sptServerPath = Path.Combine(requestedDirectory, "Aki.Server.exe");
if (File.Exists(sptLauncherPath) || File.Exists(sptServerPath))
{
return true;
}
return false;
}

[RelayCommand]
private void Back()
{
Expand All @@ -175,6 +206,7 @@ private void Start()
ProgressInstall();
}

// TODO convert this view model into some kind of validator or something to make this part shorter and easier to handle
private void ValidateConfiguration()
{
IsConfigurationValid = true;
Expand Down Expand Up @@ -211,6 +243,12 @@ private void ValidateConfiguration()
IsConfigurationValid = false;
return;
}

if (HasSelectedSPTInstallPath(CurrentInstallProcessState.EftInstallPath))
{
IsConfigurationValid = false;
return;
}
}

private async Task LoadAvailableModsList()
Expand Down
27 changes: 26 additions & 1 deletion SIT.Manager/ViewModels/PlayPageViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using SIT.Manager.Interfaces;
using SIT.Manager.Models.Aki;
using SIT.Manager.Models.Play;
using SIT.Manager.Services.Caching;
using SIT.Manager.Views.Play;
using System;

Expand All @@ -13,16 +15,39 @@ public partial class PlayPageViewModel : ObservableRecipient,
IRecipient<ConnectedServerRequestMessage>,
IRecipient<ServerDisconnectMessage>
{
private const string SELECTED_TAB_INDEX_CACHE_KEY = "LastSelectedPlayPageTabIndex";

private readonly ICachingService _cachingService;

private AkiServer? _connectedServer;

[ObservableProperty]
private UserControl _playControl;

public PlayPageViewModel()
[ObservableProperty]
private int _selectedTabIndex = 0;

public PlayPageViewModel(ICachingService cachingService)
{
_cachingService = cachingService;

if (_cachingService.OnDisk.TryGet(SELECTED_TAB_INDEX_CACHE_KEY, out CacheValue<int> indexValue))
{
SelectedTabIndex = indexValue.Value;
}

PlayControl = new ServerSelectionView();
}

partial void OnSelectedTabIndexChanged(int value)
{
if (_cachingService.OnDisk.Exists(SELECTED_TAB_INDEX_CACHE_KEY))
{
_cachingService.OnDisk.Remove(SELECTED_TAB_INDEX_CACHE_KEY);
}
_cachingService.OnDisk.Add(SELECTED_TAB_INDEX_CACHE_KEY, value);
}

public void Receive(ServerConnectMessage message)
{
_connectedServer = message.Value;
Expand Down
2 changes: 1 addition & 1 deletion SIT.Manager/Views/PlayPage.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:DataType="vm:PlayPageViewModel"
x:Class="SIT.Manager.Views.PlayPage">
<TabControl Margin="2">
<TabControl Margin="2" SelectedIndex="{Binding SelectedTabIndex}">
<TabItem Header="{DynamicResource PlayPageBookmarksTabHeader}">
<ContentControl Content="{Binding PlayControl}"/>
</TabItem>
Expand Down

0 comments on commit 92f6886

Please sign in to comment.