JobWhitelistSystem.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections.Immutable;
  2. using Content.Server.GameTicking.Events;
  3. using Content.Server.Station.Events;
  4. using Content.Shared.CCVar;
  5. using Content.Shared.Roles;
  6. using Robust.Server.Player;
  7. using Robust.Shared.Configuration;
  8. using Robust.Shared.Prototypes;
  9. using Robust.Shared.Utility;
  10. namespace Content.Server.Players.JobWhitelist;
  11. public sealed class JobWhitelistSystem : EntitySystem
  12. {
  13. [Dependency] private readonly IConfigurationManager _config = default!;
  14. [Dependency] private readonly JobWhitelistManager _manager = default!;
  15. [Dependency] private readonly IPlayerManager _player = default!;
  16. [Dependency] private readonly IPrototypeManager _prototypes = default!;
  17. private ImmutableArray<ProtoId<JobPrototype>> _whitelistedJobs = [];
  18. public override void Initialize()
  19. {
  20. SubscribeLocalEvent<PrototypesReloadedEventArgs>(OnPrototypesReloaded);
  21. SubscribeLocalEvent<StationJobsGetCandidatesEvent>(OnStationJobsGetCandidates);
  22. SubscribeLocalEvent<IsJobAllowedEvent>(OnIsJobAllowed);
  23. SubscribeLocalEvent<GetDisallowedJobsEvent>(OnGetDisallowedJobs);
  24. CacheJobs();
  25. }
  26. private void OnPrototypesReloaded(PrototypesReloadedEventArgs ev)
  27. {
  28. if (ev.WasModified<JobPrototype>())
  29. CacheJobs();
  30. }
  31. private void OnStationJobsGetCandidates(ref StationJobsGetCandidatesEvent ev)
  32. {
  33. if (!_config.GetCVar(CCVars.GameRoleWhitelist))
  34. return;
  35. for (var i = ev.Jobs.Count - 1; i >= 0; i--)
  36. {
  37. var jobId = ev.Jobs[i];
  38. if (_player.TryGetSessionById(ev.Player, out var player) &&
  39. !_manager.IsAllowed(player, jobId))
  40. {
  41. ev.Jobs.RemoveSwap(i);
  42. }
  43. }
  44. }
  45. private void OnIsJobAllowed(ref IsJobAllowedEvent ev)
  46. {
  47. if (!_manager.IsAllowed(ev.Player, ev.JobId))
  48. ev.Cancelled = true;
  49. }
  50. private void OnGetDisallowedJobs(ref GetDisallowedJobsEvent ev)
  51. {
  52. if (!_config.GetCVar(CCVars.GameRoleWhitelist))
  53. return;
  54. foreach (var job in _whitelistedJobs)
  55. {
  56. if (!_manager.IsAllowed(ev.Player, job))
  57. ev.Jobs.Add(job);
  58. }
  59. }
  60. private void CacheJobs()
  61. {
  62. var builder = ImmutableArray.CreateBuilder<ProtoId<JobPrototype>>();
  63. foreach (var job in _prototypes.EnumeratePrototypes<JobPrototype>())
  64. {
  65. if (job.Whitelisted)
  66. builder.Add(job.ID);
  67. }
  68. _whitelistedJobs = builder.ToImmutable();
  69. }
  70. }