Skip to content

Commit

Permalink
Merge pull request #67 from BeloMaximka/caching
Browse files Browse the repository at this point in the history
Caching, fixes, collapse hw sections
  • Loading branch information
BeloMaximka authored Apr 23, 2023
2 parents 3cc040e + d11e838 commit 679340f
Show file tree
Hide file tree
Showing 31 changed files with 1,144 additions and 698 deletions.
10 changes: 8 additions & 2 deletions MystatDesktopWpf/Domain/MystatAPISingleton.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
using MystatAPI;
using MystatAPI.Entity;
using MystatDesktopWpf.Services;
using System.Threading.Tasks;

namespace MystatDesktopWpf.Domain
{
internal static class MystatAPISingleton
{
static public MystatAPIClient Client { get; private set; }
static public ProfileInfo? Profile { get; private set; }
static public ProfileInfo ProfileInfo { get; private set; }
static async public Task<MystatAuthResponse> LoginAndGetProfileInfo()
{
var result = await Client.Login();
if (result is MystatAuthSuccess responseSuccess)
Profile = await Client.GetProfileInfo();
{
MystatAPICachingService.Login = Client.LoginData.Username;
ProfileInfo = await MystatAPICachingService.GetAndUpdateCachedProfileInfo();
Client.GroudId = ProfileInfo.CurrentGroupId;
}
return result;
}

static MystatAPISingleton()
{
Client = new MystatAPIClient();
Expand Down
13 changes: 13 additions & 0 deletions MystatDesktopWpf/Languages/lang.en-US.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,17 @@
<v:String x:Key="m_TimezoneDescription">Converting time in a schedule to account for time zones</v:String>
<v:String x:Key="m_TimezoneConvertFrom">Convert from</v:String>
<v:String x:Key="m_TimezoneConvertTo">to</v:String>

<!-- Cache -->
<v:String x:Key="m_Cache">Cache</v:String>
<v:String x:Key="m_CacheSize">Cache size: </v:String>
<v:String x:Key="m_ClearCache">Clear cache</v:String>
<v:String x:Key="m_Cleared">Cleared!</v:String>
<v:String x:Key="m_Clearing">Clearing...</v:String>
<v:String x:Key="m_Calculating">Calculating...</v:String>
<v:String x:Key="m_FailedToClear">Failed to clear!</v:String>

<!-- Windows settings -->
<v:String x:Key="m_WindowsSettings">Windows settings</v:String>
<v:String x:Key="m_RunOnWindowsStartup">Run on Windows startup</v:String>
</ResourceDictionary>
13 changes: 13 additions & 0 deletions MystatDesktopWpf/Languages/lang.ru-RU.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,17 @@
<v:String x:Key="m_TimezoneDescription">Преобразование времени в расписании с учетом часовых поясов</v:String>
<v:String x:Key="m_TimezoneConvertFrom">Преобразовать из</v:String>
<v:String x:Key="m_TimezoneConvertTo">в</v:String>

<!-- Cache -->
<v:String x:Key="m_Cache">Кэш</v:String>
<v:String x:Key="m_CacheSize">Размер кэша: </v:String>
<v:String x:Key="m_ClearCache">Очистить кэш</v:String>
<v:String x:Key="m_Cleared">Очищено!</v:String>
<v:String x:Key="m_Clearing">Очистка...</v:String>
<v:String x:Key="m_Calculating">Вычисление...</v:String>
<v:String x:Key="m_FailedToClear">Не получилось очистить кэш!</v:String>

<!-- Windows settings -->
<v:String x:Key="m_WindowsSettings">Настройки Windows</v:String>
<v:String x:Key="m_RunOnWindowsStartup">Запускать при старте Windows</v:String>
</ResourceDictionary>
13 changes: 13 additions & 0 deletions MystatDesktopWpf/Languages/lang.uk-UA.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,17 @@
<v:String x:Key="m_TimezoneDescription">Перетворення часу в розкладі з урахуванням часових поясів</v:String>
<v:String x:Key="m_TimezoneConvertFrom">Перетворити з</v:String>
<v:String x:Key="m_TimezoneConvertTo">у</v:String>

<!-- Cache -->
<v:String x:Key="m_Cache">Кеш</v:String>
<v:String x:Key="m_CacheSize">Розмір кешу: </v:String>
<v:String x:Key="m_ClearCache">Очистити кеш</v:String>
<v:String x:Key="m_Cleared">Очищено!</v:String>
<v:String x:Key="m_Clearing">Очистка...</v:String>
<v:String x:Key="m_Calculating">Розрахунок...</v:String>
<v:String x:Key="m_FailedToClear">Не вдалося очистити!</v:String>

<!-- Windows settings -->
<v:String x:Key="m_WindowsSettings">Налаштування Windows</v:String>
<v:String x:Key="m_RunOnWindowsStartup">Запускати під час старту Windows</v:String>
</ResourceDictionary>
12 changes: 12 additions & 0 deletions MystatDesktopWpf/MystatDesktopWpf.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@
<None Remove="Resources\trayicon.ico" />
</ItemGroup>

<ItemGroup>
<COMReference Include="IWshRuntimeLibrary">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>0</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>f935dc20-1cf0-11d0-adb9-00c04fd58a0b</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Hardcodet.NotifyIcon.Wpf" Version="1.1.0" />
<PackageReference Include="MaterialDesignThemes" Version="4.6.1" />
Expand Down
153 changes: 153 additions & 0 deletions MystatDesktopWpf/Services/MystatAPICachingService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
using MystatAPI;
using MystatAPI.Entity;
using MystatDesktopWpf.Domain;
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;

namespace MystatDesktopWpf.Services
{
internal static class MystatAPICachingService
{
private static readonly MystatAPIClient api;
private static string? userCachePath;
private static string rootCachePath;


private static string UserCachePath
{
get
{
if (userCachePath == null) throw new DirectoryNotFoundException("No user directory speficied");
return userCachePath;
}
}
public static string Login
{
set
{
string encodedLogin = Convert.ToBase64String(Encoding.UTF8.GetBytes(value));

userCachePath = Directory.CreateDirectory(
Environment.ExpandEnvironmentVariables(@"%appdata%\Mystat\cache\users\" + encodedLogin)).FullName;
}
}
static MystatAPICachingService()
{
api = MystatAPISingleton.Client;
try
{
Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(@"%appdata%\Mystat"));
Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(@"%appdata%\Mystat\cache"));
rootCachePath = Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(@"%appdata%\Mystat\cache\users")).FullName;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
throw;
}
}

public static async Task<ProfileInfo> GetAndUpdateCachedProfileInfo()
{
string filePath = $"{UserCachePath}\\profileInfo.json";
ProfileInfo? profileInfo = null;
if (File.Exists(filePath))
{
string jsonData = await File.ReadAllTextAsync(filePath);
profileInfo = JsonSerializer.Deserialize<ProfileInfo>(jsonData);
}
profileInfo ??= await api.GetProfileInfo();
CreateUserCacheDir();
UpdateCachedProfileInfo(filePath, profileInfo);
return profileInfo;
}

public static async Task<MystatAPI.Entity.Activity[]?> GetCachedActivities()
{
string filePath = $"{UserCachePath}\\activities.json";
MystatAPI.Entity.Activity[]? activities = null;
if (File.Exists(filePath))
{
string jsonData = await File.ReadAllTextAsync(filePath);
activities = JsonSerializer.Deserialize<MystatAPI.Entity.Activity[]>(jsonData);
}
return activities;
}

public static async void UpdateCachedActivities(MystatAPI.Entity.Activity[] activities)
{
try
{
CreateUserCacheDir();
await File.WriteAllTextAsync($"{UserCachePath}\\activities.json", JsonSerializer.Serialize(activities));
}
catch (Exception)
{
// TODO LOG
}
}

public async static Task<bool> ClearCacheAsync()
{
return await Task.Run(() =>
{
try
{
foreach (var directory in Directory.GetDirectories(rootCachePath))
{
Directory.Delete(directory, true);
}
return true;

}
catch (Exception)
{
return false;
}
});
}

public async static Task<int> GetCacheSize()
{
return await Task.Run(() =>
{
int size = 0;
try
{

foreach (var dir in Directory.GetDirectories(rootCachePath))
{
foreach (var file in Directory.GetFiles(dir))
{
size += file.Length;
}
}
}
catch (Exception) {}
return size;
});
}

private static void CreateUserCacheDir()
{
Directory.CreateDirectory(userCachePath);
}

private async static void UpdateCachedProfileInfo(string path, ProfileInfo? profileInfo = null)
{
try
{
profileInfo ??= await api.GetProfileInfo();
await File.WriteAllTextAsync(path, JsonSerializer.Serialize(profileInfo));
}
catch (Exception)
{
// TODO LOG
}
}
}
}
19 changes: 13 additions & 6 deletions MystatDesktopWpf/Services/SettingsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ internal static class SettingsService
private static readonly string settingsFilePath;
public static Settings Settings { get; private set; }

public static event Action OnSettingsChange;
public static event Action SettingsChanged;

static SettingsService()
{
Expand All @@ -42,11 +42,11 @@ static SettingsService()
}, TaskScheduler.Default);
};

