-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoCode.cs
1367 lines (1196 loc) · 41.8 KB
/
AutoCode.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
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 Oxide.Core;
using Oxide.Core.Configuration;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Libraries;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Auto Code", "BlueBeka", "1.6.0")]
[Description("Automatically sets the code on code locks when placed.")]
public class AutoCode : RustPlugin
{
[PluginReference("NoEscape")]
private Plugin pluginNoEscape;
private AutoCodeConfig config;
private Commands commands;
private Data data;
private Dictionary<BasePlayer, TempCodeLockInfo> tempCodeLocks;
private const string HiddenCode = "****";
#region Hooks
private void Init()
{
config = new AutoCodeConfig(this);
data = new Data(this);
commands = new Commands(this);
tempCodeLocks = new Dictionary<BasePlayer, TempCodeLockInfo>();
config.Load();
data.Load();
Permissions.Register(this);
commands.Register();
}
protected override void LoadDefaultConfig()
{
Interface.Oxide.LogInfo("New configuration file created.");
}
private void OnServerSave()
{
data.Save();
}
private void Unload()
{
RemoveAllTempCodeLocks();
data.Save();
}
private object OnCodeEntered(CodeLock codeLock, BasePlayer player, string code)
{
// Not one of our temporary code locks?
if (player == null || !tempCodeLocks.ContainsKey(player) || tempCodeLocks[player].CodeLock != codeLock)
{
UnsubscribeFromUnneededHooks();
return null;
}
// Destroy the temporary code lock as soon as it's ok to do so.
timer.In(0, () =>
{
DestroyTempCodeLock(player);
});
SetCode(player, code, tempCodeLocks[player].Guest);
Effect.server.Run(codeLock.effectCodeChanged.resourcePath, player.transform.position);
return false;
}
private void OnItemDeployed(Deployer deployer, BaseEntity lockable, CodeLock codeLock)
{
// Code already set?
if (codeLock.hasCode && codeLock.hasGuestCode)
{
return;
}
BasePlayer player = BasePlayer.FindByID(codeLock.OwnerID);
// No player or the player doesn't have permission?
if (player == null || !permission.UserHasPermission(player.UserIDString, Permissions.Use))
{
return;
}
// No data for player.
if (!data.Inst.playerSettings.ContainsKey(player.userID))
{
return;
}
// NoEscape blocked.
if (pluginNoEscape != null)
{
if (
config.Options.PluginIntegration.NoEscape.BlockRaid &&
pluginNoEscape.Call<bool>("HasPerm", player.UserIDString, "raid.buildblock") &&
pluginNoEscape.Call<bool>("IsRaidBlocked", player.UserIDString)
)
{
Message(player, lang.GetMessage("NoEscape.RaidBlocked", this, player.UserIDString));
return;
}
if (
config.Options.PluginIntegration.NoEscape.BlockCombat &&
pluginNoEscape.Call<bool>("HasPerm", player.UserIDString, "combat.buildblock") &&
pluginNoEscape.Call<bool>("IsCombatBlocked", player.UserIDString)
)
{
Message(player, lang.GetMessage("NoEscape.CombatBlocked", this, player.UserIDString));
return;
}
}
Data.Structure.PlayerSettings settings = data.Inst.playerSettings[player.userID];
// Player doesn't have a code?
if (settings == null || settings.code == null)
{
return;
}
// Set the main code.
codeLock.code = settings.code;
codeLock.hasCode = true;
codeLock.whitelistPlayers.Add(player.userID);
// Set the guest code.
if (settings.guestCode != null)
{
codeLock.guestCode = settings.guestCode;
codeLock.hasGuestCode = true;
codeLock.guestPlayers.Add(player.userID);
}
// Lock the lock.
codeLock.SetFlag(BaseEntity.Flags.Locked, true);
if (!settings.quietMode)
{
Message(
player,
string.Format(
lang.GetMessage(
codeLock.hasGuestCode ? "CodeAutoLockedWithGuest" : "CodeAutoLocked",
this,
player.UserIDString),
Formatter.Value(Utils.ShouldHideCode(player, settings) ? HiddenCode : codeLock.code),
Formatter.Value(Utils.ShouldHideCode(player, settings) ? HiddenCode : codeLock.guestCode)
)
);
}
}
private object CanUseLockedEntity(BasePlayer player, CodeLock codeLock)
{
// Is a player that has permission and lock is locked?
if (
player != null &&
codeLock.hasCode &&
codeLock.HasFlag(BaseEntity.Flags.Locked) &&
permission.UserHasPermission(player.UserIDString, Permissions.Use) &&
permission.UserHasPermission(player.UserIDString, Permissions.Try) &&
data.Inst.playerSettings.ContainsKey(player.userID)
)
{
Data.Structure.PlayerSettings settings = data.Inst.playerSettings[player.userID];
// Player has the code?
if (settings != null && codeLock.code == settings.code)
{
// Auth the player.
codeLock.whitelistPlayers.Add(player.userID);
}
}
// Use default behavior.
return null;
}
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
{ "Help", "Usage:\n{0}" },
{ "Description", "Automatically set the code on code locks you place." },
{ "Info", "Code: {0}\nGuest Code: {1}\nQuiet Mode: {2}" },
{ "NoPermission", "You don't have permission." },
{ "CodeAutoLocked", "Code lock placed with code {0}." },
{ "CodeAutoLockedWithGuest", "Code lock placed with code {0} and guest code {1}." },
{ "CodeUpdated", "Your auto-code has changed to {0}." },
{ "CodeUpdatedHidden", "New auto-code set." },
{ "GuestCodeUpdated", "Your guest auto-code has changed to {0}." },
{ "GuestCodeUpdatedHidden", "New guest auto-code set." },
{ "CodeRemoved", "Your auto-code has been removed." },
{ "GuestCodeRemoved", "Your guest auto-code has been removed." },
{ "InvalidArgsTooMany", "Too many arguments supplied." },
{ "NotSet", "Not set" },
{ "SyntaxError", "Syntax Error: expected command in the form:\n{0}" },
{ "SpamPrevention", "Too many recent auto-code sets. Please wait {0} and try again." },
{ "InvalidArguments", "Invalid arguments supplied." },
{ "ErrorNoPlayerFound", "Error: No player found." },
{ "ErrorMoreThanOnePlayerFound", "Error: More than one player found." },
{ "ResettingAllLockOuts", "Resetting lock outs for all players." },
{ "ResettingLockOut", "Resetting lock outs for {0}." },
{ "QuietModeEnable", "Quiet mode now enabled." },
{ "QuietModeDisable", "Quiet mode now disabled." },
{ "Enabled", "Enabled" },
{ "Disabled", "Disabled" },
{ "HelpExtendedCoreCommands", "Core Commands:" },
{ "HelpExtendedOtherCommands", "Other Commands:" },
{ "HelpExtendedInfo", "Show your settings:\n{0}" },
{ "HelpExtendedSetCode", "Set your auto-code to 1234:\n{0}" },
{ "HelpExtendedRandomCode", "Set your auto-code to a randomly generated code:\n{0}" },
{ "HelpExtendedRemoveCode", "Remove your set auto-code:\n{0}" },
{ "HelpExtendedCoreGuestCommands", "Each core command is also available in a guest code version. e.g.\n{0}" },
{ "HelpExtendedQuietMode", "Toggles on/off quiet mode:\n{0}" },
{ "HelpExtendedQuietModeDetails", "Less messages will be shown and your auto-code will be hidden." },
{ "HelpExtendedHelp", "Displays this help message:\n{0}" },
{ "NoLongerSupportedPick", "\"{0}\" is no longer supported, please use \"{1}\" instead." },
{ "NoEscape.RaidBlocked", "Auto-code disabled due to raid block." },
{ "NoEscape.CombatBlocked", "Auto-code disabled due to combat block." },
}, this);
}
#endregion Hooks
#region API
[ObsoleteAttribute("This method is deprecated. Call GetCode instead.", false)]
public string GetPlayerCode(BasePlayer player) => GetCode(player);
/// <summary>
/// Get the code for the given player.
/// </summary>
/// <param name="player">The player to get the code for.</param>
/// <param name="guest">If true, the guest code will be returned instead of the main code.</param>
/// <returns>A string of the player's code or null if the player doesn't have a code.</returns>
public string GetCode(BasePlayer player, bool guest = false)
{
if (data.Inst.playerSettings.ContainsKey(player.userID))
{
return guest
? data.Inst.playerSettings[player.userID].guestCode
: data.Inst.playerSettings[player.userID].code;
}
return null;
}
/// <summary>
/// Set the code for the given player.
/// </summary>
/// <param name="player">The player to set the code for.</param>
/// <param name="code">The code to set for the given player.</param>
/// <param name="guest">If true, the guest code will be set instead of the main code.</param>
/// <param name="quiet">If true, no output message will be shown to the player.</param>
/// <param name="hideCode">If true, the new code won't be displayed to the user. Has no effect if quiet is true.</param>
public void SetCode(BasePlayer player, string code, bool guest = false, bool quiet = false, bool hideCode = false)
{
if (!data.Inst.playerSettings.ContainsKey(player.userID))
{
data.Inst.playerSettings.Add(player.userID, new Data.Structure.PlayerSettings());
}
// Load the player's settings
Data.Structure.PlayerSettings settings = data.Inst.playerSettings[player.userID];
double currentTime = Utils.CurrentTime();
if (config.Options.SpamPrevention.Enabled)
{
double timePassed = currentTime - settings.lastSet;
bool lockedOut = currentTime < settings.lockedOutUntil;
double lockOutFor = config.Options.SpamPrevention.LockOutTime * Math.Pow(2, (config.Options.SpamPrevention.UseExponentialLockOutTime ? settings.lockedOutTimes : 0));
if (!lockedOut)
{
// Called again within spam window time?
if (timePassed < config.Options.SpamPrevention.WindowTime)
{
settings.timesSetInSpamWindow++;
}
else
{
settings.timesSetInSpamWindow = 1;
}
// Too many recent changes?
if (settings.timesSetInSpamWindow > config.Options.SpamPrevention.Attempts)
{
// Locked them out.
settings.lockedOutUntil = currentTime + lockOutFor;
settings.lastLockedOut = currentTime;
settings.lockedOutTimes++;
settings.timesSetInSpamWindow = 0;
lockedOut = true;
}
}
// Locked out?
if (lockedOut)
{
if (!quiet)
{
Message(
player,
string.Format(
lang.GetMessage("SpamPrevention", this, player.UserIDString),
TimeSpan.FromSeconds(Math.Ceiling(settings.lockedOutUntil - currentTime)).ToString(@"d\d\ h\h\ mm\m\ ss\s").TrimStart(' ', 'd', 'h', 'm', 's', '0'),
config.Options.SpamPrevention.LockOutTime,
config.Options.SpamPrevention.WindowTime
)
);
}
return;
}
// Haven't been locked out for a long time?
if (currentTime > settings.lastLockedOut + config.Options.SpamPrevention.LockOutResetFactor * lockOutFor)
{
// Reset their lockOuts.
settings.lockedOutTimes = 0;
}
}
if (guest)
{
settings.guestCode = code;
}
else
{
settings.code = code;
}
settings.lastSet = currentTime;
if (!quiet)
{
hideCode = hideCode || Utils.ShouldHideCode(player, settings);
Message(
player,
hideCode
? lang.GetMessage(guest ? "GuestCodeUpdatedHidden" : "CodeUpdatedHidden", this, player.UserIDString)
: string.Format(
lang.GetMessage(guest ? "GuestCodeUpdated" : "CodeUpdated", this, player.UserIDString),
Formatter.Value(code)
)
);
}
}
/// <summary>
/// This method will only toggle off, not on.
/// </summary>
/// <param name="player"></param>
[ObsoleteAttribute("This method is deprecated.", true)]
public void ToggleEnabled(BasePlayer player)
{
RemoveCode(player);
}
/// <summary>
/// Remove the given player's the code.
/// </summary>
/// <param name="player">The player to remove the code of.</param>
/// <param name="guest">If true, the guest code will be removed instead of the main code.</param>
/// <param name="quiet">If true, no output message will be shown to the player.</param>
public void RemoveCode(BasePlayer player, bool guest = false, bool quiet = false)
{
if (!data.Inst.playerSettings.ContainsKey(player.userID))
{
return;
}
// Load the player's settings.
Data.Structure.PlayerSettings settings = data.Inst.playerSettings[player.userID];
if (!guest)
{
settings.code = null;
}
// Remove the guest code both then removing the main code and when just removing the guest code.
settings.guestCode = null;
if (!quiet)
{
Message(
player,
lang.GetMessage(guest ? "GuestCodeRemoved" : "CodeRemoved", this, player.UserIDString)
);
}
}
[ObsoleteAttribute("This method is deprecated. Call IsValidCode instead.", false)]
public bool ValidCode(string codeString) => ValidCode(codeString);
/// <summary>
/// Is the given string a valid code?
/// </summary>
/// <param name="code">The code to test.</param>
/// <returns>True if it's valid, otherwise false.</returns>
public bool IsValidCode(string codeString)
{
if (codeString == null)
{
return false;
}
int code;
if (codeString.Length == 4 && int.TryParse(codeString, out code))
{
if (code >= 0 && code < 10000)
{
return true;
}
}
return false;
}
[ObsoleteAttribute("This method is deprecated. Call GenerateRandomCode instead.", false)]
public static string GetRandomCode()
{
return Core.Random.Range(0, 10000).ToString("0000");
}
/// <summary>
/// Generate a random code.
/// </summary>
/// <returns></returns>
public string GenerateRandomCode()
{
return Core.Random.Range(0, 10000).ToString("0000");
}
/// <summary>
/// Remove all lock outs caused by spam protection.
/// </summary>
/// <param name="player">The player to toggle quiet mode for.</param>
/// <param name="quiet">If true, no output message will be shown to the player.</param>
public void ToggleQuietMode(BasePlayer player, bool quiet = false)
{
// Load the player's settings.
Data.Structure.PlayerSettings settings = data.Inst.playerSettings[player.userID];
settings.quietMode = !settings.quietMode;
if (!quiet)
{
if (settings.quietMode)
{
Message(
player,
string.Format(
"{0}\n" + Formatter.SmallLineGap + "{1}",
lang.GetMessage("QuietModeEnable", this, player.UserIDString),
lang.GetMessage("HelpExtendedQuietModeDetails", this, player.UserIDString)
)
);
}
else
{
Message(
player,
lang.GetMessage("QuietModeDisable", this, player.UserIDString)
);
}
}
}
/// <summary>
/// Reset (remove) all lock outs caused by spam protection.
/// </summary>
public void ResetAllLockOuts()
{
foreach (ulong userID in data.Inst.playerSettings.Keys)
{
ResetLockOut(userID);
}
}
/// <summary>
/// Reset (remove) the lock out caused by spam protection for the given player.
/// </summary>
/// <param name="player"></param>
public void ResetLockOut(BasePlayer player)
{
ResetLockOut(player.userID);
}
/// <summary>
/// Reset (remove) the lock out caused by spam protection for the given user id.
/// </summary>
/// <param name="userID"></param>
public void ResetLockOut(ulong userID)
{
if (!data.Inst.playerSettings.ContainsKey(userID))
{
return;
}
Data.Structure.PlayerSettings settings = data.Inst.playerSettings[userID];
settings.lockedOutTimes = 0;
settings.lockedOutUntil = 0;
}
#endregion API
/// <summary>
/// Destroy the temporary code lock for the given player.
/// </summary>
/// <param name="player"></param>
private void DestroyTempCodeLock(BasePlayer player)
{
// Code lock for player exists? Remove it.
if (tempCodeLocks.ContainsKey(player))
{
// Code lock exists? Destroy it.
if (!tempCodeLocks[player].CodeLock.IsDestroyed)
{
tempCodeLocks[player].CodeLock.Kill();
}
tempCodeLocks.Remove(player);
}
UnsubscribeFromUnneededHooks();
}
/// <summary>
/// Remove all the temporary code locks.
/// </summary>
private void RemoveAllTempCodeLocks()
{
// Remove all temp code locks - we don't want to save them.
foreach (TempCodeLockInfo codeLockInfo in tempCodeLocks.Values)
{
if (!codeLockInfo.CodeLock.IsDestroyed)
{
codeLockInfo.CodeLock.Kill();
}
}
tempCodeLocks.Clear();
UnsubscribeFromUnneededHooks();
}
/// <summary>
/// Unsubscribe from things that there is not point currently being subscribed to.
/// </summary>
private void UnsubscribeFromUnneededHooks()
{
// No point listing for code lock codes if we aren't expecting any.
if (tempCodeLocks.Count < 1)
{
Unsubscribe("OnCodeEntered");
}
}
/// <summary>
/// Message the given player via the in-game chat.
/// </summary>
private void Message(BasePlayer player, string message)
{
if (string.IsNullOrEmpty(message) || !player.IsConnected)
return;
player.SendConsoleCommand(
"chat.add",
2,
config.Commands.ChatIconId,
message
);
}
/// <summary>
/// The Config for this plugin.
/// </summary>
private class AutoCodeConfig
{
// The plugin.
private readonly AutoCode plugin;
// The oxide DynamicConfigFile instance.
public readonly DynamicConfigFile OxideConfig;
// Meta.
private bool UnsavedChanges = false;
public AutoCodeConfig()
{
}
public AutoCodeConfig(AutoCode plugin)
{
this.plugin = plugin;
OxideConfig = plugin.Config;
}
public CommandsDef Commands = new CommandsDef();
public class CommandsDef
{
public string Use = "code";
public ulong ChatIconId = 76561199143387303u;
};
public OptionsDef Options = new OptionsDef();
public class OptionsDef
{
public bool DisplayPermissionErrors = true;
public SpamPreventionDef SpamPrevention = new SpamPreventionDef();
public PluginIntegrationDef PluginIntegration = new PluginIntegrationDef();
public class SpamPreventionDef
{
public bool Enabled = true;
public int Attempts = 5;
public double LockOutTime = 5.0;
public double WindowTime = 30.0;
public bool UseExponentialLockOutTime = true;
public double LockOutResetFactor = 5.0;
};
public class PluginIntegrationDef
{
public NoEscapeDef NoEscape = new NoEscapeDef();
public class NoEscapeDef
{
public bool BlockRaid = false;
public bool BlockCombat = false;
};
};
};
/// <summary>
/// Save the changes to the config file.
/// </summary>
public void Save(bool force = false)
{
if (UnsavedChanges || force)
{
plugin.SaveConfig();
}
}
/// <summary>
/// Load config values.
/// </summary>
public void Load()
{
// Options.
Options.DisplayPermissionErrors = GetConfigValue(
new string[] { "Options", "Display Permission Errors" },
GetConfigValue(new string[] { "Options", "displayPermissionErrors" }, true, true)
);
RemoveConfigValue(new string[] { "Options", "displayPermissionErrors" }); // Remove deprecated version.
// Spam prevention.
Options.SpamPrevention.Enabled = GetConfigValue(new string[] { "Options", "Spam Prevention", "Enable" }, true);
Options.SpamPrevention.Attempts = GetConfigValue(new string[] { "Options", "Spam Prevention", "Attempts" }, 5);
Options.SpamPrevention.LockOutTime = GetConfigValue(new string[] { "Options", "Spam Prevention", "Lock Out Time" }, 5.0);
Options.SpamPrevention.WindowTime = GetConfigValue(new string[] { "Options", "Spam Prevention", "Window Time" }, 30.0);
Options.SpamPrevention.LockOutResetFactor = GetConfigValue(new string[] { "Options", "Spam Prevention", "Lock Out Reset Factor" }, 5.0);
Options.SpamPrevention.UseExponentialLockOutTime = GetConfigValue(
new string[] { "Options", "Spam Prevention", "Exponential Lock Out Time" },
GetConfigValue(new string[] { "Options", "Spam Prevention", "Use Exponential Lock Out Time" }, true, true)
);
RemoveConfigValue(new string[] { "Options", "Spam Prevention", "Exponential Lock Out Time" }); // Remove deprecated version.
// Plugin integration - No Escape.
Options.PluginIntegration.NoEscape.BlockCombat = GetConfigValue(new string[] { "Options", "Plugin Integration", "No Escape", "Block Combat" }, false);
Options.PluginIntegration.NoEscape.BlockRaid = GetConfigValue(new string[] { "Options", "Plugin Integration", "No Escape", "Block Raid" }, true);
// Commands.
plugin.commands.Use = GetConfigValue(new string[] { "Commands", "Use" }, plugin.commands.Use);
Save();
}
/// <summary>
/// Get the config value for the given settings.
/// </summary>
private T GetConfigValue<T>(string[] settingPath, T defaultValue, bool deprecated = false)
{
object value = OxideConfig.Get(settingPath);
if (value == null)
{
if (!deprecated)
{
SetConfigValue(settingPath, defaultValue);
}
return defaultValue;
}
return OxideConfig.ConvertValue<T>(value);
}
/// <summary>
/// Set the config value for the given settings.
/// </summary>
private void SetConfigValue<T>(string[] settingPath, T newValue)
{
List<object> pathAndTrailingValue = new List<object>();
foreach (var segment in settingPath)
{
pathAndTrailingValue.Add(segment);
}
pathAndTrailingValue.Add(newValue);
OxideConfig.Set(pathAndTrailingValue.ToArray());
UnsavedChanges = true;
}
/// <summary>
/// Remove the config value for the given setting.
/// </summary>
private void RemoveConfigValue(string[] settingPath)
{
if (settingPath.Length == 1)
{
OxideConfig.Remove(settingPath[0]);
return;
}
List<string> parentPath = new List<string>();
for (int i = 0; i < settingPath.Length - 1; i++)
{
parentPath.Add(settingPath[i]);
}
Dictionary<string, object> parent = OxideConfig.Get(parentPath.ToArray()) as Dictionary<string, object>;
parent.Remove(settingPath[settingPath.Length - 1]);
}
}
/// <summary>
/// Everything related to the data the plugin needs to save.
/// </summary>
private class Data
{
// The plugin.
private readonly string Filename;
// The actual data.
public Structure Inst { private set; get; }
public Data(AutoCode plugin)
{
Filename = plugin.Name;
}
/// <summary>
/// Save the data.
/// </summary>
public void Save()
{
Interface.Oxide.DataFileSystem.WriteObject(Filename, Inst);
}
/// <summary>
/// Load the data.
/// </summary>
public void Load()
{
Inst = Interface.Oxide.DataFileSystem.ReadObject<Structure>(Filename);
}
/// <summary>
/// The data this plugin needs to save.
/// </summary>
public class Structure
{
public Dictionary<ulong, PlayerSettings> playerSettings = new Dictionary<ulong, PlayerSettings>();
/// <summary>
/// The settings saved for each player.
/// </summary>
public class PlayerSettings
{
public string code = null;
public string guestCode = null;
public bool quietMode = false;
public double lastSet = 0;
public int timesSetInSpamWindow = 0;
public double lockedOutUntil = 0;
public double lastLockedOut = 0;
public int lockedOutTimes = 0;
}
}
}
/// <summary>
/// The permissions this plugin uses.
/// </summary>
private static class Permissions
{
// Permissions.
public const string Use = "autocode.use";
public const string Try = "autocode.try";
public const string Admin = "autocode.admin";
/// <summary>
/// Register the permissions.
/// </summary>
public static void Register(AutoCode plugin)
{
plugin.permission.RegisterPermission(Use, plugin);
plugin.permission.RegisterPermission(Try, plugin);
plugin.permission.RegisterPermission(Admin, plugin);
}
}
/// <summary>
/// Everything related to commands.
/// </summary>
private class Commands
{
// The plugin.
private readonly AutoCode plugin;
// The rust command instance.
public readonly Command Rust;
// Console Commands.
public string ResetLockOut = "autocode.resetlockout";
// Chat Commands.
public string Use = "code";
// Chat Command Arguments.
public string Guest = "guest";
public string PickCode = "pick";
public string RandomCode = "random";
public string RemoveCode = "remove";
public string SetCode = "set";
public string QuietMode = "quiet";
public string Help = "help";
public Commands(AutoCode plugin)
{
this.plugin = plugin;
Rust = plugin.cmd;
}
/// <summary>
/// Register this command.
/// </summary>
public void Register()
{
Rust.AddConsoleCommand(ResetLockOut, plugin, HandleResetLockOut);
Rust.AddChatCommand(Use, plugin, HandleUse);
}
/// <summary>
/// Reset lock out.
/// </summary>
/// <returns></returns>
private bool HandleResetLockOut(ConsoleSystem.Arg arg)
{
BasePlayer player = arg.Player();
// Not admin?
if (!plugin.permission.UserHasPermission(player.UserIDString, Permissions.Admin))
{
if (plugin.config.Options.DisplayPermissionErrors)
{
arg.ReplyWith(plugin.lang.GetMessage("NoPermission", plugin, player?.UserIDString));
}
return false;
}
// Incorrect number of args given.
if (!arg.HasArgs(1) || arg.HasArgs(2))
{
arg.ReplyWith(plugin.lang.GetMessage("InvalidArguments", plugin, player?.UserIDString));
return false;
}
string resetForString = arg.GetString(0).ToLower();
// Reset all?
if (resetForString == "*")
{
arg.ReplyWith(plugin.lang.GetMessage("ResettingAllLockOuts", plugin, player?.UserIDString));
plugin.ResetAllLockOuts();
return true;
}
// Find the player to reset for.
List<BasePlayer> resetForList = new List<BasePlayer>();
foreach (BasePlayer p in BasePlayer.allPlayerList)
{
if (p == null || string.IsNullOrEmpty(p.displayName))
{
continue;
}
if (p.UserIDString == resetForString || p.displayName.Contains(resetForString, CompareOptions.OrdinalIgnoreCase))
{
resetForList.Add(p);
}
}
// No player found?
if (resetForList.Count == 0)
{
arg.ReplyWith(plugin.lang.GetMessage("ErrorNoPlayerFound", plugin, player?.UserIDString));
return false;
}
// Too many players found?
if (resetForList.Count > 1)
{
arg.ReplyWith(plugin.lang.GetMessage("ErrorMoreThanOnePlayerFound", plugin, player?.UserIDString));
return false;
}
// Rest for player.
arg.ReplyWith(
string.Format(
plugin.lang.GetMessage("ResettingLockOut", plugin, player?.UserIDString),
resetForList[0].displayName
)
);
plugin.ResetLockOut(resetForList[0]);
return true;
}
/// <summary>
/// The "use" chat command.
/// </summary>
private void HandleUse(BasePlayer player, string label, string[] args)
{
// Allowed to use this command?
if (!plugin.permission.UserHasPermission(player.UserIDString, Permissions.Use))
{
if (plugin.config.Options.DisplayPermissionErrors)
{
plugin.Message(
player,
plugin.lang.GetMessage("NoPermission", plugin, player.UserIDString)
);
}
return;
}
if (args.Length == 0)
{
ShowInfo(player, label, args);
return;
}
// Create settings for user if they don't already have any settings.
if (!plugin.data.Inst.playerSettings.ContainsKey(player.userID))
{
plugin.data.Inst.playerSettings.Add(player.userID, new Data.Structure.PlayerSettings());
}
int nextArg = 0;
int argsRemainingCount = args.Length;
string operation = args[nextArg++].ToLower();
argsRemainingCount--;
bool guest = false;
if (operation == Guest)
{
if (argsRemainingCount < 1)
{
SyntaxError(player, label, args);
return;
}
guest = true;
operation = args[nextArg++].ToLower();
argsRemainingCount--;
}
if (operation == SetCode)
{
if (argsRemainingCount < 1)