-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOfflineRaidProtection.cs
More file actions
3037 lines (2512 loc) · 95.9 KB
/
OfflineRaidProtection.cs
File metadata and controls
3037 lines (2512 loc) · 95.9 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
#if CARBON
using Carbon.Extensions;
using Carbon.Plugins.OfflineRaidProtectionEx;
#else
using Facepunch.Extend;
using Oxide.Plugins.OfflineRaidProtectionEx;
#endif
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using Oxide.Core.Libraries;
using Oxide.Core.Plugins;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace
#if CARBON
Carbon.Plugins
#else
Oxide.Plugins
#endif
{
[Info("Offline Raid Protection", "realedwin/HunterZ", "1.3.1"), Description("Prevents/reduces offline raids by other players")]
public sealed class OfflineRaidProtection :
#if CARBON
CarbonPlugin
#else
RustPlugin
#endif
{
#region Fields
[PluginReference] private Plugin Clans;
private static OfflineRaidProtection Instance { get; set; }
private static ConfigData Configuration { get; set; }
private readonly Dictionary<ulong, LastOnlineData> _lastOnline = new();
private readonly Dictionary<ulong, PlayerScaleCache> _scaleCache = new();
private readonly Dictionary<string, List<ulong>> _clanMemberCache = new();
private readonly Dictionary<ulong, string> _clanTagCache = new();
private readonly Dictionary<uint, bool> _prefabCache = new();
private readonly Dictionary<uint, CupboardPrivilege> _tcCache = new();
private readonly List<float> _damageScaleKeys = new();
private readonly List<int> _absolutTimeScaleKeys = new();
#pragma warning disable IDE0044
// default to UTC
private System.TimeZoneInfo _timeZone = System.TimeZoneInfo.Utc;
#pragma warning restore IDE0044
#region Temp
// TODO: Refactor; some of these seem to be used to pass ephemeral state
// across methods, which is prone to bugs -HZ
private readonly List<ulong> _tmpList = new();
private readonly HashSet<ulong> _tmpHashSet = new();
private readonly HashSet<ulong> _tmpHashSet2 = new();
private readonly StringBuilder _sb = new();
private readonly TextTable _textTable = new();
#endregion Temp
#region Constants
private const string
// NOTE: Facepunch has broken this implementation, so we will just show
// normal toasts for now; these expire on their own, but I've kept the
// timing code in effect so that players can't generate console spam -HZ
// COMMAND_HIDEGAMETIP = "gametip.hidegametip",
// COMMAND_SHOWGAMETIP = "gametip.showgametip",
COMMAND_SHOWTOAST = "gametip.showtoast",
#if !CARBON
LANG_MESSAGE_NOPERMISSION = "You don't have the permission to use this command",
#endif
LANG_PROTECTION_MESSAGE_BUILDING = "Protection Message Building",
LANG_PROTECTION_MESSAGE_VEHICLE = "Protection Message Vehicle",
MESSAGE_INVALID_SYNTAX = "Invalid Syntax",
MESSAGE_PLAYER_NOT_FOUND = "No player found",
MESSAGE_TITLE_SIZE = "15",
TEXT_CLAN_MEMBER = "Clan Members",
TEXT_TEAM_MEMBER = "Team Members";
#region Colors
private const string
COLOR_AQUA = "#1ABC9C",
COLOR_BLUE = "#3498DB",
COLOR_DARK_GREEN = "#1F8B4C",
COLOR_GREEN = "#57F287",
COLOR_ORANGE = "#E67E22",
COLOR_RED = "#ED4245",
COLOR_WHITE = "white",
COLOR_YELLOW = "#FFFF00";
#endregion Colors
#endregion Constants
#endregion Fields
#region Classes
private sealed class ConfigData
{
[JsonProperty(PropertyName = "Raid Protection Options")]
public RaidProtectionOptions RaidProtection { get; set; }
[JsonProperty(PropertyName = "Team Options")]
public TeamOptions Team { get; set; }
[JsonProperty(PropertyName = "Command Options")]
public CommandOptions Command { get; set; }
[JsonProperty(PropertyName = "Permission Options")]
public PermissionOptions Permission { get; set; }
[JsonProperty(PropertyName = "Other Options")]
public OtherOptions Other { get; set; }
[JsonProperty(PropertyName = "Timezone Options")]
public TimeZoneOptions TimeZone { get; set; }
public VersionNumber Version { get; set; }
public sealed class RaidProtectionOptions
{
[JsonProperty(PropertyName = "Only mitigate damage caused by players")]
public bool OnlyPlayerDamage { get; set; }
[JsonProperty(PropertyName = "Protect players that are online")]
public bool OnlineRaidProtection { get; set; }
[JsonProperty(PropertyName = "Scale of damage depending on the current hour of the real day")]
public Dictionary<int, float> AbsoluteTimeScale { get; set; }
[JsonProperty(PropertyName = "Scale of damage depending on the offline time in hours")]
public Dictionary<float, float> DamageScale { get; set; }
[JsonProperty(PropertyName = "Cooldown in minutes")]
public int CooldownMinutes { get; set; }
[JsonProperty(PropertyName = "Online time to qualify for offline raid protection in minutes")]
public int CooldownQualifyMinutes { get; set; }
[JsonProperty(PropertyName = "Scale of damage between the cooldown and the first configured time")]
public float InterimDamage { get; set; }
[JsonProperty(PropertyName = "Protect all prefabs")]
public bool ProtectAll { get; set; }
[JsonProperty(PropertyName = "Protect AI (animals, NPCs, Bradley and attack helicopters etc.) if 'Protect all Prefabs' is enabled")]
public bool ProtectAi { get; set; }
[JsonProperty(PropertyName = "Protect modular and tug boats")]
public bool ProtectBaseBoats { get; set; }
[JsonProperty(PropertyName = "Protect vehicles")]
public bool ProtectVehicles { get; set; }
[JsonProperty(PropertyName = "Protect twigs")]
public bool ProtectTwigs { get; set; }
[JsonProperty(PropertyName = "Protect decaying buildings")]
public bool ProtectDecayingBase { get; set; }
[JsonProperty(PropertyName = "Ignore wood decay if only due to twig")]
public bool DecayIgnoreTwig { get; set; }
[JsonProperty(PropertyName = "Prefabs to protect")]
public HashSet<string> Prefabs { get; set; }
[JsonProperty(PropertyName = "Prefabs blacklist")]
public HashSet<string> PrefabsBlacklist { get; set; }
}
public sealed class TeamOptions
{
[JsonProperty(PropertyName = "Enable team offline protection sharing")]
public bool TeamShare { get; set; }
[JsonProperty(PropertyName = "Mitigate damage by the team-mate who was offline the longest")]
public bool TeamFirstOffline { get; set; }
[JsonProperty(PropertyName = "Include players that are whitelisted on Codelocks")]
public bool IncludeWhitelistPlayers { get; set; }
[JsonProperty(PropertyName = "Prevent players from leaving or disbanding their team if at least one team member is offline")]
public bool TeamAvoidAbuse { get; set; }
[JsonProperty(PropertyName = "Enable offline raid protection penalty for leaving or disbanding a team")]
public bool TeamEnablePenalty { get; set; }
[JsonProperty(PropertyName = "Penalty duration in hours")]
public float TeamPenaltyDuration { get; set; }
}
public sealed class CommandOptions
{
[JsonProperty(PropertyName = "Commands to check offline protection status")]
public string[] Commands { get; set; }
[JsonProperty(PropertyName = "Command to display offline raid protection information")]
public string CommandHelp { get; set; }
[JsonProperty(PropertyName = "Command to fill the offline times of all players")]
public string CommandFillOnlineTimes { get; set; }
[JsonProperty(PropertyName = "Command to update the permission status for all players.")]
public string CommandUpdatePermissions { get; set; }
[JsonProperty(PropertyName = "Command to change a player's offline time")]
public string CommandTestOffline { get; set; }
[JsonProperty(PropertyName = "Command to change a player's offline time to the current time")]
public string CommandTestOnline { get; set; }
[JsonProperty(PropertyName = "Command to change a player's penalty duration")]
public string CommandTestPenalty { get; set; }
[JsonProperty(PropertyName = "Command to update the Prefabs to protect list")]
public string CommandUpdatePrefabList { get; set; }
[JsonProperty(PropertyName = "Command to dump the Prefabs to protect list")]
public string CommandDumpPrefabList { get; set; }
#if CARBON
[JsonIgnore]
private int _commandCooldown;
[JsonProperty(PropertyName = "Command cooldown in seconds")]
public int CommandCooldown
{
get => _commandCooldown;
set => _commandCooldown = System.Math.Max(0, value);
}
#endif
internal void RegisterCommands(Plugin plugin, OfflineRaidProtection offlineRaidProtection)
{
RegisterChatCommands(Commands, plugin, offlineRaidProtection.cmdStatus, Configuration.Permission.Check);
RegisterChatCommands(new[] {CommandHelp}, plugin, offlineRaidProtection.cmdHelp, Configuration.Permission.Protect);
RegisterChatCommands(new[] {CommandFillOnlineTimes}, plugin, offlineRaidProtection.cmdFillOnlineTimes, Configuration.Permission.Admin);
RegisterChatCommands(new[] {CommandTestOffline}, plugin, offlineRaidProtection.cmdTestOffline, Configuration.Permission.Admin);
RegisterChatCommands(new[] {CommandTestOnline}, plugin, offlineRaidProtection.cmdTestOnline, Configuration.Permission.Admin);
RegisterChatCommands(new[] {CommandTestPenalty}, plugin, offlineRaidProtection.cmdTestPenalty, Configuration.Permission.Admin);
RegisterConsoleCommands(new[] {CommandFillOnlineTimes}, plugin, nameof(Instance.ccFillOnlineTimes), Configuration.Permission.Admin);
RegisterConsoleCommands(new[] {CommandUpdatePermissions}, plugin, nameof(Instance.ccUpdatePermissions), Configuration.Permission.Admin);
RegisterConsoleCommands(new[] {CommandUpdatePrefabList}, plugin, nameof(Instance.ccUpdatePrefabList), Configuration.Permission.Admin);
RegisterConsoleCommands(new[] {CommandDumpPrefabList}, plugin, nameof(Instance.ccDumpPrefabList), Configuration.Permission.Admin);
}
private void RegisterChatCommands(string[] commands, Plugin plugin, System.Action<BasePlayer, string, string[]> callback, string permission)
{
foreach (var command in commands)
#if CARBON
Community.Runtime.Core.cmd.AddChatCommand(command, plugin, callback, cooldown: CommandCooldown * 1000, permissions: new[] {permission});
#else
Instance.cmd.AddChatCommand(command, plugin, callback);
#endif
}
private void RegisterConsoleCommands(string[] commands, Plugin plugin, string callback, string permission)
{
foreach (var command in commands)
#if CARBON
Community.Runtime.Core.cmd.AddConsoleCommand(command, plugin, callback, cooldown: CommandCooldown * 1000, permissions: new[] {permission});
#else
Instance.cmd.AddConsoleCommand(command, plugin, callback);
#endif
}
}
public sealed class PermissionOptions
{
[JsonProperty(PropertyName = "Permission required to enable offline protection")]
public string Protect { get; set; }
[JsonProperty(PropertyName = "Permission required to check offline protection status")]
public string Check { get; set; }
[JsonProperty(PropertyName = "Permission required to use admin functions")]
public string Admin { get; set; }
internal void RegisterPermissions(Permission permission, Plugin plugin)
{
string[] permissions = {Protect, Check, Admin};
foreach (var perm in permissions)
permission.RegisterPermission(perm, plugin);
}
}
public sealed class OtherOptions
{
[JsonProperty(PropertyName = "Play sound when damage is mitigated")]
public bool PlaySound { get; set; }
[JsonProperty(PropertyName = "Asset path of the sound to be played")]
public string SoundPath { get; set; }
[JsonProperty(PropertyName = "Display a game tip message when a prefab is protected")]
public bool ShowMessage { get; set; }
[JsonProperty(PropertyName = "Game tip message shows remaining protection time")]
public bool ShowRemainingTime { get; set; }
[JsonProperty(PropertyName = "Message duration in seconds")]
public float MessageDuration { get; set; }
}
public sealed class TimeZoneOptions
{
#if CARBON
[JsonProperty(PropertyName = "Timezone for Windows")]
public string WinTimeZone { get; set; }
[JsonProperty(PropertyName = "Timezone for Linux")]
public string UnixTimeZone { get; set; }
#else
[JsonProperty(PropertyName = "Timezone")]
public string TimeZone { get; set; }
#endif
}
}
private sealed class LastOnlineData
{
[JsonProperty(PropertyName = "User ID")]
public ulong UserID
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
[JsonProperty(PropertyName = "User Name")]
public string UserName
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
[JsonProperty(PropertyName = "Last Online")]
public long LastOnline
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
[JsonProperty(PropertyName = "End of Penalty")]
public long PenaltyEnd
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
[JsonProperty(PropertyName = "Last Connect")]
public long LastConnect
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
[JsonIgnore]
public System.DateTime LastOnlineDT
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => System.DateTime.FromBinary(LastOnline);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => LastOnline = value.ToBinary();
}
[JsonIgnore]
public System.DateTime PenaltyEndDT
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(PenaltyEnd);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set => PenaltyEnd = value.Ticks;
}
[JsonIgnore]
public System.DateTime LastConnectDT
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => System.DateTime.FromBinary(LastConnect);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => LastConnect = value.ToBinary();
}
[JsonConstructor]
public LastOnlineData(
in ulong userid, in string userName, in long lastOnline,
in long lastConnect)
{
UserID = userid;
UserName = userName;
LastOnline = lastOnline;
LastConnect = lastConnect;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LastOnlineData(
in BasePlayer player, in System.DateTime currentTime,
in bool connected = false) :
this(player.userID.Get(), player.displayName, 0, 0)
{
LastOnlineDT = currentTime;
LastConnectDT = connected ? currentTime : LastConnectDT;
}
// [JsonIgnore] public float Days => (float)TimeSpanSinceLastOnline.TotalDays;
[JsonIgnore] public float Minutes =>
(float)TimeSpanSinceLastOnline.TotalMinutes;
[JsonIgnore] public float Hours =>
(float)TimeSpanSinceLastOnline.TotalHours;
[JsonIgnore] private System.TimeSpan TimeSpanSinceLastOnline =>
System.DateTime.UtcNow - (!IsOnline ? LastOnlineDT : System.DateTime.UtcNow);
[JsonIgnore] private BasePlayer Player => PlayerManager.GetPlayer(UserID);
[JsonIgnore] public bool IsOnline => true == Player?.IsConnected;
[JsonIgnore] public bool IsOffline =>
!IsOnline && Minutes >= Configuration.RaidProtection.CooldownMinutes;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnablePenalty(in float duration) =>
PenaltyEndDT = System.DateTime.UtcNow.AddHours(duration);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void DisablePenalty() => PenaltyEnd = 0L;
}
private sealed class PlayerScaleCache
{
public float Scale
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
public long Expires
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set;
}
public bool ActiveGameTipMessage
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
public System.TimeSpan RemainingTime
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
public bool HasPermission
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set;
}
public System.Action HideGameTipAction
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set;
}
public string ProtectionMessageBuilding
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set;
}
public string ProtectionMessageVehicle
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PlayerScaleCache(
System.DateTime expires, float scale, bool hasPermission)
{
ExpiresDT = expires;
Scale = scale;
ActiveGameTipMessage = false;
HasPermission = hasPermission;
HideGameTipAction = null;
}
public System.DateTime ExpiresDT
{
// get => new(Expires);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Expires = value.Ticks;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CacheAction(BasePlayer player) =>
HideGameTipAction = GetAction(player, this);
private void ClearAction() => HideGameTipAction = null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static System.Action GetAction(
BasePlayer player, PlayerScaleCache playerScaleCache)
{
return () =>
{
playerScaleCache.ActiveGameTipMessage = false;
// if (player)
// player.SendConsoleCommand(COMMAND_HIDEGAMETIP);
// else
if (!player)
playerScaleCache.ClearAction();
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CacheMessages(in string userID)
{
ProtectionMessageBuilding =
Instance.Msg(LANG_PROTECTION_MESSAGE_BUILDING, userID);
ProtectionMessageVehicle =
Instance.Msg(LANG_PROTECTION_MESSAGE_VEHICLE, userID);
}
}
// TODO: Refactor - MrBlue says static data in plugins is terrifying -HZ
private static class PlayerManager
{
private static readonly Dictionary<ulong, BasePlayer> PlayersByUserID =
new();
private static readonly Dictionary<string, BasePlayer> PlayersByName =
new();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AddPlayer(in BasePlayer player)
{
PlayersByUserID[player.userID.Get()] = player;
PlayersByName[player.displayName] = player;
}
// public static void RemovePlayer(in BasePlayer player)
// {
// PlayersByUserID.Remove(player.userID.Get());
// PlayersByName.Remove(player.displayName);
// }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static BasePlayer GetPlayer(in ulong userID) =>
PlayersByUserID.GetValueOrDefault(userID, null);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static BasePlayer GetPlayer(in string displayName) =>
PlayersByName.TryGetValue(displayName, out var player) ||
ulong.TryParse(displayName, out var userID) &&
PlayersByUserID.TryGetValue(userID, out player) ?
player : null;
public static void Clear()
{
PlayersByUserID.Clear();
PlayersByName.Clear();
}
}
private sealed class CupboardPrivilege
{
// public BuildingPrivlidge BuildingPrivlidge { get; set; }
// public float LastProtectedMinutes { get; set; }
public bool IsDecaying { get; set; }
public CupboardPrivilege(
in BuildingPrivlidge buildingPrivlidge, in float lastProtectedMinutes,
in bool isDecaying = false)
{
// BuildingPrivlidge = buildingPrivlidge;
// LastProtectedMinutes = lastProtectedMinutes;
IsDecaying = isDecaying;
}
}
#endregion Classes
#region Data
private void SaveData() =>
Interface.Oxide.DataFileSystem.WriteObject(
$"{Name}/{nameof(LastOnlineData)}", _lastOnline);
private void Save()
{
UpdateLastOnlineAll();
SaveData();
}
private void LoadData()
{
try
{
var data =
Interface.Oxide.DataFileSystem.ReadObject<Dictionary<ulong, LastOnlineData>>(
$"{Name}/{nameof(LastOnlineData)}");
_lastOnline.ClearAndMergeWith(data);
}
catch (System.Exception ex)
{
PrintError(ex.ToString());
}
}
#endregion Data
#region Config
protected override void LoadDefaultConfig() =>
Configuration = GetBaseConfig(Version);
protected override void SaveConfig() =>
Config.WriteObject(Configuration, true);
protected override void LoadConfig()
{
base.LoadConfig();
try
{
Configuration = Config.ReadObject<ConfigData>();
if (Configuration.Version < Version)
UpdateConfigValues();
Config.WriteObject(Configuration, true);
SetTimeZone();
}
catch (System.Exception ex)
{
PrintError($"There is an error in your configuration file. Using default settings\n{ex}");
LoadDefaultConfig();
}
}
private void UpdateConfigValues()
{
PrintWarning("Config update detected! Update config values...");
var baseConfig = GetBaseConfig(Version);
if (Configuration.Version < new VersionNumber(1, 1, 8))
Configuration.Command.CommandUpdatePermissions =
baseConfig.Command.CommandUpdatePermissions;
if (Configuration.Version < new VersionNumber(1, 1, 15))
{
Configuration.Command.CommandUpdatePrefabList =
baseConfig.Command.CommandUpdatePrefabList;
Configuration.Command.CommandDumpPrefabList =
baseConfig.Command.CommandDumpPrefabList;
Configuration.RaidProtection.CooldownQualifyMinutes =
baseConfig.RaidProtection.CooldownQualifyMinutes;
}
if (Configuration.Version < new VersionNumber(1, 1, 16))
{
DeleteMessages();
LoadDefaultMessages();
Configuration.RaidProtection.ProtectDecayingBase =
baseConfig.RaidProtection.ProtectDecayingBase;
}
Configuration.Version = Version;
SaveConfig();
PrintWarning("Config update has been completed!");
}
private void SetTimeZone()
{
var id =
#if !CARBON
Configuration.TimeZone.TimeZone;
#elif WIN
Configuration.TimeZone.WinTimeZone;
#elif UNIX
Configuration.TimeZone.UnixTimeZone;
#endif
if (!string.IsNullOrEmpty(id)) _timeZone = GetTimeZoneByID(id);
}
private static System.TimeZoneInfo GetTimeZoneByID(string id)
{
foreach (var tz in System.TimeZoneInfo.GetSystemTimeZones())
{
if (tz.Id == id) return tz;
}
return System.TimeZoneInfo.Utc;
}
private static ConfigData GetBaseConfig(VersionNumber version) => new()
{
RaidProtection = new()
{
OnlyPlayerDamage = false,
OnlineRaidProtection = false,
AbsoluteTimeScale = new(),
CooldownMinutes = 10,
CooldownQualifyMinutes = 0,
DamageScale = new()
{
{ 12f, 0.25f },
{ 24f, 0.5f },
{ 48f, 1f },
},
InterimDamage = 0f,
ProtectAll = false,
ProtectAi = false,
ProtectBaseBoats = false,
ProtectVehicles = true,
ProtectTwigs = false,
ProtectDecayingBase = true,
DecayIgnoreTwig = false,
Prefabs = GetPrefabNames(),
PrefabsBlacklist = new()
},
Team = new()
{
TeamShare = true,
TeamFirstOffline = false,
IncludeWhitelistPlayers = false,
TeamAvoidAbuse = false,
TeamEnablePenalty = false,
TeamPenaltyDuration = 24f
},
Command = new()
{
Commands = new[] { "ao", "orp" },
CommandHelp = "raidprot",
CommandFillOnlineTimes = "orp.fill.onlinetimes",
CommandUpdatePermissions = "orp.update.permissions",
CommandTestOffline = "orp.test.offline",
CommandTestOnline = "orp.test.online",
CommandTestPenalty = "orp.test.penalty",
CommandUpdatePrefabList = "orp.update.prefabs",
CommandDumpPrefabList = "orp.dump.prefabs",
#if CARBON
CommandCooldown = 1
#endif
},
Permission = new()
{
Protect = "offlineraidprotection.protect",
Check = "offlineraidprotection.check",
Admin = "offlineraidprotection.admin"
},
Other = new()
{
PlaySound = false,
SoundPath = "assets/prefabs/locks/keypad/effects/lock.code.denied.prefab",
ShowMessage = true,
ShowRemainingTime = false,
MessageDuration = 3f
},
TimeZone = new()
{
#if CARBON
WinTimeZone = "W. Europe Standard Time",
UnixTimeZone = "Europe/Berlin"
#else
TimeZone = ""
#endif
},
Version = version
};
private static HashSet<string> GetPrefabNames()
{
var prefabNames = new HashSet<string>();
foreach (var itemDef in ItemManager.GetItemDefinitions())
{
var shortName = GetShortName(
itemDef?.GetComponent<ItemModDeployable>()?.entityPrefab?.resourcePath);
if (!string.IsNullOrEmpty(shortName))
prefabNames.Add(shortName);
}
var manifest = GameManifest.Current;
if (!manifest)
return prefabNames;
foreach (var entity in manifest.entities)
{
if (string.IsNullOrEmpty(entity))
continue;
var shortName =
GameManager.server.FindPrefab(entity)?.GetComponent<BaseVehicle>()?.ShortPrefabName;
if (!string.IsNullOrEmpty(shortName))
prefabNames.Add(shortName);
}
return prefabNames;
}
#endregion Config
#region Hooks
private void Loaded()
{
// This seems sus; why not just overwrite unconditionally? -HZ
Instance ??= this;
Configuration.Permission.RegisterPermissions(permission, this);
Configuration.Command.RegisterCommands(this, this);
LoadData();
UnsubscribeHooks();
}
private void OnServerInitialized() => CacheData();
private void OnNewSave(string _filename)
{
_lastOnline.Clear();
SaveData();
}
// TODO: Refactor - this is problematic for a couple of reasons:
// 1. Saves even when nothing has changed
// 2. Saving around when the server does has a higher change of causing lag
private void OnServerSave() =>
ServerMgr.Instance.Invoke(Instance.Save, 10f);
private void OnServerShutdown() => Save();
private void Unload()
{
Save();
Configuration = null;
Instance = null;
Clans = null;
_prefabCache.Clear();
_scaleCache.Clear();
_lastOnline.Clear();
_damageScaleKeys.Clear();
_absolutTimeScaleKeys.Clear();
_tcCache.Clear();
_tmpList.Clear();
_tmpHashSet.Clear();
_tmpHashSet2.Clear();
_sb.Clear();
_textTable.Clear();
FreeAllClanPoolLists();
_clanMemberCache.Clear();
_clanTagCache.Clear();
PlayerManager.Clear();
// foreach (var player in BasePlayer.activePlayerList)
// {
// if (!player)
// return;
//
// player.SendConsoleCommand(COMMAND_HIDEGAMETIP);
// }
}
private void OnPluginLoaded(Plugin plugin)
{
if (plugin.Name is nameof(Clans))
Clans = plugin;
}
private void OnPluginUnloaded(Plugin plugin)
{
if (plugin.Name is nameof(Clans))
Clans = null;
}
private void OnPlayerConnected(BasePlayer player)
{
if (!player)
return;
var currentTime = System.DateTime.UtcNow;
UpdateLastOnline(player, currentTime);
UpdateLastConnect(player, currentTime);
PlayerManager.AddPlayer(player);
if (_scaleCache.TryGetValue(player.userID.Get(), out var scaleCache))
{
scaleCache.CacheAction(player);
}
else
{
scaleCache = new(
currentTime, -1f,
player.userID.Get().HasPermission(Configuration.Permission.Protect));
_scaleCache[player.userID.Get()] = scaleCache;
}
scaleCache.CacheMessages(player.UserIDString);
}
private void OnPlayerDisconnected(BasePlayer player)
{
if (!player)
return;
var currentTime = System.DateTime.UtcNow;
UpdateLastOnline(player, currentTime);
}
private void OnUserNameUpdated(string id, string _oldName, string newName)
{
if (_lastOnline.TryGetValue(ulong.Parse(id), out var lastOnline))
lastOnline.UserName = newName;
}
private void OnCupboardProtectionCalculated(
BuildingPrivlidge buildingPrivlidge, float cachedProtectedMinutes)
{
if (!buildingPrivlidge || buildingPrivlidge.buildingID is 0U)
return;
if (!_tcCache.TryGetValue(buildingPrivlidge.buildingID, out var tc))
{
_tcCache[buildingPrivlidge.buildingID] =
new CupboardPrivilege(buildingPrivlidge, cachedProtectedMinutes)
{
IsDecaying =
IsBuildingDecaying(buildingPrivlidge, cachedProtectedMinutes > 0)
};
return;
}
// **** The following line was not in the Carbon version for some reason;
// looks like it and LastProtectedMinutes aren't being used, so I've
// commented them out for now -HZ
// tc.BuildingPrivlidge = buildingPrivlidge;
// tc.LastProtectedMinutes = cachedProtectedMinutes;
tc.IsDecaying =
IsBuildingDecaying(buildingPrivlidge, cachedProtectedMinutes > 0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private object OnEntityTakeDamage(BaseCombatEntity entity, HitInfo hitInfo)
{
if (hitInfo is null || !entity)
return null;
// Abort on non-player damage if non-player damage mitigation disabled
if (Configuration.RaidProtection.OnlyPlayerDamage &&
!hitInfo.InitiatorPlayer)
return null;
// Abort on self-damage
if (hitInfo.Initiator == entity)
return null;
// Abort if decay damage or non-protected entity
if (hitInfo.damageTypes.Has(Rust.DamageType.Decay) ||
!IsProtected(entity))