-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRecycle.cs
More file actions
637 lines (513 loc) · 23.4 KB
/
Recycle.cs
File metadata and controls
637 lines (513 loc) · 23.4 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
using Oxide.Core.Libraries.Covalence;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using Oxide.Core;
using System;
using Facepunch;
namespace Oxide.Plugins
{
[Info("Recycle", "nivex", "3.2.0")]
[Description("Recycle items into their resources")]
public class Recycle : RustPlugin
{
private const string
RecyclePrefab = "assets/bundled/prefabs/static/recycler_static.prefab",
BackpackPrefab = "assets/prefabs/misc/item drop/item_drop_backpack.prefab",
AdminPermission = "recycle.admin",
RecyclerPermission = "recycle.use",
CooldownBypassPermission = "recycle.bypass";
private readonly Dictionary<ulong, DroppedInfo> _droppedContainers = new();
private readonly Dictionary<ulong, RecyclerInfo> _recyclers = new();
private readonly Dictionary<string, long> _cooldowns = new();
private ConfigData config;
public class DroppedInfo
{
public DroppedItemContainer container;
public BasePlayer target;
public DroppedInfo(DroppedItemContainer container, BasePlayer target)
{
this.container = container;
this.target = target;
}
}
public class RecyclerInfo
{
public Recycler recycler;
public BasePlayer player;
public ItemContainerId id;
public RecyclerInfo(Recycler recycler, BasePlayer player)
{
this.recycler = recycler;
this.player = player;
id = recycler.inventory.uid;
}
}
#region Hooks
private void Loaded()
{
string recycleCommand = string.IsNullOrEmpty(config.Settings.RecycleCommand) ? "recycle" : config.Settings.RecycleCommand;
AddCovalenceCommand(recycleCommand, "RecycleCommand");
AddCovalenceCommand("purgerecyclers", "PurgeRecyclersCommand");
AddCovalenceCommand("purgebags", "PurgeBagsCommand");
permission.RegisterPermission(AdminPermission, this);
permission.RegisterPermission(RecyclerPermission, this);
permission.RegisterPermission(CooldownBypassPermission, this);
if (!config.Settings.ToInventory) Unsubscribe(nameof(CanMoveItem));
}
private void Unload()
{
DestroyRecyclers();
DestroyBags();
}
private void OnLootEntityEnd(BasePlayer player, Recycler recycler)
{
if (player != null) DestroyRecycler(player);
}
private void OnPlayerDisconnected(BasePlayer player, string reason)
{
if (player == null) return;
DestroyRecycler(player);
if (_droppedContainers.Count == 0) return;
using var tmp = Pool.Get<PooledList<KeyValuePair<ulong, DroppedInfo>>>();
tmp.AddRange(_droppedContainers);
foreach (var (uid, val) in tmp)
{
if (!IsValid(val.container) || !IsValid(val.target) || val.target.userID == player.userID)
{
if (IsValid(val.container))
val.container.Kill();
_droppedContainers.Remove(uid);
}
}
}
private object CanMoveItem(Item item, PlayerInventory inv, ItemContainerId targetContainerId, int targetSlot, int amount)
{
if (targetSlot < 6) return null;
foreach (ItemContainer container in inv.loot.containers)
{
if (container.uid != targetContainerId || container.entityOwner == null) continue;
if (container.entityOwner is Recycler recycler && IsRecycleBox(recycler)) return false;
}
return null;
}
private float lastMessageTime;
private object CanAcceptItem(ItemContainer container, Item item, int targetPos)
{
if (container == null || !(container.entityOwner is Recycler recycler)) return null;
if (!IsRecycleBox(recycler)) return null;
BasePlayer player = PlayerFromRecycler(recycler.net.ID.Value);
if (player == null) return null;
string type = Enum.GetName(typeof(ItemCategory), item.info.category);
if (targetPos < 6)
{
if (!config.Settings.RecyclableTypes.Contains(type) || config.Settings.Blacklist.Contains(item.info.shortname))
{
if (lastMessageTime < Time.time)
{
lastMessageTime = Time.time + 0.1f;
Message(player, "Recycle", "Invalid");
}
return ItemContainer.CanAcceptResult.CannotAcceptRightNow;
}
recycler.Invoke(() =>
{
if (recycler.IsOn()) return;
if (!recycler.HasRecyclable()) return;
float time = config.Settings.InstantRecycling ? 0.0625f : recycler.GetRecycleThinkDuration();
recycler.InvokeRepeating(recycler.RecycleThink, time, time);
recycler.SetFlag(BaseEntity.Flags.On, b: true);
recycler.SendNetworkUpdateImmediate();
}, 0.0625f);
}
else if (config.Settings.ToInventory && item.GetOwnerPlayer() == null)
{
Item copy = ItemManager.Create(item.info, item.amount, item.skin);
if (player.inventory.GiveItem(copy)) item.Remove();
}
return null;
}
private object CanLootEntity(BasePlayer player, DroppedItemContainer container)
{
if (container.IsValid() && _droppedContainers.TryGetValue(container.net.ID.Value, out var t) && t.target.userID != player.userID) return true;
return null;
}
private void OnEntityKill(DroppedItemContainer container)
{
if (container.IsValid()) _droppedContainers.Remove(container.net.ID.Value);
}
private void OnUseNPC(BasePlayer npc, BasePlayer player) // HumanNPC plugin support
{
if (npc == null || !config.Settings.NPCIds.Contains(npc.UserIDString)) return;
OpenRecycler(player);
}
#endregion
#region Commands
private void RecycleCommand(IPlayer user, string command, string[] args)
{
if (CanManageRecyclers(user) && args.Contains("reloadconfig"))
{
LoadConfig();
Message(user, "Recycle", "Reloaded");
}
if (config.Settings.NPCOnly)
return;
BasePlayer player = user.Object as BasePlayer;
if (player == null || !CanPlayerOpenRecycler(player))
return;
OpenRecycler(player);
if (config.Settings.Cooldown > 0 && !CanBypassCooldown(user))
_cooldowns[player.UserIDString] = DateTimeOffset.Now.ToUnixTimeSeconds() + (long)(config.Settings.Cooldown * 60);
}
private void PurgeRecyclersCommand(IPlayer user, string command, string[] args)
{
if (CanManageRecyclers(user))
{
DestroyRecyclers();
Message(user, "Recycle", "DestroyedAll");
}
else Message(user, "Denied", "Permission");
}
private void PurgeBagsCommand(IPlayer user, string command, string[] args)
{
if (CanManageRecyclers(user))
{
DestroyBags();
Message(user, "Recycle", "DestroyedAllBags");
}
else Message(user, "Denied", "Permission");
}
private void Message(IPlayer user, string top, string bottom)
{
if (user.Object is BasePlayer player)
{
Message(player, top, bottom);
return;
}
string message = GetMessage(top, bottom, user.Id);
if (string.IsNullOrEmpty(message))
{
return; // set a message value to empty to disable that message
}
if (user.IsServer)
{
Puts(message);
}
else
{
user.Message(message);
}
}
private void Message(BasePlayer player, string top, string bottom, params object[] args)
{
if (player == null) return;
string message = GetMessage(top, bottom, player.UserIDString);
if (string.IsNullOrEmpty(message)) return;
PrintToChat(player, args.Length > 0 ? string.Format(message, args) : message);
}
public bool IsValid(BaseNetworkable e) => e.IsValid() && !e.IsDestroyed;
#endregion
#region Helpers
private Recycler CreateRecycler(BasePlayer player)
{
var recycler = GameManager.server.CreateEntity(RecyclePrefab, player.transform.position.WithY(-5f)) as Recycler;
if (recycler == null) return null;
recycler.enableSaving = false;
recycler.Spawn();
if (!IsValid(recycler)) return null;
recycler.radtownRecycleEfficiency = config.Settings.RefundRatio;
recycler.safezoneRecycleEfficiency = config.Settings.RefundRatio;
recycler.SetFlag(BaseEntity.Flags.Locked, true);
recycler.UpdateNetworkGroup();
recycler.gameObject.layer = 0;
recycler.SendNetworkUpdateImmediate(true);
OpenContainer(player, recycler);
_recyclers.Add(recycler.net.ID.Value, new(recycler, player));
return recycler;
}
private void OpenContainer(BasePlayer player, StorageContainer container)
{
player.Invoke(() =>
{
if (container == null || container.IsDestroyed || player.IsDestroyed) return;
player.EndLooting();
if (!player.inventory.loot.StartLootingEntity(container, false)) return;
player.inventory.loot.AddContainer(container.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPC(RpcTarget.Player("RPC_OpenLootPanel", player), container.panelName);
player.SendNetworkUpdate();
}, 0.2f);
}
private void DropRecyclerContents(Recycler recycler, BasePlayer player)
{
if (player == null || player.inventory == null || player.inventory.containerMain == null || player.inventory.containerBelt == null) return;
if (recycler == null || recycler.inventory == null || recycler.inventory.itemList.IsNullOrEmpty()) return;
using var items = Pool.Get<PooledList<Item>>();
items.AddRange(recycler.inventory.itemList);
if (config.Settings.InventoryBeforeBag)
{
for (int i = 0; i < items.Count; i++)
{
Item item = items[i];
if (player.inventory.GiveItem(item))
{
items.RemoveAt(i);
i--;
}
}
}
if (items.Count == 0)
{
return;
}
Message(player, "Recycle", "Dropped");
var container = GameManager.server.CreateEntity(BackpackPrefab, player.transform.position + Vector3.up) as DroppedItemContainer;
if (container == null) return;
container.enableSaving = false;
container.lootPanelName = "generic_resizable";
container.playerSteamID = player.userID;
container.TakeFrom(new[] { recycler.inventory }, 0f);
container.Spawn();
if (IsValid(container))
{
_droppedContainers[container.net.ID.Value] = new(container, player);
}
}
private void DestroyRecycler(BasePlayer player)
{
Recycler recycler = RecyclerFromPlayer(player.userID);
if (IsValid(recycler) && _recyclers.TryGetValue(recycler.net.ID.Value, out var t))
{
DropRecyclerContents(recycler, t.player);
_recyclers.Remove(recycler.net.ID.Value);
recycler.Kill();
}
}
private void DestroyRecyclers()
{
if (_recyclers.Count == 0) return;
using var tmp = Pool.Get<PooledList<RecyclerInfo>>();
tmp.AddRange(_recyclers.Values);
foreach (var val in tmp)
{
if (IsValid(val.recycler))
{
DropRecyclerContents(val.recycler, val.player);
val.recycler.Kill();
}
}
_recyclers.Clear();
}
private void DestroyBags()
{
if (_droppedContainers.Count == 0) return;
using var tmp = Pool.Get<PooledList<DroppedInfo>>();
tmp.AddRange(_droppedContainers.Values);
foreach (var val in tmp)
{
if (IsValid(val.container))
{
val.container.Kill();
}
}
_droppedContainers.Clear();
}
private string GetMessage(string top, string bottom, string userid)
{
return lang.GetMessage(top + " -> " + bottom, this, userid);
}
private int[] GetCooldown(string userid)
{
if (!_cooldowns.TryGetValue(userid, out var time)) return Array.Empty<int>();
long now = DateTimeOffset.Now.ToUnixTimeSeconds();
if (now > time) return Array.Empty<int>();
TimeSpan diff = TimeSpan.FromSeconds(time - DateTimeOffset.Now.ToUnixTimeSeconds());
return new int[] { diff.Minutes, diff.Seconds };
}
private string CooldownTimesToString(int[] times, BasePlayer player)
{
if (times == null || times.Length != 2) return string.Empty;
int mins = times[0], secs = times[1];
return (string.Format(
mins == 0 ? string.Empty : ("{0} " + GetMessage("Timings", mins == 1 ? "minute" : "minutes", player.UserIDString)), mins) +
string.Format(" {0} " + GetMessage("Timings", secs == 1 ? "second" : "seconds", player.UserIDString), secs)
).Trim();
}
#endregion
#region API
private BasePlayer PlayerFromRecycler(ulong netID) => _recyclers.TryGetValue(netID, out var t) ? t.player : null;
private Recycler RecyclerFromPlayer(ulong userid)
{
foreach (var val in _recyclers.Values)
if (val.player?.userID == userid)
return val.recycler;
return null;
}
private bool IsOnCooldown(IPlayer user) => config.Settings.Cooldown > 0 && !CanBypassCooldown(user) && _cooldowns.ContainsKey(user.Id) && DateTimeOffset.Now.ToUnixTimeSeconds() < _cooldowns[user.Id];
private bool CanUseRecycler(IPlayer user) => user.HasPermission(RecyclerPermission);
private bool CanManageRecyclers(IPlayer user) => user.HasPermission(AdminPermission);
private bool CanBypassCooldown(IPlayer user) => user.HasPermission(CooldownBypassPermission);
private bool IsRecycleBox(BaseNetworkable e) => IsValid(e) && _recyclers.ContainsKey(e.net.ID.Value);
private bool CanPlayerOpenRecycler(BasePlayer player)
{
if (player == null || !(player.IPlayer is IPlayer user) || !player.IsAlive())
Message(player, "Denied", "Hook Denied");
else if (!CanUseRecycler(user) && !CanManageRecyclers(user))
Message(player, "Denied", "Permission");
else if (IsOnCooldown(user))
Message(player, "Cooldown", "In", CooldownTimesToString(GetCooldown(player.UserIDString), player));
else if (player.IsWounded())
Message(player, "Denied", "Wounded");
else if (!player.CanBuild())
Message(player, "Denied", "Privilege");
else if (config.Settings.RadiationMax > 0 && player.radiationLevel > config.Settings.RadiationMax)
Message(player, "Denied", "Irradiation");
else if (player.IsSwimming())
Message(player, "Denied", "Swimming");
else if (!player.IsOnGround() || player.IsFlying || player.isInAir)
Message(player, "Denied", "Falling");
else if (player.isMounted || player.GetParentEntity() is BaseMountable)
Message(player, "Denied", "Mounted");
else if (player.GetComponentInParent<CargoShip>())
Message(player, "Denied", "Ship");
else if (player.GetComponentInParent<HotAirBalloon>())
Message(player, "Denied", "Balloon");
else if (player.GetComponentInParent<Lift>())
Message(player, "Denied", "Elevator");
else if (!config.Settings.AllowedInSafeZones && player.InSafeZone())
Message(player, "Denied", "Safe Zone");
else if (Interface.Call("CanOpenRecycler", player) is object obj && obj != null && (obj is not bool val || !val))
Message(player, "Denied", obj is string str && str.Length > 0 ? str : "Hook Denied");
else
return true;
return false;
}
private void OpenRecycler(BasePlayer player)
{
if (player == null)
return;
DestroyRecycler(player);
CreateRecycler(player);
}
private void AddNpc(string id)
{
if (config.Settings.NPCIds.Contains(id))
return;
config.Settings.NPCIds.Add(id);
SaveConfig();
}
private void RemoveNpc(string id)
{
if (config.Settings.NPCIds.Remove(id))
SaveConfig();
}
#endregion
#region Structs
public class ConfigData
{
public class SettingsWrapper
{
[JsonProperty("Command To Open Recycler")]
public string RecycleCommand = "recycle";
[JsonProperty("Cooldown (in minutes)")]
public float Cooldown = 5.0f;
[JsonProperty("Maximum Radiation")]
public float RadiationMax = 1f;
[JsonProperty("Refund Ratio")]
public float RefundRatio = 0.5f;
[JsonProperty("NPCs Only")]
public bool NPCOnly;
[JsonProperty("Allowed In Safe Zones")]
public bool AllowedInSafeZones = true;
[JsonProperty("Instant Recycling")]
public bool InstantRecycling = false;
[JsonProperty("Send Recycled Items To Inventory")]
public bool ToInventory = true;
[JsonProperty("Send Items To Inventory Before Bag")]
public bool InventoryBeforeBag = true;
[JsonProperty("NPC Ids", ObjectCreationHandling = ObjectCreationHandling.Replace)]
public List<object> NPCIds = new();
[JsonProperty("Recyclable Types", ObjectCreationHandling = ObjectCreationHandling.Replace)]
public List<object> RecyclableTypes = new();
[JsonProperty("Blacklisted Items", ObjectCreationHandling = ObjectCreationHandling.Replace)]
public List<object> Blacklist = new();
}
public SettingsWrapper Settings = new();
public string VERSION = "3.2.0";
}
#endregion
#region Configuration
protected override void LoadDefaultMessages()
{
Func<string, string> youCannot = (thing) => "You cannot recycle while " + thing;
lang.RegisterMessages(new Dictionary<string, string>
{
{ "Recycle -> Reloaded", "Configuration file has been reloaded" },
{ "Recycle -> DestroyedAllBags", "All bags have been destroyed" },
{ "Recycle -> DestroyedAll", "All recyclers have been destroyed" },
{ "Recycle -> Dropped", "You left some items in the recycler!" },
{ "Recycle -> Invalid", "You cannot recycle that!" },
{ "Denied -> Npc Only", "You must use the recycler at specific npcs only" },
{ "Denied -> Permission", "You don't have permission to use that command" },
{ "Denied -> Privilege", "You cannot recycle within someone's building privilege" },
{ "Denied -> Swimming", youCannot("swimming") },
{ "Denied -> Falling", youCannot("falling") },
{ "Denied -> Mounted", youCannot("mounted") },
{ "Denied -> Wounded", youCannot("wounded") },
{ "Denied -> Irradiation", youCannot("irradiated") },
{ "Denied -> Ship", youCannot("on a ship") },
{ "Denied -> Elevator", youCannot("on an elevator") },
{ "Denied -> Balloon", youCannot("on a balloon") },
{ "Denied -> Safe Zone", youCannot("in a safe zone") },
{ "Denied -> Hook Denied", "You can't recycle right now" },
{ "Cooldown -> In", "You need to wait {0} before recycling" },
{ "Timings -> second", "second" },
{ "Timings -> seconds", "seconds" },
{ "Timings -> minute", "minute" },
{ "Timings -> minutes", "minutes" }
}, this);
}
protected override void LoadDefaultConfig()
{
config = new()
{
Settings =
{
RecyclableTypes = new()
{
"Ammunition", "Attire", "Component", "Construction", "Electrical", "Fun", "Items", "Medical", "Misc", "Resources", "Tool", "Traps", "Weapon"
}
}
};
}
protected override void LoadConfig()
{
base.LoadConfig();
canSaveConfig = false;
try
{
config = Config.ReadObject<ConfigData>();
config ??= new();
config.Settings ??= new();
config.Settings.NPCIds ??= new();
canSaveConfig = true;
SaveConfig();
}
catch (Exception ex)
{
Puts(ex.ToString());
LoadDefaultConfig();
}
}
private bool canSaveConfig = true;
protected override void SaveConfig()
{
if (canSaveConfig)
{
config.VERSION = Version.ToString();
Config.WriteObject(config, true);
}
}
#endregion
}
}