-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStorage.cs
89 lines (78 loc) · 2.69 KB
/
Storage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using Dapper;
using MySqlConnector;
namespace SkyboxChanger;
public class SkyData
{
public ulong SteamID { get; set; }
public string Skybox { get; set; } = "";
public float Brightness { get; set; } = 1.0f;
public int Color { get; set; } = int.MaxValue;
public bool HasSkybox()
{
return Skybox != "";
}
}
public class Storage
{
private string _DbConnString { get; set; }
private string _Table { get; set; } = "";
private List<SkyData> _PlayerStorage { get; set; } = new();
public Storage(string host, int port, string user, string password, string database, string tablePrefix)
{
_DbConnString = $"Host={host};Port={port};User={user};Password={password};Database={database}";
_Table = tablePrefix + "playerstorage";
using MySqlConnection connection = ConnectAsync().Result;
var createTableQuery = $"CREATE TABLE IF NOT EXISTS `{_Table}` ( `steamid` BIGINT NOT NULL, `skybox` VARCHAR(255) NOT NULL, `brightness` FLOAT DEFAULT 1.0, `color` INT NOT NULL, PRIMARY KEY (`steamid`)) ENGINE = InnoDB;";
connection.Execute(createTableQuery);
Load();
}
public async Task<MySqlConnection> ConnectAsync()
{
MySqlConnection connection = new(_DbConnString);
await connection.OpenAsync();
return connection;
}
public void ExecuteAsync(string query, object? parameters)
{
Task.Run(async () =>
{
using MySqlConnection connection = await ConnectAsync();
await connection.ExecuteAsync(query, parameters);
});
}
public void Load()
{
_PlayerStorage.Clear();
using MySqlConnection connection = ConnectAsync().Result;
var result = connection.Query<SkyData>($"SELECT * FROM `{_Table}`;");
_PlayerStorage.AddRange(result);
}
public void Save(ulong? steamid = null)
{
if (steamid == null)
{
foreach (var data in _PlayerStorage)
{
ExecuteAsync($"INSERT INTO `{_Table}` (`steamid`, `skybox`, `brightness`, `color`) VALUES (@SteamID, @Skybox, @Brightness, @Color) ON DUPLICATE KEY UPDATE `skybox` = @Skybox, `brightness` = @Brightness, `color` = @Color;", data);
}
}
else
{
var data = _PlayerStorage.Find((data) => data.SteamID == steamid);
if (data != null)
{
ExecuteAsync($"INSERT INTO `{_Table}` (`steamid`, `skybox`, `brightness`, `color`) VALUES (@SteamID, @Skybox, @Brightness, @Color) ON DUPLICATE KEY UPDATE `skybox` = @Skybox, `brightness` = @Brightness, `color` = @Color;", data);
}
}
}
public SkyData GetPlayerSkydata(ulong steamid)
{
var data = _PlayerStorage.Find((data) => data.SteamID == steamid);
if (data == null)
{
data = new SkyData { SteamID = steamid };
_PlayerStorage.Add(data);
}
return data;
}
}