-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuildBlocker.cs
369 lines (327 loc) · 13.1 KB
/
BuildBlocker.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//Written so that permissions block placement of the specific deployable when granted. There are just too many permissions to grant for placement
//If you want it to be permissions for placement, change the if permission.UserHasPermission to include ! after the bracket but before permission inside CanBuild
//Will rewrite soon, I know its a bit long but it works as intended.
//Good example of a self populating, permissions creating config file
using System;
using System.Collections.Generic;
using System.IO;
using Oxide.Core.Plugins;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Build Blocker", "Tacman", "1.0.0")]
[Description("Prevent building of specified entities by permission")]
public class BuildBlocker : RustPlugin
{
#region Config
private static Configuration config;
public class Configuration
{
[JsonProperty(PropertyName = "Permissions")]
public Dictionary<string, string> Permissions { get; set; } = new Dictionary<string, string>();
public static Configuration DefaultConfig()
{
return new Configuration();
}
}
//We create the config template here, with only a permissions dictionary.
protected override void LoadConfig()
{
base.LoadConfig();
try
{
config = Config.ReadObject<Configuration>() ?? Configuration.DefaultConfig();
ValidateConfig();
PopulateConfig();
SaveConfig();
}
catch (Exception ex)
{
Debug.LogException(ex);
PrintWarning("Error loading configuration. Creating new configuration file.");
LoadDefaultConfig();
}
}
//Create an empty permissions template
protected override void LoadDefaultConfig()
{
config = Configuration.DefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
try
{
Config.WriteObject(config, true);
Puts("Configuration saved successfully.");
}
catch (Exception ex)
{
PrintWarning($"Error saving configuration: {ex.Message}");
}
}
//Ensure that the config is not broken before proceeding to use it.
private void ValidateConfig()
{
if (config.Permissions == null)
{
config.Permissions = new Dictionary<string, string>();
}
}
//Creating the permissions here from the specified categories, if the items are deployable.
private void PopulateConfig()
{
if (ItemManager.itemList == null || ItemManager.itemList.Count == 0)
{
Puts("ItemManager.itemList is null or empty. Cannot populate config.");
return;
}
var newPermissions = new Dictionary<string, string>();
bool hasNewPermissions = false;
//foreach loop to find the items to register permissions with
foreach (var itemDefinition in ItemManager.itemList)
{
if (IsBlacklisted(itemDefinition.shortname))
{
//Puts($"Skipping blacklisted item: {itemDefinition.shortname}");
continue;
}
if (IsDeployable(itemDefinition))
{
string shortName = itemDefinition.shortname;
string prefabName = SanitizeDisplayName(itemDefinition.displayName?.english ?? shortName);
string permissionName = $"buildblocker.{prefabName}";
if (!config.Permissions.ContainsKey(shortName))
{
newPermissions[shortName] = permissionName;
hasNewPermissions = true;
Puts($"Added new permission for item '{shortName}' with permission '{permissionName}'.");
}
}
else
{
//Do nothing here, added this to see if deployable check was working correctly
//Puts($"Item '{itemDefinition.shortname}' is not deployable.");
}
}
if (hasNewPermissions)
{
foreach (var kvp in newPermissions)
{
config.Permissions[kvp.Key] = kvp.Value;
}
SaveConfig();
Puts("Config updated with new deployable item permissions.");
}
else
{
Puts("No new permissions to add.");
}
}
//Hardcoded blacklist. This is done to prevent the config becoming too cluttered.
private bool IsBlacklisted(string shortName)
{
//Blacklisted Items (hardcoded to not clutter config)
var blacklist = new HashSet<string>
{
"wiretool",
"pipetool",
"hosetool",
"attackhelicopter",
"motorbike",
"motorbike_sidecar",
"bicycle",
"trike",
"kayak",
"rhib",
"rowboat",
"tugboat",
"minihelicopter.repair",
"mlrs",
"scraptransportheli.repair",
"snowmobile",
"snowmobiletomaha",
"submarineduo",
"submarinesolo",
"locomotive",
"wagon",
"workcart",
"rf_pager",
"mobilephone",
"fun.bass",
"fun.cowbell",
"fun.flute",
"fun.guitar",
"fun.trumpet",
"fun.tuba",
"fun.jerrycanguitar",
"wrappedgift",
"wrappingpaper",
"fun.casetterecorder",
"cassette.medium",
"cassette",
"cassette.short",
"building.planner",
"fun.boomboxportable",
"botabag",
"carvable.pumpkin",
"map"
};
return blacklist.Contains(shortName);
}
//checking for common categories with deployables in them
private bool IsDeployable(ItemDefinition itemDefinition)
{
return itemDefinition.category == ItemCategory.Construction || itemDefinition.category == ItemCategory.Electrical || itemDefinition.category == ItemCategory.Fun || itemDefinition.category == ItemCategory.Items || itemDefinition.category == ItemCategory.Traps || itemDefinition.category == ItemCategory.Common || itemDefinition.category == ItemCategory.Misc;
}
//here I clean up the display names of the entities, so they can be used as easy to find permissions
private string SanitizeDisplayName(string displayName)
{
return string.IsNullOrEmpty(displayName) ? string.Empty : displayName.Replace(' ', '_').Replace('/', '_').ToLower();
}
#endregion
#region Initialization
private Timer _initTimer;
private void Init()
{
_initTimer = timer.Every(5f, () =>
{
if (ItemManager.itemList != null)
{
LoadConfig();
RegisterPermissions();
EnsureLanguageFiles();
_initTimer?.Destroy();
}
else
{
PrintWarning("ItemManager.itemList is still null. Retrying...");
}
});
}
#endregion
#region Permissions
private void RegisterPermissions()
{
foreach (var permissionName in config.Permissions.Values)
{
if (!permission.PermissionExists(permissionName))
{
//Register the permissions, to allow customizing of entity blocking with permissions
permission.RegisterPermission(permissionName, this);
//Puts($"Registered permission: {permissionName}");
}
}
Puts("Permissions registration complete. Granted means disallowed placement");
}
#endregion
#region Hooks
//Check if players have the blocking permission to prevent building.
private object CanBuild(Planner planner, Construction prefab)
{
if (prefab == null || planner == null)
{
PrintWarning("Planner or prefab is null.");
return null;
}
//Getting player ID to check for permission.
var player = planner.GetOwnerPlayer();
if (player == null)
{
Puts("Player is null.");
return null;
}
//Get the prefab name
string prefabShortName = prefab.fullName;
//Check if the entity is in the permissions dictionary
foreach (var kvp in config.Permissions)
{
if (prefabShortName.Contains(kvp.Key))
{
string permissionName = kvp.Value;
if (permission.UserHasPermission(player.UserIDString, permissionName))
{
//Notify player they are not allowed to place this object(permission granted)
player.ChatMessage(lang.GetMessage("NotAllowed", this));
// Return false to prevent the build
return false;
}
return null;
}
}
return null;
}
#endregion
#region Language
private void EnsureLanguageFiles()
{
string baseLangDir = Path.Combine(Directory.GetCurrentDirectory(), "oxide", "lang");
var languages = new Dictionary<string, Dictionary<string, string>>
{
["en"] = new Dictionary<string, string>
{
["NotAllowed"] = "You are not permitted to place this entity."
},
["fr"] = new Dictionary<string, string>
{
["NotAllowed"] = "Vous n'êtes pas autorisé à placer cette entité."
},
["de"] = new Dictionary<string, string>
{
["NotAllowed"] = "Sie sind nicht berechtigt, dieses Objekt zu platzieren."
},
["es"] = new Dictionary<string, string>
{
["NotAllowed"] = "No tienes permiso para colocar esta entidad."
}
};
foreach (var lang in languages)
{
string langDir = Path.Combine(baseLangDir, lang.Key);
if (!Directory.Exists(langDir))
{
Directory.CreateDirectory(langDir);
}
string filePath = Path.Combine(langDir, $"{Name}.json");
try
{
string json = JsonConvert.SerializeObject(lang.Value, Formatting.Indented);
if (!File.Exists(filePath) || File.ReadAllText(filePath) != json)
{
File.WriteAllText(filePath, json);
Puts($"Created/Updated language file: {filePath}");
}
}
catch (Exception ex)
{
PrintWarning($"Error creating/updating language file {filePath}: {ex.Message}");
}
}
foreach (var langCode in languages.Keys)
{
string filePath = Path.Combine(baseLangDir, langCode, $"{Name}.json");
var messages = ReadLanguageFile(filePath);
lang.RegisterMessages(messages, this, langCode);
}
}
private Dictionary<string, string> ReadLanguageFile(string filePath)
{
try
{
if (File.Exists(filePath))
{
string json = File.ReadAllText(filePath);
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
}
catch (Exception ex)
{
PrintWarning($"Error reading language file {filePath}: {ex.Message}");
}
return new Dictionary<string, string>();
}
#endregion
}
}