-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcs2-store-voucher.cs
266 lines (211 loc) · 9.58 KB
/
cs2-store-voucher.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Admin;
using StoreApi;
using MySqlConnector;
using System.Text.Json.Serialization;
public class Store_VoucherConfig : BasePluginConfig
{
[JsonPropertyName("max_vouchers_per_command")]
public int MaxVouchersPerCommand { get; set; } = 20;
[JsonPropertyName("generate_voucher_admin_only")]
public bool GenerateVoucherAdminOnly { get; set; } = true;
[JsonPropertyName("generate_voucher_admin_flag")]
public string GenerateVoucherAdminFlag { get; set; } = "@css/generic";
[JsonPropertyName("skip_credit_check_flag_enabled")]
public bool SkipCreditCheckFlagEnabled { get; set; } = true;
[JsonPropertyName("skip_credit_check_flag")]
public string SkipCreditCheckFlag { get; set; } = "@css/slay";
[JsonPropertyName("print_to_server_console")]
public bool PrintToServerConsole { get; set; } = false;
[JsonPropertyName("print_to_client_console")]
public bool PrintToClientConsole { get; set; } = true;
[JsonPropertyName("generate_voucher_commands")]
public List<string> GenerateVoucherCommands { get; set; } = ["generate_voucher"];
[JsonPropertyName("use_voucher_commands")]
public List<string> UseVoucherCommands { get; set; } = ["use_voucher", "voucher"];
[JsonPropertyName("database_host")]
public string DatabaseHost { get; set; } = "localhost";
[JsonPropertyName("database_port")]
public int DatabasePort { get; set; } = 3306;
[JsonPropertyName("database_name")]
public string DatabaseName { get; set; } = "name";
[JsonPropertyName("database_user")]
public string DatabaseUser { get; set; } = "root";
[JsonPropertyName("database_password")]
public string DatabasePassword { get; set; } = "password";
}
public class Store_Voucher : BasePlugin, IPluginConfig<Store_VoucherConfig>
{
public override string ModuleName => "Store Module [Voucher]";
public override string ModuleVersion => "0.2.0";
public override string ModuleAuthor => "Nathy";
public IStoreApi? StoreApi { get; set; }
public Store_VoucherConfig Config { get; set; } = new();
public override void OnAllPluginsLoaded(bool hotReload)
{
StoreApi = IStoreApi.Capability.Get() ?? throw new Exception("StoreApi could not be located.");
InitializeDatabase();
CreateCommands();
}
public void OnConfigParsed(Store_VoucherConfig config)
{
Config = config;
}
private void CreateCommands()
{
foreach (var cmd in Config.GenerateVoucherCommands)
{
AddCommand($"css_{cmd}", "Generate vouchers", Command_GenerateVoucher);
}
foreach (var cmd in Config.UseVoucherCommands)
{
AddCommand($"css_{cmd}", "Use a voucher", Command_UseVoucher);
}
}
[CommandHelper(minArgs: 2, usage: "<quantity> <credits_per_voucher>")]
public void Command_GenerateVoucher(CCSPlayerController? player, CommandInfo info)
{
if (player == null) return;
if (StoreApi == null) throw new Exception("StoreApi could not be located.");
if (Config.GenerateVoucherAdminOnly && !AdminManager.PlayerHasPermissions(player, Config.GenerateVoucherAdminFlag))
{
info.ReplyToCommand(Localizer["Prefix"] + Localizer["No permission to generate voucher"]);
return;
}
int quantity = int.Parse(info.GetArg(1));
int creditsPerVoucher = int.Parse(info.GetArg(2));
if (quantity > Config.MaxVouchersPerCommand)
{
info.ReplyToCommand(Localizer["Prefix"] + Localizer["Maximum vouchers per command exceeded", Config.MaxVouchersPerCommand]);
return;
}
bool skipCreditCheck = Config.SkipCreditCheckFlagEnabled && AdminManager.PlayerHasPermissions(player, Config.SkipCreditCheckFlag);
if (!skipCreditCheck)
{
int totalCost = quantity * creditsPerVoucher;
if (StoreApi.GetPlayerCredits(player) < totalCost)
{
info.ReplyToCommand(Localizer["Prefix"] + Localizer["Not enough credits"]);
return;
}
}
GenerateVouchers(player, quantity, creditsPerVoucher, info, skipCreditCheck);
}
[CommandHelper(minArgs: 1, usage: "<voucher_code>")]
public void Command_UseVoucher(CCSPlayerController? player, CommandInfo info)
{
if (player == null) return;
if (StoreApi == null) throw new Exception("StoreApi could not be located.");
UseVoucher(player, info.GetArg(1), info);
}
private void GenerateVouchers(CCSPlayerController player, int quantity, int creditsPerVoucher, CommandInfo info, bool skipCreditCheck)
{
if (StoreApi == null) throw new Exception("StoreApi could not be located.");
if (!skipCreditCheck)
{
int totalCost = quantity * creditsPerVoucher;
StoreApi.GivePlayerCredits(player, -totalCost);
}
using (var connection = new MySqlConnection(GetConnectionString()))
{
connection.Open();
for (int i = 0; i < quantity; i++)
{
string voucherCode = GenerateVoucherCode();
string insertQuery = @"
INSERT INTO store_vouchers (SteamID, VoucherCode, Credits)
VALUES (@SteamID, @VoucherCode, @Credits)";
using (var command = new MySqlCommand(insertQuery, connection))
{
command.Parameters.AddWithValue("@SteamID", player.SteamID.ToString());
command.Parameters.AddWithValue("@VoucherCode", voucherCode);
command.Parameters.AddWithValue("@Credits", creditsPerVoucher);
command.ExecuteNonQuery();
}
player.PrintToChat(Localizer["Prefix"] + Localizer["Generated voucher", voucherCode, creditsPerVoucher]);
if (Config.PrintToClientConsole)
{
player.PrintToConsole($"{voucherCode}");
}
if (Config.PrintToServerConsole)
{
Console.WriteLine($"{voucherCode}");
}
}
}
}
private void UseVoucher(CCSPlayerController player, string voucherCode, CommandInfo info)
{
if (StoreApi == null) throw new Exception("StoreApi could not be located.");
using (var connection = new MySqlConnection(GetConnectionString()))
{
connection.Open();
string query = "SELECT Credits FROM store_vouchers WHERE VoucherCode = @VoucherCode";
using (var command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@VoucherCode", voucherCode);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
int credits = reader.GetInt32("Credits");
reader.Close();
string deleteQuery = "DELETE FROM store_vouchers WHERE VoucherCode = @VoucherCode";
using (var deleteCommand = new MySqlCommand(deleteQuery, connection))
{
deleteCommand.Parameters.AddWithValue("@VoucherCode", voucherCode);
deleteCommand.ExecuteNonQuery();
}
StoreApi.GivePlayerCredits(player, credits);
player.PrintToChat(Localizer["Prefix"] + Localizer["Voucher redeemed successfully", credits]);
}
else
{
info.ReplyToCommand(Localizer["Prefix"] + Localizer["Invalid or already used"]);
}
}
}
}
}
private string GenerateVoucherCode()
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var code = new string(Enumerable.Repeat(chars, 16)
.Select(s => s[random.Next(s.Length)]).ToArray());
return $"{code.Substring(0, 4)}-{code.Substring(4, 4)}-{code.Substring(8, 4)}-{code.Substring(12, 4)}";
}
private void InitializeDatabase()
{
using (var connection = new MySqlConnection(GetConnectionString()))
{
connection.Open();
string createTableQuery = @"
CREATE TABLE IF NOT EXISTS store_vouchers (
id INT AUTO_INCREMENT PRIMARY KEY,
SteamID VARCHAR(255),
VoucherCode VARCHAR(255),
Credits INT
)";
using (var command = new MySqlCommand(createTableQuery, connection))
{
command.ExecuteNonQuery();
}
}
}
private string GetConnectionString()
{
var builder = new MySqlConnectionStringBuilder
{
Server = Config.DatabaseHost,
Port = (uint)Config.DatabasePort,
Database = Config.DatabaseName,
UserID = Config.DatabaseUser,
Password = Config.DatabasePassword
};
return builder.ConnectionString;
}
}