-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrismCart.cs
146 lines (130 loc) · 4.97 KB
/
PrismCart.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
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using Newtonsoft.Json;
using Oxide.Core.Configuration;
namespace Oxide.Plugins {
[Info("Prism Cart", "Cassanova", "1.0.0")]
public class PrismCart: RustPlugin {
private string apiUrl;
private string apiKey;
private readonly CommandTimer commandTimer = new CommandTimer();
protected override void LoadDefaultMessages() {
lang.RegisterMessages(new Dictionary < string, string > {
["AntiFlood"] = "This command is locked to prevent flooding. Please wait a few seconds.",
["EmptyCart"] = "Your cart is empty.",
["GetSuccess"] = "You have successfully received your items. Thank you!",
["UnknownError"] = "An error occurred while retrieving cart items.",
["PleaseWait"] = "Please wait a moment. We are checking the availability of the order...",
}, this);
lang.RegisterMessages(new Dictionary < string, string > {
["AntiFlood"] = "Ця команда заблокована для запобігання перенавантаження. Будь ласка, зачекайте кілька секунд.",
["EmptyCart"] = "Ваш кошик пустий.",
["GetSuccess"] = "Ви успішно отримали свої товари. Дякуємо!",
["UnknownError"] = "Виникла помилка під час отримання товарів у кошику. Будь ласка, зверніться до адміністрації сервера.",
["PleaseWait"] = "Зачекайте будь ласка. Перевіряємо наявність предметів у кошику...",
}, this, "uk");
}
protected override void LoadDefaultConfig()
{
Config["ApiUrl"] = "http://rustprism.test/api/orders/";
Config["ApiKey"] = "GeGeFqp5xsdAjYJiTxDhARvIozOcVThT";
}
void OnServerInitialized()
{
apiUrl = Config.Get<string>("ApiUrl");
apiKey = Config.Get<string>("ApiKey");
}
[ChatCommand("cart")]
private async Task PrismCartCommand(BasePlayer player, string command, string[] args)
{
if (!commandTimer.CheckCooldown(player))
{
player.ChatMessage(lang.GetMessage("AntiFlood", this, player.UserIDString));
return;
}
player.ChatMessage(lang.GetMessage("PleaseWait", this, player.UserIDString));
string steamId = player.UserIDString;
using(var webClient = new System.Net.WebClient())
{
webClient.Headers.Add("X-API-KEY", apiKey);
try
{
string json = await webClient.DownloadStringTaskAsync(apiUrl + steamId);
var cartItems = JsonConvert.DeserializeObject<List<CartItem>>(json);
if (cartItems == null || !cartItems.Any())
{
player.ChatMessage(lang.GetMessage("EmptyCart", this, player.UserIDString));
return;
}
foreach(var item in cartItems)
{
if (string.IsNullOrEmpty(item.command))
{
Item newItem = ItemManager.CreateByName(item.item, item.quantity);
newItem.MoveToContainer(player.inventory.containerMain);
}
else
{
string commandWithSteamId = item.command.Replace("{playerid}", steamId);
for (int i = 0; i < item.quantity; i++)
{
rust.RunServerCommand(commandWithSteamId);
}
}
}
player.ChatMessage(lang.GetMessage("GetSuccess", this, player.UserIDString));
}
catch (System.Net.WebException ex)
{
var response = ex.Response as System.Net.HttpWebResponse;
if (response != null && response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
player.ChatMessage(lang.GetMessage("EmptyCart", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("UnknownError", this, player.UserIDString));
}
}
}
}
private class CartItem {
public int id {
get;
set;
}
public int quantity {
get;
set;
}
public string item {
get;
set;
}
public string command {
get;
set;
}
}
private class CommandTimer {
private readonly Dictionary < ulong, float > lastCommandTimes = new Dictionary < ulong, float > ();
public int CooldownSeconds {
get;
set;
} = 5;
public bool CheckCooldown(BasePlayer player) {
float lastCommandTime;
if (lastCommandTimes.TryGetValue(player.userID, out lastCommandTime)) {
float timeElapsed = Time.realtimeSinceStartup - lastCommandTime;
if (timeElapsed < CooldownSeconds) {
return false;
}
}
lastCommandTimes[player.userID] = Time.realtimeSinceStartup;
return true;
}
}
}
}