-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandcuffLimiter.cs
More file actions
1717 lines (1374 loc) · 55.9 KB
/
HandcuffLimiter.cs
File metadata and controls
1717 lines (1374 loc) · 55.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
/*
* HandcuffLimiter
* Rust uMod plugin that prevents restraint abuse by enforcing maximum handcuff duration and safely teleporting victims to Outpost or Bandit Camp.
* Also gives captives a unique opportunity to punish or forgive their captors.
*
* Copyright (C) 2026 SeesAll
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Commercial Licensing:
* While this software is available under GPLv3 for open-source use,
* commercial redistribution, resale, bundling in paid packages,
* or closed-source modifications require a separate commercial license.
*
* For commercial licensing inquiries, contact:
* (SeesAll on uMod | N01B4ME on Discord)
*/
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using Rust;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("HandcuffLimiter", "SeesAll", "0.8.5")]
[Description("Prevents indefinite handcuff restraint by auto-releasing and teleporting restrained players to a safe monument after a configurable limit.")]
public class HandcuffLimiter : RustPlugin
{
#region Permissions
private const string PermExempt = "handcufflimiter.exempt";
private const string PermAdmin = "handcufflimiter.admin";
#endregion
#region Configuration
private PluginConfig _config;
private enum SafeDestination
{
Outpost = 1,
BanditCamp = 2
}
private class PluginConfig
{
public bool Enabled = true;
public int CheckIntervalSeconds = 2;
public float ExemptPermissionCacheSeconds = 10f; // performance: cache exempt permission lookups for this many seconds
public int MaxRestrainMinutes = 20;
public int WarnSecondsBeforeLimit = 60;
public bool WarnVictim = true;
[JsonProperty("Teleport Destination (outpost / bandit)")]
public string TeleportDestination = "outpost"; // "outpost" or "bandit"
[JsonProperty("Destination")]
public string LegacyDestination;
public bool ShouldSerializeLegacyDestination() => false;
public Vector3 DestinationOffset = new Vector3(0f, 1.5f, 0f);
public bool TeleportOnlyWithinSafeZone = true;
public float SafeZoneSearchRadius = 25f;
public int SafeZoneSearchAttempts = 8;
public float TeleportClearanceRadius = 0.6f;
public float TeleportClearanceHeight = 1.8f;
public float BuildingProximityRejectRadius = 6f;
public float TeleportAttemptTimeoutSeconds = 3.0f;
public bool CacheSafeTeleportSpots = true;
public float CacheBlacklistMinDistance = 6f;
public int BlacklistMaxEntriesPerDestination = 50;
public bool RemoveHoodBeforePrompt = false;
public int HoodRemoveSecondsBeforeLimit = 60;
public int VictimRecuffImmunitySeconds = 300;
public int EpisodeMergeWindowSeconds = 60;
public bool ChaosEnabled = false;
public bool ChaosOnlyOutsideSafeZones = true;
public int ChaosFuseSeconds = 10;
public int ChaosCooldownMinutesPerVictim = 1440;
public bool ChaosRadiusCheckPlayers = false;
public float ChaosRadiusCheckMeters = 6f;
public int ChaosMaxPlayersInRadius = 0;
public bool EnablePunishForgivePrompt = false;
public int PromptSecondsBeforeLimit = 60;
public bool DebugEnabled = true;
public int DebugTestSeconds = 60;
}
private SafeDestination ParseDestination(string value)
{
if (string.IsNullOrEmpty(value)) return SafeDestination.Outpost;
var v = value.Trim().ToLowerInvariant();
if (v == "1") return SafeDestination.Outpost;
if (v == "2") return SafeDestination.BanditCamp;
if (v == "outpost") return SafeDestination.Outpost;
if (v == "bandit" || v == "banditcamp" || v == "bandit camp") return SafeDestination.BanditCamp;
return SafeDestination.Outpost;
}
private int DestinationToInt() => (int)ParseDestination(_config?.TeleportDestination);
protected override void LoadDefaultConfig()
{
_config = new PluginConfig();
SaveConfig();
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<PluginConfig>() ?? new PluginConfig();
if (!string.IsNullOrEmpty(_config.LegacyDestination))
{
var legacyParsed = ParseDestination(_config.LegacyDestination);
if (string.IsNullOrEmpty(_config.TeleportDestination) ||
(_config.TeleportDestination.Trim().Equals("outpost", StringComparison.OrdinalIgnoreCase) && legacyParsed == SafeDestination.BanditCamp))
{
_config.TeleportDestination = (legacyParsed == SafeDestination.BanditCamp) ? "bandit" : "outpost";
}
}
}
catch
{
PrintWarning("Config is invalid/corrupted; loading default values.");
_config = new PluginConfig();
}
if (_config.MaxRestrainMinutes < 1) _config.MaxRestrainMinutes = 1;
if (_config.CheckIntervalSeconds < 1) _config.CheckIntervalSeconds = 1;
if (_config.CheckIntervalSeconds > 30) _config.CheckIntervalSeconds = 30;
if (_config.WarnSecondsBeforeLimit < 0) _config.WarnSecondsBeforeLimit = 0;
if (_config.ChaosFuseSeconds < 0) _config.ChaosFuseSeconds = 0;
if (_config.SafeZoneSearchAttempts < 1) _config.SafeZoneSearchAttempts = 1;
if (_config.SafeZoneSearchAttempts > 25) _config.SafeZoneSearchAttempts = 25;
if (_config.SafeZoneSearchRadius < 0f) _config.SafeZoneSearchRadius = 0f;
if (_config.TeleportClearanceRadius < 0.1f) _config.TeleportClearanceRadius = 0.1f;
if (_config.TeleportClearanceRadius > 3f) _config.TeleportClearanceRadius = 3f;
if (_config.TeleportClearanceHeight < 0.5f) _config.TeleportClearanceHeight = 0.5f;
if (_config.TeleportClearanceHeight > 5f) _config.TeleportClearanceHeight = 5f;
if (_config.PromptSecondsBeforeLimit < 0) _config.PromptSecondsBeforeLimit = 0;
if (_config.DebugTestSeconds < 5) _config.DebugTestSeconds = 5;
if (_config.HoodRemoveSecondsBeforeLimit < 0) _config.HoodRemoveSecondsBeforeLimit = 0;
if (_config.CacheBlacklistMinDistance < 0f) _config.CacheBlacklistMinDistance = 0f;
if (_config.TeleportAttemptTimeoutSeconds < 0f) _config.TeleportAttemptTimeoutSeconds = 0f;
if (_config.ExemptPermissionCacheSeconds < 0f) _config.ExemptPermissionCacheSeconds = 0f; if (_config.BlacklistMaxEntriesPerDestination < 0) _config.BlacklistMaxEntriesPerDestination = 0;
SaveConfig();
}
protected override void SaveConfig() => Config.WriteObject(_config, true);
#endregion
#region Lang
private const string MsgVictimWarn = "VictimWarn";
private const string MsgVictimAction = "VictimAction";
private const string MsgAdminNoPerm = "AdminNoPerm";
private const string MsgAdminUsage = "AdminUsage";
private const string MsgAdminStatus = "AdminStatus";
private const string MsgAdminNotFound = "AdminNotFound";
private const string MsgAdminReset = "AdminReset";
private const string MsgPromptTitle = "PromptTitle";
private const string MsgPromptBody = "PromptBody";
private const string MsgPromptPunish = "PromptPunish";
private const string MsgPromptForgive = "PromptForgive";
private const string MsgDebugStarted = "DebugStarted";
private const string MsgDebugStopped = "DebugStopped";
private const string MsgDebugDisabled = "DebugDisabled";
private const string MsgCacheCleared = "CacheCleared";
private const string MsgCacheUsage = "CacheUsage";
private const string MsgWearListHeader = "WearListHeader";
private const string MsgWearListLine = "WearListLine";
private void Init()
{
permission.RegisterPermission(PermExempt, this);
permission.RegisterPermission(PermAdmin, this);
lang.RegisterMessages(new Dictionary<string, string>
{
[MsgVictimWarn] = "You have been restrained for a long time. If you are still restrained in {0} seconds, you will be released and moved to a safe location.",
[MsgVictimAction] = "You were restrained too long. You have been released and moved to a safe location.",
[MsgAdminNoPerm] = "You don't have permission to use that command.",
[MsgAdminUsage] = "Usage: /hcl status <nameOrId> OR /hcl reset <nameOrId> OR /hcl debug OR /hcl debugoff OR /hcl clearcache [outpost|bandit|all] OR /hcl wear <nameOrId>",
[MsgAdminNotFound] = "Player not found.",
[MsgAdminStatus] = "{0} restrained={1}, tracked={2}, elapsed={3}s, debug={4}",
[MsgAdminReset] = "Tracking state reset for {0}.",
[MsgPromptTitle] = "Punish or Forgive?",
[MsgPromptBody] = "You're about to be freed. Choose what happens when you teleport out.",
[MsgPromptPunish] = "Punish",
[MsgPromptForgive] = "Forgive",
[MsgDebugStarted] = "Debug test started: you have been restrained for {0} seconds.",
[MsgDebugStopped] = "Debug test stopped.",
[MsgDebugDisabled] = "Debug mode is disabled in the config.",
[MsgCacheUsage] = "Usage: /hcl clearcache [outpost|bandit|all] OR /hcl wear <nameOrId>",
[MsgCacheCleared] = "Cleared cached safe teleport spot for: {0}. It will be re-learned on the next rescue.",
["WearListHeader"] = "Wear items for {0}:",
["WearListLine"] = "- {0} (itemid {1})"
}, this);
}
#endregion
#region Data
private const int MaxLogEntries = 2000;
private StoredData _data;
private class StoredData
{
public string MapId;
public Dictionary<ulong, long> LastChaosUtc = new Dictionary<ulong, long>();
public Dictionary<int, SerializableVector3> CachedSafeSpots = new Dictionary<int, SerializableVector3>();
public Dictionary<int, List<SerializableVector3>> BlacklistedSpots = new Dictionary<int, List<SerializableVector3>>();
public List<LogEntry> Log = new List<LogEntry>();
}
private class SerializableVector3
{
public float x, y, z;
public SerializableVector3() { }
public SerializableVector3(Vector3 v) { x = v.x; y = v.y; z = v.z; }
public Vector3 ToVector3() => new Vector3(x, y, z);
}
private class LogEntry
{
public long Utc;
public ulong VictimId;
public string VictimName;
public int DurationSeconds;
public int Destination;
public int Choice;
public bool ChaosDropped;
}
private void LoadData()
{
_data = Interface.Oxide.DataFileSystem.ReadObject<StoredData>(Name) ?? new StoredData();
if (_data.LastChaosUtc == null) _data.LastChaosUtc = new Dictionary<ulong, long>();
if (_data.Log == null) _data.Log = new List<LogEntry>();
if (_data.CachedSafeSpots == null) _data.CachedSafeSpots = new Dictionary<int, SerializableVector3>();
if (_data.BlacklistedSpots == null) _data.BlacklistedSpots = new Dictionary<int, List<SerializableVector3>>();
}
private void SaveData() => Interface.Oxide.DataFileSystem.WriteObject(Name, _data);
private string GetCurrentMapId()
{
try
{
var seed = ConVar.Server.seed;
var size = ConVar.Server.worldsize;
var level = ConVar.Server.level ?? string.Empty;
return $"{seed}:{size}:{level}";
}
catch
{
return "unknown";
}
}
private void WipeData(string reason)
{
if (_data == null) _data = new StoredData();
_data.MapId = GetCurrentMapId();
_data.LastChaosUtc.Clear();
_data.Log.Clear();
_data.CachedSafeSpots.Clear();
_data.BlacklistedSpots.Clear();
SaveData();
Puts($"Data wiped ({reason}).");
}
#endregion
#region State
private class RestrainState
{
public ulong VictimId;
public double EpisodeStartUtc;
public double LastSeenUnrestrainedUtc;
public bool Warned;
public bool IsCurrentlyRestrained;
public bool PromptShown;
public int Choice;
public bool Debug;
public int DebugMaxSeconds;
public bool HoodRemoved;
}
private readonly Dictionary<ulong, RestrainState> _stateByVictim = new Dictionary<ulong, RestrainState>();
private readonly Dictionary<ulong, double> _immuneUntilUtc = new Dictionary<ulong, double>();
private struct PermCacheEntry
{
public bool Value;
public double ExpiresUtc;
}
private readonly Dictionary<ulong, PermCacheEntry> _exemptPermCache = new Dictionary<ulong, PermCacheEntry>();
private Timer _pollTimer;
private readonly Dictionary<int, Vector3> _monumentCenterByDest = new Dictionary<int, Vector3>();
private class PendingTeleport
{
public int Destination;
public Vector3 Center;
public int AttemptsRemaining;
public float Radius;
public bool TriedCached;
public double StartedUtc;
}
private readonly Dictionary<ulong, PendingTeleport> _pendingTeleports = new Dictionary<ulong, PendingTeleport>();
private const string UiLayer = "HandcuffLimiter.UI";
#endregion
#region Hooks
private void OnServerInitialized()
{
if (!_config.Enabled) return;
LoadData();
var mapId = GetCurrentMapId();
if (string.IsNullOrEmpty(_data.MapId) || !_data.MapId.Equals(mapId, StringComparison.Ordinal))
WipeData("map identity changed");
CacheMonumentCenter(DestinationToInt());
StartPolling();
}
private void OnNewSave(string filename)
{
if (_data != null)
WipeData("OnNewSave");
}
private void Unload()
{
_pollTimer?.Destroy();
var players = BasePlayer.activePlayerList;
if (players != null)
{
for (var i = 0; i < players.Count; i++)
{
var p = players[i];
if (p != null) DestroyPromptUi(p);
}
}
_stateByVictim.Clear();
_immuneUntilUtc.Clear();
_monumentCenterByDest.Clear();
_pendingTeleports.Clear();
_exemptPermCache.Clear();
if (_data != null) SaveData();
}
private void OnPlayerDisconnected(BasePlayer player, string reason)
{
if (player == null) return;
DestroyPromptUi(player);
_stateByVictim.Remove(player.userID);
_immuneUntilUtc.Remove(player.userID);
_pendingTeleports.Remove(player.userID);
_exemptPermCache.Remove(player.userID);
}
private void OnPlayerDeath(BasePlayer player, HitInfo info)
{
if (player == null) return;
DestroyPromptUi(player);
_stateByVictim.Remove(player.userID);
_immuneUntilUtc.Remove(player.userID);
_pendingTeleports.Remove(player.userID);
_exemptPermCache.Remove(player.userID);
}
#endregion
#region Commands
[ChatCommand("hcl")]
private void CmdHcl(BasePlayer player, string command, string[] args)
{
if (player == null) return;
if (!permission.UserHasPermission(player.UserIDString, PermAdmin))
{
player.ChatMessage(lang.GetMessage(MsgAdminNoPerm, this, player.UserIDString));
return;
}
if (args == null || args.Length < 1)
{
player.ChatMessage(lang.GetMessage(MsgAdminUsage, this, player.UserIDString));
return;
}
var sub = args[0].ToLowerInvariant();
if (sub == "debug")
{
if (!_config.DebugEnabled)
{
player.ChatMessage(lang.GetMessage(MsgDebugDisabled, this, player.UserIDString));
return;
}
StartDebugEpisode(player);
player.ChatMessage(string.Format(lang.GetMessage(MsgDebugStarted, this, player.UserIDString), _config.DebugTestSeconds));
return;
}
if (sub == "debugoff")
{
StopDebugEpisode(player);
player.ChatMessage(lang.GetMessage(MsgDebugStopped, this, player.UserIDString));
return;
}
if (sub == "clearcache")
{
var which = args.Length >= 2 ? args[1] : "all";
if (!TryClearCache(which, out var cleared))
{
player.ChatMessage(lang.GetMessage(MsgCacheUsage, this, player.UserIDString));
return;
}
if (sub == "wear")
{
if (args.Length < 2)
{
player.ChatMessage(lang.GetMessage(MsgAdminUsage, this, player.UserIDString));
return;
}
var targetWear = FindPlayer(args[1]);
if (targetWear == null)
{
player.ChatMessage(lang.GetMessage(MsgAdminNotFound, this, player.UserIDString));
return;
}
ShowWearList(player, targetWear);
return;
}
player.ChatMessage(string.Format(lang.GetMessage(MsgCacheCleared, this, player.UserIDString), cleared));
return;
}
if (args.Length < 2)
{
player.ChatMessage(lang.GetMessage(MsgAdminUsage, this, player.UserIDString));
return;
}
var target = FindPlayer(args[1]);
if (target == null)
{
player.ChatMessage(lang.GetMessage(MsgAdminNotFound, this, player.UserIDString));
return;
}
if (sub == "status")
{
var tracked = _stateByVictim.TryGetValue(target.userID, out var st);
var restrained = (target.IsRestrained || IsWearingHandcuffs(target));
var elapsed = tracked ? (int)Math.Floor(Interface.Oxide.Now - st.EpisodeStartUtc) : 0;
var debug = tracked && st.Debug;
player.ChatMessage(string.Format(lang.GetMessage(MsgAdminStatus, this, player.UserIDString),
target.displayName, restrained, tracked, elapsed, debug));
return;
}
if (sub == "reset")
{
DestroyPromptUi(target);
_stateByVictim.Remove(target.userID);
_immuneUntilUtc.Remove(target.userID);
player.ChatMessage(string.Format(lang.GetMessage(MsgAdminReset, this, player.UserIDString), target.displayName));
return;
}
player.ChatMessage(lang.GetMessage(MsgAdminUsage, this, player.UserIDString));
}
[ConsoleCommand("hcl.clearcache")]
private void CCmdClearCache(ConsoleSystem.Arg arg)
{
var player = arg?.Player();
if (player != null && !permission.UserHasPermission(player.UserIDString, PermAdmin))
{
arg.ReplyWith("No permission.");
return;
}
var which = "all";
if (arg?.Args != null && arg.Args.Length >= 1) which = arg.Args[0];
if (!TryClearCache(which, out var cleared))
{
arg.ReplyWith("Usage: hcl.clearcache <outpost|bandit|all>");
return;
}
arg.ReplyWith($"Cleared cached safe teleport spot for: {cleared}. It will be re-learned on the next rescue.");
}
[ConsoleCommand("hcl.choice")]
private void CmdChoice(ConsoleSystem.Arg arg)
{
var player = arg?.Player();
if (player == null) return;
if (arg.Args == null || arg.Args.Length < 1) return;
if (!_stateByVictim.TryGetValue(player.userID, out var st)) return;
var a = arg.Args[0].ToLowerInvariant();
if (a == "punish") st.Choice = 1;
else if (a == "forgive") st.Choice = 2;
DestroyPromptUi(player);
}
private bool TryClearCache(string which, out string clearedText)
{
clearedText = string.Empty;
if (_data == null) return false;
which = (which ?? string.Empty).Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(which)) which = "all";
var cleared = new List<string>(2);
if (which == "all")
{
ClearCacheForDestination((int)SafeDestination.Outpost, cleared);
ClearCacheForDestination((int)SafeDestination.BanditCamp, cleared);
}
else if (which == "outpost" || which == "1")
{
ClearCacheForDestination((int)SafeDestination.Outpost, cleared);
}
else if (which == "bandit" || which == "banditcamp" || which == "2")
{
ClearCacheForDestination((int)SafeDestination.BanditCamp, cleared);
}
else
{
return false;
}
clearedText = cleared.Count == 0 ? "none (no cached spot existed)" : string.Join(", ", cleared);
return true;
}
private void ClearCacheForDestination(int destination, List<string> clearedList)
{
if (_data.CachedSafeSpots != null && _data.CachedSafeSpots.TryGetValue(destination, out var cached))
{
AddToBlacklist(destination, cached.ToVector3());
_data.CachedSafeSpots.Remove(destination);
SaveData();
clearedList.Add(destination == (int)SafeDestination.Outpost ? "Outpost" : "Bandit");
}
else
{
}
}
private BasePlayer FindPlayer(string nameOrId)
{
if (string.IsNullOrEmpty(nameOrId)) return null;
if (ulong.TryParse(nameOrId, out var id))
{
var p = BasePlayer.FindByID(id);
if (p != null) return p;
return BasePlayer.FindSleeping(id);
}
var lower = nameOrId.ToLowerInvariant();
var list = BasePlayer.activePlayerList;
for (var i = 0; i < list.Count; i++)
{
var p = list[i];
if (p == null) continue;
if (p.displayName != null && p.displayName.ToLowerInvariant().Contains(lower))
return p;
}
return null;
}
private bool IsExemptCached(BasePlayer player, double now)
{
if (player == null) return false;
if (_config.ExemptPermissionCacheSeconds <= 0f)
return permission.UserHasPermission(player.UserIDString, PermExempt);
if (_exemptPermCache.TryGetValue(player.userID, out var entry) && entry.ExpiresUtc > now)
return entry.Value;
var value = permission.UserHasPermission(player.UserIDString, PermExempt);
_exemptPermCache[player.userID] = new PermCacheEntry
{
Value = value,
ExpiresUtc = now + _config.ExemptPermissionCacheSeconds
};
return value;
}
private void ShowWearList(BasePlayer admin, BasePlayer target)
{
if (admin == null || target == null) return;
admin.ChatMessage(string.Format(lang.GetMessage(MsgWearListHeader, this, admin.UserIDString), target.displayName));
try
{
var wear = target.inventory?.containerWear;
if (wear == null || wear.itemList == null || wear.itemList.Count == 0)
{
admin.ChatMessage("- (none)");
return;
}
var items = wear.itemList;
for (var i = 0; i < items.Count; i++)
{
var it = items[i];
if (it?.info == null) continue;
admin.ChatMessage(string.Format(lang.GetMessage(MsgWearListLine, this, admin.UserIDString), it.info.shortname, it.info.itemid));
}
}
catch
{
admin.ChatMessage("- (error reading wear container)");
}
}
#endregion
#region Debug
private void TryApplyDebugHandcuffs(BasePlayer player)
{
try
{
if (player == null) return;
if (IsWearingHandcuffs(player)) return;
var def = ItemManager.FindItemDefinition(HandcuffsShortname);
if (def == null)
{
PrintWarning("Debug: could not find ItemDefinition for handcuffs.");
return;
}
var item = ItemManager.Create(def, 1, 0UL);
if (item == null)
{
PrintWarning("Debug: could not create handcuffs item.");
return;
}
var wear = player.inventory?.containerWear;
if (wear != null && item.MoveToContainer(wear))
return;
item.Drop(player.transform.position + (Vector3.up * 0.25f), Vector3.zero);
PrintWarning("Debug: handcuffs could not be worn automatically on this build. Dropped handcuffs at your feet; cuff yourself normally to test.");
}
catch { }
}
private void StartDebugEpisode(BasePlayer player)
{
if (player == null) return;
TryApplyDebugHandcuffs(player);
try { player.SendNetworkUpdateImmediate(); } catch { }
var now = Interface.Oxide.Now;
if (!_stateByVictim.TryGetValue(player.userID, out var st))
{
st = new RestrainState { VictimId = player.userID };
_stateByVictim[player.userID] = st;
}
st.EpisodeStartUtc = now;
st.LastSeenUnrestrainedUtc = 0;
st.Warned = false;
st.IsCurrentlyRestrained = true;
st.PromptShown = false;
st.Choice = 0;
st.Debug = true;
st.DebugMaxSeconds = _config.DebugTestSeconds;
st.HoodRemoved = false;
_immuneUntilUtc.Remove(player.userID);
}
private void StopDebugEpisode(BasePlayer player)
{
if (player == null) return;
DestroyPromptUi(player);
_stateByVictim.Remove(player.userID);
TryUnrestrain(player);
}
#endregion
#region Core
private void StartPolling()
{
_pollTimer?.Destroy();
_pollTimer = timer.Every(_config.CheckIntervalSeconds, PollPlayers);
}
private void PollPlayers()
{
if (!_config.Enabled) return;
var now = Interface.Oxide.Now;
var normalMaxSeconds = _config.MaxRestrainMinutes * 60;
var players = BasePlayer.activePlayerList;
if (players == null || players.Count == 0) return;
for (var i = 0; i < players.Count; i++)
{
var p = players[i];
if (p == null || !p.IsConnected || p.IsDead()) continue;
var tracked = _stateByVictim.TryGetValue(p.userID, out var st);
var exempt = IsExemptCached(p, now);
if (exempt && !(tracked && st.Debug))
{
DestroyPromptUi(p);
_stateByVictim.Remove(p.userID);
continue;
}
var restrained = (p.IsRestrained || IsWearingHandcuffs(p));
if (restrained)
{
if (_immuneUntilUtc.TryGetValue(p.userID, out var immuneUntil) && immuneUntil > now)
{
TryUnrestrain(p);
continue;
}
if (!tracked)
{
st = new RestrainState
{
VictimId = p.userID,
EpisodeStartUtc = now,
LastSeenUnrestrainedUtc = 0,
Warned = false,
IsCurrentlyRestrained = true,
PromptShown = false,
Choice = 0,
Debug = false,
DebugMaxSeconds = 0,
HoodRemoved = false
};
_stateByVictim[p.userID] = st;
}
else
{
if (!st.IsCurrentlyRestrained && _config.EpisodeMergeWindowSeconds > 0)
{
var sinceUnrestrained = now - st.LastSeenUnrestrainedUtc;
if (sinceUnrestrained > _config.EpisodeMergeWindowSeconds)
{
st.EpisodeStartUtc = now;
st.Warned = false;
st.PromptShown = false;
st.Choice = 0;
st.HoodRemoved = false;
}
}
st.IsCurrentlyRestrained = true;
}
var maxSeconds = st.Debug && st.DebugMaxSeconds > 0 ? st.DebugMaxSeconds : normalMaxSeconds;
var elapsed = now - st.EpisodeStartUtc;
var remaining = maxSeconds - elapsed;
if (_config.WarnVictim && !st.Warned && _config.WarnSecondsBeforeLimit > 0 && remaining <= _config.WarnSecondsBeforeLimit && remaining > 0)
{
st.Warned = true;
p.ChatMessage(string.Format(lang.GetMessage(MsgVictimWarn, this, p.UserIDString), (int)Math.Ceiling(remaining)));
}
if (_config.RemoveHoodBeforePrompt && !st.HoodRemoved && _config.HoodRemoveSecondsBeforeLimit > 0 && remaining <= _config.HoodRemoveSecondsBeforeLimit && remaining > 0)
{
st.HoodRemoved = true;
TryRemovePrisonerHood(p);
}
if (_config.EnablePunishForgivePrompt && !st.PromptShown && _config.PromptSecondsBeforeLimit > 0 && remaining <= _config.PromptSecondsBeforeLimit && remaining > 0)
{
st.PromptShown = true;
ShowPromptUi(p);
}
if (elapsed >= maxSeconds)
{
EnforceLimit(p, st, (int)Math.Floor(elapsed));
}
}
else
{
if (tracked)
{
if (st.IsCurrentlyRestrained)
{
st.IsCurrentlyRestrained = false;
st.LastSeenUnrestrainedUtc = now;
}
else
{
if (_config.EpisodeMergeWindowSeconds <= 0 || (now - st.LastSeenUnrestrainedUtc) > _config.EpisodeMergeWindowSeconds)
{
DestroyPromptUi(p);
_stateByVictim.Remove(p.userID);
continue;
}
}
DestroyPromptUi(p);
if (st.Debug)
{
_stateByVictim.Remove(p.userID);
continue;
}
if (_config.EpisodeMergeWindowSeconds <= 0)
_stateByVictim.Remove(p.userID);
}
}
}
}
private void EnforceLimit(BasePlayer victim, RestrainState st, int durationSeconds)
{
if (victim == null || !victim.IsConnected) return;
_stateByVictim.Remove(victim.userID);
DestroyPromptUi(victim);
var originPos = victim.transform.position;
var originWasSafeZone = victim.InSafeZone();
TryUnrestrain(victim);
TeleportToDestination(victim, DestinationToInt());
NextTick(() => TryUnrestrain(victim));
victim.ChatMessage(lang.GetMessage(MsgVictimAction, this, victim.UserIDString));
if (_config.VictimRecuffImmunitySeconds > 0 && !(st != null && st.Debug))
_immuneUntilUtc[victim.userID] = Interface.Oxide.Now + _config.VictimRecuffImmunitySeconds;
var chaosDropped = false;
if (_config.ChaosEnabled)
{
var shouldChaos = !_config.EnablePunishForgivePrompt || (st != null && st.Choice == 1);
if (shouldChaos)
chaosDropped = TryChaosDrop(victim.userID, originPos, originWasSafeZone);
}
AddLogEntry(victim, durationSeconds, st != null ? st.Choice : 0, chaosDropped);
if (st != null && st.Debug)
return;
Puts($"Enforced restraint limit on {victim.displayName} ({victim.userID}). Destination={_config.TeleportDestination}.");
}
private void AddLogEntry(BasePlayer victim, int durationSeconds, int choice, bool chaosDropped)
{
if (_data == null) return;
_data.Log.Add(new LogEntry
{
Utc = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
VictimId = victim.userID,
VictimName = victim.displayName,
DurationSeconds = durationSeconds,
Destination = DestinationToInt(),
Choice = choice,
ChaosDropped = chaosDropped
});
while (_data.Log.Count > MaxLogEntries)
_data.Log.RemoveAt(0);
SaveData();
}
#endregion
private bool IsWearingHandcuffs(BasePlayer player)
{
try
{
var wear = player?.inventory?.containerWear;
if (wear == null) return false;