-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildingLicense.cs
More file actions
1177 lines (974 loc) · 45.6 KB
/
Copy pathBuildingLicense.cs
File metadata and controls
1177 lines (974 loc) · 45.6 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Oxide.Core;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("BuildingLicense", "whitecristafer, infunv.ru", "2.0.0")]
[Description("Building license control with bilingual messaging and safer update flow")]
public class BuildingLicense : RustPlugin
{
#region Constants
private const ulong PluginIcon = 76561198209258869UL;
private const string PluginVersion = "2.0.0";
private const string DefaultPrefix = "<size=12><color=#4f8cff><b>[BuildingLicense]</b></color></size>";
private const string AdminPermission = "buildinglicense.admin";
private const string StonePermission = "buildinglicense.stone";
private const string MetalPermission = "buildinglicense.metal";
private const string ArmoredPermission = "buildinglicense.armored";
private const string DefaultUpdateUrl = "https://raw.githubusercontent.com/whitecristafer/BuildingLicense/main/BuildingLicense.cs";
private static readonly string[] SupportedCategories = { "foundation", "wall", "floor", "stair", "roof", "ramp", "other" };
#endregion
#region Config models
private PluginConfig _config;
private Timer _updateTimer;
private string _dataPath;
private string _backupPath;
private sealed class PluginConfig
{
public SettingsConfig Settings = new SettingsConfig();
public UpdateConfig Update = new UpdateConfig();
public MessagesConfig Messages = new MessagesConfig();
public PermissionsConfig Permissions = new PermissionsConfig();
public GradeRulesConfig GradeRules = new GradeRulesConfig();
}
private sealed class SettingsConfig
{
public bool Enabled = true;
public bool BlockWithoutLicense = true;
public bool ShowMessages = true;
public bool LogToConsole = true;
public bool AllowAdminsBypass = false;
public bool UseCategoryRestrictions = true;
public bool AllowMultipleLicenses = true;
}
private sealed class UpdateConfig
{
public bool Enabled = true;
public bool CheckOnStartup = true;
public bool AutoCheck = true;
public int CheckIntervalMinutes = 360;
public string SourceUrl = string.Empty;
public int TimeoutSeconds = 15;
public bool CreateBackupBeforeApply = true;
}
private sealed class MessagesConfig
{
public string Prefix = DefaultPrefix;
public string NoPermission = "You don't have permission to use this command.";
public string PluginDisabled = "The Building License plugin is currently disabled.";
public string NoLicenseStone = "You need a Stone Building License to upgrade to Stone.";
public string NoLicenseMetal = "You need a Metal Building License to upgrade to Metal.";
public string NoLicenseArmored = "You need an Armored Building License to upgrade to Armored.";
public string GradeBlocked = "This upgrade tier has been disabled by the server administrator.";
public string CategoryBlocked = "This building category is not allowed for this upgrade tier.";
public string Granted = "License granted: {0} now has the {1} license.";
public string AlreadyHas = "That player already has the requested license.";
public string PlayerNotFound = "Player not found. Please check the name or Steam ID.";
public string InvalidLicense = "Invalid license type. Use: stone, metal, or armored.";
public string HelpHeader = "Building License Plugin - Help";
public string HelpLine1 = "/grantlicense <player> <stone|metal|armored> - Grants a license to a player.";
public string HelpLine2 = "/bl help - Displays this help menu.";
public string HelpLine3 = "/bl status - Shows plugin status and configuration.";
public string HelpLine4 = "/bl reload - Reloads the plugin configuration and caches.";
public string HelpLine5 = "/bl update - Checks for plugin updates manually.";
public string HelpLine6 = "Licenses can be combined. Players with a higher tier automatically have access to lower tiers.";
public string StatusHeader = "Building License Plugin Status";
public string StatusLine1 = "Enabled: {0} | Block Without License: {1} | Show Messages: {2} | Log to Console: {3} | Allow Multiple Licenses: {4}";
public string StatusLine2 = "Auto-Update: {0} | Check Interval: {1} minutes | Source URL: {2}";
public string UpdateCheckStart = "Checking for plugin updates...";
public string UpdateCurrent = "You are running the latest version: {0}";
public string UpdateAvailable = "New version {1} available (current: {0}). Downloading update...";
public string UpdateDownloaded = "Update downloaded successfully and will be applied on reload. File: {0}";
public string UpdateFailed = "Update check failed. Please check the console for details.";
public string UpdateInvalid = "The remote file does not contain valid version information.";
public string ConfigReloaded = "Configuration and caches have been reloaded.";
public string NoTarget = "No player found matching that name or ID.";
public string UsageGrant = "Usage: /grantlicense <player> <stone|metal|armored>";
}
private sealed class PermissionsConfig
{
public string Admin = AdminPermission;
public string Stone = StonePermission;
public string Metal = MetalPermission;
public string Armored = ArmoredPermission;
}
private sealed class GradeRulesConfig
{
public GradeRuleConfig Stone = new GradeRuleConfig();
public GradeRuleConfig Metal = new GradeRuleConfig();
public GradeRuleConfig Armored = new GradeRuleConfig();
public List<string> DisabledGrades = new List<string>();
}
private sealed class GradeRuleConfig
{
public bool Enabled = true;
public string Permission = string.Empty;
public string Message = string.Empty;
public List<string> AllowedCategories = new List<string>();
}
#endregion
#region Runtime model
private readonly Dictionary<string, string> _categoryCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<BuildingGrade.Enum, GradeRuntime> _gradeCache = new Dictionary<BuildingGrade.Enum, GradeRuntime>();
private readonly HashSet<BuildingGrade.Enum> _disabledGrades = new HashSet<BuildingGrade.Enum>();
private sealed class GradeRuntime
{
public BuildingGrade.Enum Grade;
public bool Enabled;
public string Permission;
public string Message;
public HashSet<string> AllowedCategories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
private enum LicenseTier
{
Stone,
Metal,
Armored
}
#endregion
#region Lifecycle
private void Init()
{
EnsureFolders();
}
private void Loaded()
{
LoadPluginConfig();
RegisterPermissions();
BuildCaches();
RegisterCommands();
}
private void OnServerInitialized()
{
PrintStartupBanner();
if (_config.Update.Enabled && _config.Update.CheckOnStartup)
{
timer.Once(3f, () => CheckForUpdates(false));
}
StartUpdateLoop();
}
private void Unload()
{
if (_updateTimer != null)
{
_updateTimer.Destroy();
_updateTimer = null;
}
}
private object CanUpgrade(BasePlayer player, BuildingBlock block, ConstructionGrade grade)
{
return HandleUpgradeRequest(player, block, GetGradeEnum(grade));
}
private object CanUpgrade(BuildingBlock block, BasePlayer player, ConstructionGrade grade)
{
return HandleUpgradeRequest(player, block, GetGradeEnum(grade));
}
private object CanUpgrade(BasePlayer player, BuildingBlock block, BuildingGrade.Enum grade)
{
return HandleUpgradeRequest(player, block, grade);
}
private object CanUpgrade(BuildingBlock block, BasePlayer player, BuildingGrade.Enum grade)
{
return HandleUpgradeRequest(player, block, grade);
}
private object OnStructureUpgrade(BuildingBlock block, BasePlayer player, BuildingGrade.Enum grade)
{
return HandleUpgradeRequest(player, block, grade);
}
private object OnStructureUpgrade(BuildingBlock block, BasePlayer player, ConstructionGrade grade)
{
return HandleUpgradeRequest(player, block, GetGradeEnum(grade));
}
#endregion
#region Commands
private void RegisterCommands()
{
cmd.AddChatCommand("bl", this, nameof(CmdBuildingLicense));
cmd.AddChatCommand("grantlicense", this, nameof(CmdGrantLicense));
}
private void CmdBuildingLicense(BasePlayer player, string command, string[] args)
{
if (!IsAdmin(player))
{
Reply(player, _config.Messages.NoPermission);
return;
}
string sub = args.Length > 0 ? args[0].Trim().ToLowerInvariant() : "help";
switch (sub)
{
case "help":
Reply(player, _config.Messages.HelpHeader);
Reply(player, _config.Messages.HelpLine1);
Reply(player, _config.Messages.HelpLine2);
Reply(player, _config.Messages.HelpLine3);
Reply(player, _config.Messages.HelpLine4);
Reply(player, _config.Messages.HelpLine5);
Reply(player, _config.Messages.HelpLine6);
break;
case "status":
Reply(player, _config.Messages.StatusHeader);
Reply(player, string.Format(_config.Messages.StatusLine1,
_config.Settings.Enabled,
_config.Settings.BlockWithoutLicense,
_config.Settings.ShowMessages,
_config.Settings.LogToConsole,
_config.Settings.AllowMultipleLicenses));
Reply(player, string.Format(_config.Messages.StatusLine2,
_config.Update.Enabled,
_config.Update.AutoCheck,
_config.Update.SourceUrl));
break;
case "reload":
LoadPluginConfig();
RegisterPermissions();
BuildCaches();
StartUpdateLoop();
Reply(player, _config.Messages.ConfigReloaded);
break;
case "update":
CheckForUpdates(true);
break;
default:
Reply(player, _config.Messages.HelpHeader);
Reply(player, _config.Messages.HelpLine1);
Reply(player, _config.Messages.HelpLine2);
Reply(player, _config.Messages.HelpLine3);
Reply(player, _config.Messages.HelpLine4);
Reply(player, _config.Messages.HelpLine5);
Reply(player, _config.Messages.HelpLine6);
break;
}
}
private void CmdGrantLicense(BasePlayer player, string command, string[] args)
{
if (!IsAdmin(player))
{
Reply(player, _config.Messages.NoPermission);
return;
}
if (args.Length < 2)
{
Reply(player, _config.Messages.UsageGrant);
return;
}
BasePlayer target = FindPlayer(args[0]);
if (target == null)
{
Reply(player, _config.Messages.NoTarget);
return;
}
LicenseTier tier;
if (!TryParseTier(args[1], out tier))
{
Reply(player, _config.Messages.InvalidLicense);
return;
}
string permissionNode = GetPermissionForTier(tier);
if (string.IsNullOrWhiteSpace(permissionNode))
{
Reply(player, _config.Messages.InvalidLicense);
return;
}
if (HasLicenseForTier(target, tier))
{
Reply(player, _config.Messages.AlreadyHas);
return;
}
ApplyExclusiveLicenses(target, tier);
permission.GrantUserPermission(target.UserIDString, permissionNode, this);
Reply(player, string.Format(_config.Messages.Granted, target.displayName, tier.ToString().ToLowerInvariant()));
Puts(string.Format("{0} Granted {1} license to {2} ({3})", GetLogTag(), tier, target.displayName, target.UserIDString));
}
#endregion
#region Upgrade enforcement
private object HandleUpgradeRequest(BasePlayer player, BuildingBlock block, BuildingGrade.Enum grade)
{
if (player == null || block == null)
return null;
if (!_config.Settings.Enabled || !_config.Settings.BlockWithoutLicense)
return null;
if (grade <= BuildingGrade.Enum.Wood)
return null;
if (player.IsAdmin && _config.Settings.AllowAdminsBypass)
return null;
GradeRuntime runtime;
if (!_gradeCache.TryGetValue(grade, out runtime))
return null;
if (!runtime.Enabled || _disabledGrades.Contains(grade))
{
if (_config.Settings.ShowMessages)
Reply(player, _config.Messages.GradeBlocked);
LogBlocked(player, block, grade, "disabled-grade");
return false;
}
if (!IsCategoryAllowed(runtime, block))
{
if (_config.Settings.ShowMessages)
Reply(player, _config.Messages.CategoryBlocked);
LogBlocked(player, block, grade, "category-restricted");
return false;
}
if (string.IsNullOrWhiteSpace(runtime.Permission))
return null;
LicenseTier requiredTier = GetTierFromGrade(grade);
if (!HasLicenseForTier(player, requiredTier))
{
if (_config.Settings.ShowMessages)
Reply(player, ResolveDeniedMessage(runtime, block, grade));
LogBlocked(player, block, grade, "missing-permission");
return false;
}
return null;
}
private string ResolveDeniedMessage(GradeRuntime runtime, BuildingBlock block, BuildingGrade.Enum grade)
{
string message = runtime != null ? runtime.Message : string.Empty;
if (string.IsNullOrWhiteSpace(message))
message = GetDefaultDenyMessage(grade);
string category = ResolveCategory(block);
string categoryLabel = ResolveCategoryLabel(category);
if (message.IndexOf("{0}", StringComparison.Ordinal) >= 0)
{
try
{
return string.Format(message, categoryLabel);
}
catch
{
// I intentionally fall back to the raw message when formatting fails.
}
}
return message;
}
private string ResolveCategoryLabel(string category)
{
switch (category)
{
case "foundation":
return "foundation / фундамент";
case "wall":
return "wall / стена";
case "floor":
return "floor / пол";
case "stair":
return "stair / лестница";
case "roof":
return "roof / крыша";
case "ramp":
return "ramp / рампа";
default:
return "other / другое";
}
}
private bool IsCategoryAllowed(GradeRuntime runtime, BuildingBlock block)
{
if (!_config.Settings.UseCategoryRestrictions)
return true;
if (runtime == null || runtime.AllowedCategories == null || runtime.AllowedCategories.Count == 0)
return true;
string category = ResolveCategory(block);
return runtime.AllowedCategories.Contains(category);
}
private string ResolveCategory(BuildingBlock block)
{
if (block == null)
return "other";
string key = null;
try
{
key = block.ShortPrefabName;
}
catch
{
key = null;
}
if (string.IsNullOrWhiteSpace(key))
key = block.name;
if (string.IsNullOrWhiteSpace(key))
return "other";
string cached;
if (_categoryCache.TryGetValue(key, out cached))
return cached;
string lower = key.ToLowerInvariant();
string category = "other";
if (lower.Contains("foundation"))
category = "foundation";
else if (lower.Contains("wall"))
category = "wall";
else if (lower.Contains("floor"))
category = "floor";
else if (lower.Contains("stair"))
category = "stair";
else if (lower.Contains("roof"))
category = "roof";
else if (lower.Contains("ramp"))
category = "ramp";
_categoryCache[key] = category;
return category;
}
#endregion
#region Update system
private void StartUpdateLoop()
{
if (_updateTimer != null)
{
_updateTimer.Destroy();
_updateTimer = null;
}
if (!_config.Update.Enabled || !_config.Update.AutoCheck)
return;
float interval = Mathf.Max(15f, _config.Update.CheckIntervalMinutes * 60f);
_updateTimer = timer.Every(interval, () => CheckForUpdates(false));
}
private void CheckForUpdates(bool manual)
{
if (!_config.Update.Enabled)
return;
string url = (_config.Update.SourceUrl ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(url))
{
if (manual)
ReplyToConsole(_config.Messages.UpdateFailed);
PrintWarning("[BuildingLicense] Update source URL is empty.");
return;
}
if (manual)
ReplyToConsole(_config.Messages.UpdateCheckStart);
Dictionary<string, string> headers = new Dictionary<string, string>
{
["User-Agent"] = string.Format("{0}/{1}", Name, PluginVersion),
["Accept"] = "text/plain, */*"
};
webrequest.Enqueue(url, null, delegate (int code, string response)
{
if (code != 200 || string.IsNullOrWhiteSpace(response))
{
if (manual)
ReplyToConsole(_config.Messages.UpdateFailed);
PrintWarning(string.Format("[BuildingLicense] Update check failed. HTTP {0}", code));
return;
}
string remoteVersionRaw = ExtractVersion(response);
if (string.IsNullOrWhiteSpace(remoteVersionRaw))
{
if (manual)
ReplyToConsole(_config.Messages.UpdateInvalid);
PrintWarning("[BuildingLicense] Remote source does not contain a valid version.");
return;
}
Version remoteVersion;
Version localVersion;
if (!TryParseVersion(remoteVersionRaw, out remoteVersion) || !TryParseVersion(PluginVersion, out localVersion))
{
if (manual)
ReplyToConsole(_config.Messages.UpdateInvalid);
PrintWarning("[BuildingLicense] Version parse failed.");
return;
}
if (remoteVersion <= localVersion)
{
if (manual)
ReplyToConsole(string.Format(_config.Messages.UpdateCurrent, localVersion));
Puts(string.Format("{0} Update skipped. Local version is current: {1}", GetLogTag(), localVersion));
return;
}
if (manual)
ReplyToConsole(string.Format(_config.Messages.UpdateAvailable, localVersion, remoteVersionRaw));
TryApplyUpdate(response, remoteVersionRaw);
}, this, Oxide.Core.Libraries.RequestMethod.GET, headers, _config.Update.TimeoutSeconds);
}
private void TryApplyUpdate(string sourceContent, string remoteVersionRaw)
{
string currentFile = Path.Combine(Interface.Oxide.PluginDirectory, Name + ".cs");
if (_config.Update.CreateBackupBeforeApply)
TryCreateBackup(currentFile);
try
{
File.WriteAllText(currentFile, sourceContent, new UTF8Encoding(false));
Puts(string.Format("{0} Update downloaded to: {1}", GetLogTag(), currentFile));
Puts(string.Format("{0} Remote version applied: {1}", GetLogTag(), remoteVersionRaw));
ReplyToConsole(string.Format(_config.Messages.UpdateDownloaded, currentFile));
timer.Once(3f, delegate
{
try
{
Server.Command("oxide.reload " + Name);
}
catch (Exception ex)
{
PrintError("[BuildingLicense] Reload after update failed: " + ex.Message);
}
});
}
catch (Exception ex)
{
PrintError("[BuildingLicense] Failed to write update file: " + ex.Message);
}
}
private void TryCreateBackup(string currentFile)
{
try
{
if (!File.Exists(currentFile))
return;
string fileName = string.Format("{0}_{1}.bak.cs", Name, DateTime.UtcNow.ToString("yyyyMMdd_HHmmss"));
string backupFile = Path.Combine(_backupPath, fileName);
File.Copy(currentFile, backupFile, true);
}
catch (Exception ex)
{
PrintWarning("[BuildingLicense] Failed to create update backup: " + ex.Message);
}
}
private string ExtractVersion(string source)
{
if (string.IsNullOrWhiteSpace(source))
return null;
Match infoMatch = Regex.Match(source,
@"\[Info\(\s*""[^""]+""\s*,\s*""[^""]+""\s*,\s*""(?<version>[^""]+)""\s*\)\]",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (infoMatch.Success)
return infoMatch.Groups["version"].Value.Trim();
Match fieldMatch = Regex.Match(source,
@"Version\s*=\s*""(?<version>[^""]+)""",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (fieldMatch.Success)
return fieldMatch.Groups["version"].Value.Trim();
Match pluginVersionMatch = Regex.Match(source,
@"PluginVersion\s*=\s*""(?<version>[^""]+)""",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
return pluginVersionMatch.Success ? pluginVersionMatch.Groups["version"].Value.Trim() : null;
}
private bool TryParseVersion(string value, out Version version)
{
version = null;
if (string.IsNullOrWhiteSpace(value))
return false;
string trimmed = value.Trim().TrimStart('v', 'V');
if (!Regex.IsMatch(trimmed, @"^\d+(\.\d+){1,3}$"))
return false;
try
{
version = new Version(trimmed);
return true;
}
catch
{
return false;
}
}
#endregion
#region Configuration
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
SaveConfig();
}
private void LoadPluginConfig()
{
try
{
_config = Config.ReadObject<PluginConfig>();
}
catch
{
PrintWarning("[BuildingLicense] Config is broken. Rebuilding default config.");
_config = null;
}
if (_config == null)
_config = CreateDefaultConfig();
NormalizeConfig();
SaveConfig();
}
private PluginConfig CreateDefaultConfig()
{
PluginConfig cfg = new PluginConfig();
cfg.Settings.Enabled = true;
cfg.Settings.BlockWithoutLicense = true;
cfg.Settings.ShowMessages = true;
cfg.Settings.LogToConsole = true;
cfg.Settings.AllowAdminsBypass = false;
cfg.Settings.UseCategoryRestrictions = true;
cfg.Settings.AllowMultipleLicenses = true;
cfg.Update.Enabled = true;
cfg.Update.CheckOnStartup = true;
cfg.Update.AutoCheck = true;
cfg.Update.CheckIntervalMinutes = 360;
cfg.Update.SourceUrl = DefaultUpdateUrl;
cfg.Update.TimeoutSeconds = 15;
cfg.Update.CreateBackupBeforeApply = true;
cfg.Messages.Prefix = DefaultPrefix;
cfg.Messages.NoPermission = "You do not have permission. / У вас нет доступа.";
cfg.Messages.PluginDisabled = "Plugin is disabled in the config. / Плагин отключён в конфиге.";
cfg.Messages.NoLicenseStone = "Stone upgrade is locked. / Улучшение Stone заблокировано.";
cfg.Messages.NoLicenseMetal = "Metal upgrade is locked. / Улучшение Metal заблокировано.";
cfg.Messages.NoLicenseArmored = "Armored upgrade is locked. / Улучшение Armored заблокировано.";
cfg.Messages.GradeBlocked = "This upgrade tier is disabled in the config. / Этот уровень улучшения отключён в конфиге.";
cfg.Messages.CategoryBlocked = "This building category is restricted for this tier. / Эта категория построек ограничена для данного уровня.";
cfg.Messages.Granted = "License granted: {0} -> {1} / Лицензия выдана: {0} -> {1}";
cfg.Messages.AlreadyHas = "The player already has this license. / У игрока уже есть эта лицензия.";
cfg.Messages.PlayerNotFound = "Player not found. / Игрок не найден.";
cfg.Messages.InvalidLicense = "Invalid license type. Use: stone | metal | armored. / Неверный тип лицензии. Используй: stone | metal | armored.";
cfg.Messages.HelpHeader = "BuildingLicense help / справка";
cfg.Messages.HelpLine1 = "/grantlicense <player> <stone|metal|armored> - grant a license / выдать лицензию";
cfg.Messages.HelpLine2 = "/bl help - show command help / показать справку";
cfg.Messages.HelpLine3 = "/bl status - show plugin status / показать статус плагина";
cfg.Messages.HelpLine4 = "/bl reload - reload config and caches / перезагрузить конфиг и кэши";
cfg.Messages.HelpLine5 = "/bl update - check for updates / проверить обновления";
cfg.Messages.HelpLine6 = "Licenses can be combined: stone + metal + armored. / Лицензии можно совмещать.";
cfg.Messages.StatusHeader = "Plugin status / Статус плагина";
cfg.Messages.StatusLine1 = "Enabled: {0} | BlockWithoutLicense: {1} | ShowMessages: {2} | LogToConsole: {3}";
cfg.Messages.StatusLine2 = "Update: {0} | AutoCheck: {1} | SourceUrl: {2}";
cfg.Messages.UpdateCheckStart = "Checking for updates... / Проверяю обновления...";
cfg.Messages.UpdateCurrent = "Local version is current: {0} / Установлена актуальная версия: {0}";
cfg.Messages.UpdateAvailable = "New version found: {0} -> {1}. Downloading... / Найдена новая версия: {0} -> {1}. Загружаю...";
cfg.Messages.UpdateDownloaded = "Update saved to: {0} / Обновление сохранено: {0}";
cfg.Messages.UpdateFailed = "Update check or download failed. / Не удалось проверить или загрузить обновление.";
cfg.Messages.UpdateInvalid = "Remote source does not contain a valid version. / Удалённый файл не содержит валидной версии.";
cfg.Messages.ConfigReloaded = "Config and caches reloaded. / Конфиг и кэши обновлены.";
cfg.Messages.NoTarget = "No player target matched that name or ID. / Не удалось найти игрока по имени или ID.";
cfg.Messages.UsageGrant = "Usage: /grantlicense <player> <stone|metal|armored>";
cfg.Permissions.Admin = AdminPermission;
cfg.Permissions.Stone = StonePermission;
cfg.Permissions.Metal = MetalPermission;
cfg.Permissions.Armored = ArmoredPermission;
cfg.GradeRules.DisabledGrades = new List<string>();
cfg.GradeRules.Stone.Enabled = true;
cfg.GradeRules.Stone.Permission = StonePermission;
cfg.GradeRules.Stone.Message = cfg.Messages.NoLicenseStone;
cfg.GradeRules.Stone.AllowedCategories = new List<string>(SupportedCategories);
cfg.GradeRules.Metal.Enabled = true;
cfg.GradeRules.Metal.Permission = MetalPermission;
cfg.GradeRules.Metal.Message = cfg.Messages.NoLicenseMetal;
cfg.GradeRules.Metal.AllowedCategories = new List<string>(SupportedCategories);
cfg.GradeRules.Armored.Enabled = true;
cfg.GradeRules.Armored.Permission = ArmoredPermission;
cfg.GradeRules.Armored.Message = cfg.Messages.NoLicenseArmored;
cfg.GradeRules.Armored.AllowedCategories = new List<string>(SupportedCategories);
return cfg;
}
private void NormalizeConfig()
{
if (_config.Settings == null) _config.Settings = new SettingsConfig();
if (_config.Update == null) _config.Update = new UpdateConfig();
if (_config.Messages == null) _config.Messages = new MessagesConfig();
if (_config.Permissions == null) _config.Permissions = new PermissionsConfig();
if (_config.GradeRules == null) _config.GradeRules = new GradeRulesConfig();
if (string.IsNullOrWhiteSpace(_config.Update.SourceUrl))
_config.Update.SourceUrl = DefaultUpdateUrl;
if (_config.Update.CheckIntervalMinutes <= 0)
_config.Update.CheckIntervalMinutes = 360;
if (_config.Update.TimeoutSeconds <= 0)
_config.Update.TimeoutSeconds = 15;
if (string.IsNullOrWhiteSpace(_config.Messages.Prefix))
_config.Messages.Prefix = DefaultPrefix;
if (string.IsNullOrWhiteSpace(_config.Permissions.Admin))
_config.Permissions.Admin = AdminPermission;
if (string.IsNullOrWhiteSpace(_config.Permissions.Stone))
_config.Permissions.Stone = StonePermission;
if (string.IsNullOrWhiteSpace(_config.Permissions.Metal))
_config.Permissions.Metal = MetalPermission;
if (string.IsNullOrWhiteSpace(_config.Permissions.Armored))
_config.Permissions.Armored = ArmoredPermission;
if (_config.GradeRules.DisabledGrades == null)
_config.GradeRules.DisabledGrades = new List<string>();
EnsureRuleDefaults(_config.GradeRules.Stone, _config.Permissions.Stone, _config.Messages.NoLicenseStone);
EnsureRuleDefaults(_config.GradeRules.Metal, _config.Permissions.Metal, _config.Messages.NoLicenseMetal);
EnsureRuleDefaults(_config.GradeRules.Armored, _config.Permissions.Armored, _config.Messages.NoLicenseArmored);
}
private void EnsureRuleDefaults(GradeRuleConfig rule, string permissionNode, string message)
{
if (rule == null)
return;
if (string.IsNullOrWhiteSpace(rule.Permission))
rule.Permission = permissionNode;
if (string.IsNullOrWhiteSpace(rule.Message))
rule.Message = message;
if (rule.AllowedCategories == null || rule.AllowedCategories.Count == 0)
rule.AllowedCategories = new List<string>(SupportedCategories);
}
#endregion
#region Runtime caches
private void BuildCaches()
{
_disabledGrades.Clear();
_gradeCache.Clear();
_categoryCache.Clear();
if (_config.GradeRules.DisabledGrades != null)
{
foreach (string raw in _config.GradeRules.DisabledGrades)
{
BuildingGrade.Enum grade;
if (TryParseGrade(raw, out grade))
_disabledGrades.Add(grade);
}
}
AddGradeRuntime(BuildingGrade.Enum.Stone, _config.GradeRules.Stone);
AddGradeRuntime(BuildingGrade.Enum.Metal, _config.GradeRules.Metal);
AddGradeRuntime(BuildingGrade.Enum.TopTier, _config.GradeRules.Armored);
}
private void AddGradeRuntime(BuildingGrade.Enum grade, GradeRuleConfig rule)
{
GradeRuntime runtime = new GradeRuntime();
runtime.Grade = grade;
runtime.Enabled = rule != null && rule.Enabled;
runtime.Permission = rule != null ? rule.Permission : string.Empty;
runtime.Message = rule != null ? rule.Message : string.Empty;
if (rule != null && rule.AllowedCategories != null)
{
foreach (string category in rule.AllowedCategories)
{
if (string.IsNullOrWhiteSpace(category))
continue;
runtime.AllowedCategories.Add(category.Trim().ToLowerInvariant());
}
}
_gradeCache[grade] = runtime;
}
#endregion
#region Helpers
private void EnsureFolders()
{
_dataPath = Path.Combine(Interface.Oxide.DataDirectory, Name);
_backupPath = Path.Combine(_dataPath, "backups");
Directory.CreateDirectory(_dataPath);
Directory.CreateDirectory(_backupPath);
}
private bool IsAdmin(BasePlayer player)
{
if (player == null)
return false;
if (player.IsAdmin && _config != null && _config.Settings.AllowAdminsBypass)
return true;
return permission.UserHasPermission(player.UserIDString, AdminPermission);
}
private BasePlayer FindPlayer(string nameOrId)
{
if (string.IsNullOrWhiteSpace(nameOrId))
return null;
BasePlayer player = BasePlayer.Find(nameOrId);
if (player != null)
return player;
string needle = nameOrId.Trim();
foreach (BasePlayer active in BasePlayer.activePlayerList)
{
if (MatchesPlayer(active, needle))
return active;
}
foreach (BasePlayer sleeping in BasePlayer.sleepingPlayerList)
{
if (MatchesPlayer(sleeping, needle))
return sleeping;
}
return null;
}
private bool MatchesPlayer(BasePlayer player, string needle)
{
if (player == null || string.IsNullOrWhiteSpace(needle))
return false;
if (player.UserIDString == needle)
return true;
return player.displayName != null && player.displayName.IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0;
}
private bool TryParseTier(string value, out LicenseTier tier)
{
tier = LicenseTier.Stone;
if (string.IsNullOrWhiteSpace(value))
return false;
switch (value.Trim().ToLowerInvariant())
{
case "stone":
tier = LicenseTier.Stone;
return true;
case "metal":
tier = LicenseTier.Metal;
return true;
case "armored":
case "armor":
case "top":
case "toptier":
tier = LicenseTier.Armored;
return true;
default:
return false;
}
}
private bool TryParseGrade(string value, out BuildingGrade.Enum grade)
{
grade = BuildingGrade.Enum.None;
if (string.IsNullOrWhiteSpace(value))
return false;
switch (value.Trim().ToLowerInvariant())
{
case "stone":
grade = BuildingGrade.Enum.Stone;
return true;
case "metal":
grade = BuildingGrade.Enum.Metal;
return true;
case "armored":
case "armor":
case "top":
case "toptier":
grade = BuildingGrade.Enum.TopTier;
return true;
case "wood":