OnSettingsChange += saveDebounced;
Settings.ScheduleNotification.OnPropertyChanged += OnSettingsChange;
Settings.Theme.OnPropertyChanged += OnSettingsChange;
Settings.Tray.OnPropertyChanged += OnSettingsChange;
Settings.TimezoneConvertion.OnPropertyChanged += OnSettingsChange;
SettingsChanged += saveDebounced;
Settings.ScheduleNotification.OnPropertyChanged += SettingsChanged;
Settings.Theme.OnPropertyChanged += SettingsChanged;
Settings.Tray.OnPropertyChanged += SettingsChanged;
Settings.TimezoneConvertion.OnPropertyChanged += SettingsChanged;
}

public static Settings? Load()
Expand Down Expand Up @@ -120,6 +120,11 @@ public static bool SetPropertyValue(string property, object? value)
return true;
}

public static void OnSettingsChange()
{
SettingsChanged.Invoke();
}

private static string EncpyptPassword(string password)
{
StringBuilder newPass = new();
Expand Down Expand Up @@ -169,5 +174,7 @@ то мы ставим анлийский*/
public TimezoneSubSettings TimezoneConvertion { get; set; } = new();
public bool AutoLessonEvaluationEnabled { get; set; } = false;
public string Language { get; set; }

public bool[] HomeworkSectionExpandedStates { get; set; } = { true, true, true, true, true };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private void UpdateFileInfo()
fileLine.Visibility = Visibility.Visible;

string extension = Path.GetExtension(files[0]);
if (files?.Length != 1 || extension == ".txt" || extension == ".csv")
if (files?.Length != 1 || extension == ".txt" || extension == ".csv" || Directory.Exists(files[0]))
{
Archive = true;
fileTextBox.Visibility = Visibility.Visible;
Expand Down
Loading

0 comments on commit 679340f

Please sign in to comment.