Switching project to C# (because why not)

This commit is contained in:
Aurélie Delhaie
2022-05-19 18:49:04 +02:00
commit b013815a96
44 changed files with 18946 additions and 0 deletions

View File

@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using OpenSaveCloudClient.Models;
namespace OpenSaveCloudClient.Core
{
public class SaveManager
{
private static SaveManager? instance;
private List<GameSave> saves;
public List<GameSave> Saves { get { return saves; } }
private SaveManager()
{
saves = new List<GameSave>();
Load();
new Thread(() => CleanArchiveFolder()).Start();
}
public static SaveManager GetInstance()
{
if (instance == null)
{
instance = new SaveManager();
}
return instance;
}
public GameSave Create(string name, string path, string coverHash)
{
GameSave gameSave = new GameSave(name, "", path, "", 0);
return gameSave;
}
private void Load()
{
string appdata = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "osc");
string path = Path.Combine(appdata, "games.json");
if (!File.Exists(appdata))
{
Directory.CreateDirectory(appdata);
}
if (File.Exists(path))
{
string json = File.ReadAllText(path);
var res = JsonSerializer.Deserialize<List<GameSave>>(json);
if (res != null)
{
saves = res;
}
}
}
public void Save()
{
string appdata = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "osc");
string path = Path.Combine(appdata, "games.json");
if (!File.Exists(appdata))
{
Directory.CreateDirectory(appdata);
}
string json = JsonSerializer.Serialize(saves);
File.WriteAllText(path, json);
}
private void CleanArchiveFolder()
{
string appdata = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "osc");
string cachePath = Path.Combine(appdata, "cache");
if (Directory.Exists(cachePath))
{
string[] files = Directory.GetFiles(cachePath);
foreach (string file in files)
{
bool exist = false;
foreach (GameSave save in saves)
{
if (save.Uuid == Path.GetFileNameWithoutExtension(file))
{
exist = true;
break;
}
}
if (!exist)
{
File.Delete(Path.Combine(cachePath, file));
}
}
}
}
}
}

View File

@@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using OpenSaveCloudClient.Models.Remote;
using OpenSaveCloudClient.Models;
namespace OpenSaveCloudClient.Core
{
public class ServerConnector
{
private static ServerConnector? instance;
private string? token;
private string? host;
private int port;
private bool bind;
private bool connected;
private ServerInformation? serverInformation;
private Configuration configuration;
public string? Host { get { return host; } }
public int Port { get { return port; } }
public bool Bind { get { return bind; } }
public bool Connected { get { return connected; } }
public ServerInformation? ServerInformation { get { return serverInformation; } }
private ServerConnector()
{
configuration = Configuration.GetInstance();
}
public static ServerConnector GetInstance()
{
if (instance == null)
{
instance = new ServerConnector();
}
return instance;
}
public void BindNewServer(string host, int port)
{
Logout();
if (!host.StartsWith("http://") && !host.StartsWith("https://"))
{
host = "http://" + host;
}
this.host = host;
this.port = port;
GetServerInformation();
}
private void GetServerInformation()
{
try
{
HttpClient client = new();
HttpResponseMessage response = client.GetAsync(string.Format("{0}:{1}/api/v1/system/information", host, port)).Result;
if (response.IsSuccessStatusCode)
{
string responseText = response.Content.ReadAsStringAsync().Result;
serverInformation = JsonSerializer.Deserialize<ServerInformation>(responseText);
if (serverInformation != null)
{
bind = true;
}
}
}
catch (Exception)
{ }
}
public void Login(string username, string password)
{
try
{
HttpClient client = new HttpClient();
string json = JsonSerializer.Serialize(new Credential { Username = username, Password = password });
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(string.Format("{0}:{1}/api/v1/login", host, port), content).Result;
if (response.IsSuccessStatusCode)
{
string responseText = response.Content.ReadAsStringAsync().Result;
AccessToken? accessToken = JsonSerializer.Deserialize<AccessToken>(responseText);
if (accessToken != null)
{
token = accessToken.Token;
connected = true;
SaveToConfig();
}
}
}
catch (Exception)
{ }
}
public void Reconnect()
{
try
{
if (ReloadFromConfiguration())
{
HttpClient client = new HttpClient();
string json = JsonSerializer.Serialize(new AccessToken { Token = token });
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(string.Format("{0}:{1}/api/v1/check/token", host, port), content).Result;
if (response.IsSuccessStatusCode)
{
string responseText = response.Content.ReadAsStringAsync().Result;
TokenValidation? accessToken = JsonSerializer.Deserialize<TokenValidation>(responseText);
if (accessToken != null && accessToken.Valid)
{
connected = true;
SaveToConfig();
}
else
{
Logout();
}
}
}
}
catch (Exception)
{ }
}
private bool ReloadFromConfiguration()
{
string newHost = configuration.GetString("authentication.host", "");
int newPort = configuration.GetInt("authentication.port", 443);
if (string.IsNullOrWhiteSpace(newHost))
{
return false;
}
try
{
string oldToken = configuration.GetString("authentication.token", "");
BindNewServer(newHost, newPort);
if (!bind)
{
return false;
}
if (string.IsNullOrWhiteSpace(oldToken))
{
return false;
}
token = oldToken;
}
catch (Exception)
{
return false;
}
return true;
}
public void Logout()
{
serverInformation = null;
bind = false;
connected = false;
token = "";
configuration.SetValue("authentication.host", null);
configuration.SetValue("authentication.port", null);
configuration.SetValue("authentication.token", null);
configuration.Flush();
}
private void SaveToConfig()
{
configuration.SetValue("authentication.host", host);
configuration.SetValue("authentication.port", port);
configuration.SetValue("authentication.token", token);
configuration.Flush();
}
}
}

View File

@@ -0,0 +1,77 @@
using OpenSaveCloudClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenSaveCloudClient.Core
{
public class TaskManager
{
private static TaskManager instance;
private readonly System.Timers.Timer timer;
private readonly Dictionary<string, AsyncTaskInformation> _tasks;
private readonly Mutex mut;
private TaskManager()
{
_tasks = new Dictionary<string, AsyncTaskInformation>();
mut = new Mutex();
timer = new System.Timers.Timer
{
Interval = 2000
};
timer.Elapsed += timer_Tick;
timer.Start();
}
public static TaskManager GetInstance()
{
if (instance == null)
{
instance = new TaskManager();
}
return instance;
}
public string StartTask(string label, int progressMax)
{
string uuid = Guid.NewGuid().ToString();
_tasks.Add(uuid, new AsyncTaskInformation(label, progressMax));
return uuid;
}
public AsyncTaskInformation GetTask(string uuid)
{
return _tasks[uuid];
}
private void timer_Tick(object? sender, EventArgs e)
{
mut.WaitOne();
try
{
List<string> toDelete = new();
foreach (KeyValuePair<string, AsyncTaskInformation> task in _tasks)
{
if (task.Value.Status == AsyncTaskStatus.Ended)
{
toDelete.Add(task.Key);
}
}
foreach (string uuid in toDelete)
{
_tasks.Remove(uuid);
}
}
finally
{
mut.ReleaseMutex();
}
}
}
}