Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Поправка для спонсорки #303

Merged
merged 6 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions Content.Client/Lobby/LobbyUIController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
using Robust.Client.UserInterface.Controllers;
using Robust.Shared.Map;
using Robust.Shared.Prototypes;
using Robust.Shared.Player;
using Robust.Client.Player;
#if LPP_Sponsors
using Content.Client._LostParadise.Sponsors;
#endif

namespace Content.Client.Lobby;

Expand All @@ -28,6 +33,7 @@ public sealed partial class LobbyUIController : UIController, IOnStateEntered<Lo
[UISystemDependency] private readonly HumanoidAppearanceSystem _humanoid = default!;
[UISystemDependency] private readonly ClientInventorySystem _inventory = default!;
[UISystemDependency] private readonly LoadoutSystem _loadouts = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;

private LobbyCharacterPanel? _previewPanel;
private HumanoidProfileEditor? _profileEditor;
Expand Down Expand Up @@ -118,15 +124,25 @@ public void UpdateCharacterUI()
_previewPanel?.SetSummaryText(maybeProfile.Summary);
_humanoid.LoadProfile(_previewDummy.Value, maybeProfile);


#if LPP_Sponsors
var sys = IoCManager.Resolve<SponsorsManager>();
var sponsorTier = 0;
if (sys.TryGetInfo(out var sponsorInfo))
sponsorTier = sponsorInfo.Tier;
var uuid = _playerManager.LocalUser != null ? _playerManager.LocalUser.ToString() ?? "" : "";
#endif
if (UpdateClothes)
{
RemoveDummyClothes(_previewDummy.Value);
if (ShowClothes)
GiveDummyJobClothes(_previewDummy.Value, GetPreferredJob(maybeProfile), maybeProfile);
if (ShowLoadouts)
_loadouts.ApplyCharacterLoadout(_previewDummy.Value, GetPreferredJob(maybeProfile), maybeProfile,
_jobRequirements.GetRawPlayTimeTrackers(), _jobRequirements.IsWhitelisted());
_jobRequirements.GetRawPlayTimeTrackers(), _jobRequirements.IsWhitelisted()
#if LPP_Sponsors
, sponsorTier, uuid
#endif
);
Comment on lines +127 to +145
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Необходима защита от null при работе с UUID!

В строке 132 возможно возникновение NullReferenceException при вызове ToString(). Также рекомендуется выделить логику получения спонсорской информации в отдельный метод для улучшения читаемости кода.

Предлагаемые изменения:

-        var uuid = _playerManager.LocalUser != null ? _playerManager.LocalUser.ToString() ?? "" : "";
+        var uuid = _playerManager.LocalUser?.ToString() ?? "";

Рекомендуется выделить логику получения спонсорской информации в отдельный метод:

private (int tier, string uuid) GetSponsorInfo()
{
    var sponsorTier = 0;
    if (IoCManager.Resolve<SponsorsManager>().TryGetInfo(out var sponsorInfo))
        sponsorTier = sponsorInfo.Tier;
    var uuid = _playerManager.LocalUser?.ToString() ?? "";
    return (sponsorTier, uuid);
}

UpdateClothes = false;
}

Expand Down Expand Up @@ -171,9 +187,20 @@ public void RemoveDummyClothes(EntityUid dummy)
/// </summary>
public void GiveDummyJobClothesLoadout(EntityUid dummy, HumanoidCharacterProfile profile)
{
#if LPP_Sponsors
var sys = IoCManager.Resolve<SponsorsManager>();
var sponsorTier = 0;
if (sys.TryGetInfo(out var sponsorInfo))
sponsorTier = sponsorInfo.Tier;
var uuid = _playerManager.LocalUser != null ? _playerManager.LocalUser.ToString() ?? "" : "";
#endif
var job = GetPreferredJob(profile);
GiveDummyJobClothes(dummy, job, profile);
_loadouts.ApplyCharacterLoadout(dummy, job, profile, _jobRequirements.GetRawPlayTimeTrackers(), _jobRequirements.IsWhitelisted());
_loadouts.ApplyCharacterLoadout(dummy, job, profile, _jobRequirements.GetRawPlayTimeTrackers(), _jobRequirements.IsWhitelisted()
#if LPP_Sponsors
, sponsorTier, uuid
#endif
);
Comment on lines +190 to +203
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Устранить дублирование кода!

Код получения спонсорской информации дублируется в методах UpdateCharacterUI и GiveDummyJobClothesLoadout. Это нарушает принцип DRY и усложняет поддержку кода.

После создания предложенного метода GetSponsorInfo(), замените дублирующийся код:

-        var sys = IoCManager.Resolve<SponsorsManager>();
-        var sponsorTier = 0;
-        if (sys.TryGetInfo(out var sponsorInfo))
-            sponsorTier = sponsorInfo.Tier;
-        var uuid = _playerManager.LocalUser != null ? _playerManager.LocalUser.ToString() ?? "" : "";
+        var (sponsorTier, uuid) = GetSponsorInfo();

Committable suggestion was skipped due to low confidence.

}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions Content.Client/Preferences/ClientPreferencesManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ public void UpdateCharacter(ICharacterProfile profile, int slot)
if (sponsorMarkings is not null && sponsorMarkings.Count() > 0)
allowedMarkings = allowedMarkings.Concat(sponsorMarkings).ToArray();
}
var session = _playerManager.LocalSession!;
profile.EnsureValid(session, collection, allowedMarkings);
var session = _playerManager.LocalSession!;
profile.EnsureValid(session, collection, allowedMarkings);
#else
profile.EnsureValid(_playerManager.LocalSession!, collection);
#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1474,7 +1474,7 @@ private void UpdateTraits(bool showUnusable)
_configurationManager,
out _
#if LPP_Sponsors
, 0, sponsorTier, uuid
, 0, sponsorTier, uuid
#endif
);
_traits.Add(trait, usable);
Expand Down
18 changes: 16 additions & 2 deletions Content.Server/Clothing/Systems/LoadoutSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
using Content.Shared.Storage;
using Content.Shared.Storage.EntitySystems;
using Robust.Shared.Configuration;
#if LPP_Sponsors
using Content.Server._LostParadise.Sponsors;
#endif

namespace Content.Server.Clothing.Systems;

Expand All @@ -17,7 +20,9 @@ public sealed class LoadoutSystem : EntitySystem
[Dependency] private readonly InventorySystem _inventory = default!;
[Dependency] private readonly SharedStorageSystem _storage = default!;
[Dependency] private readonly PlayTimeTrackingManager _playTimeTracking = default!;

#if LPP_Sponsors
[Dependency] private readonly CheckSponsorSystem _checkSponsor = default!;
#endif

public override void Initialize()
{
Expand All @@ -27,13 +32,22 @@ public override void Initialize()

private void OnPlayerSpawnComplete(PlayerSpawnCompleteEvent ev)
{
#if LPP_Sponsors
var sponsorTier = _checkSponsor.CheckUser(ev.Player.UserId).Item2 ?? 0;
var uuid = ev.Player.UserId.ToString();
#endif
SpicyDarkFox marked this conversation as resolved.
Show resolved Hide resolved

if (ev.JobId == null ||
!_configurationManager.GetCVar(CCVars.GameLoadoutsEnabled))
return;

// Spawn the loadout, get a list of items that failed to equip
var failedLoadouts = _loadout.ApplyCharacterLoadout(ev.Mob, ev.JobId, ev.Profile,
_playTimeTracking.GetTrackerTimes(ev.Player), ev.Player.ContentData()?.Whitelisted ?? false);
_playTimeTracking.GetTrackerTimes(ev.Player), ev.Player.ContentData()?.Whitelisted ?? false
#if LPP_Sponsors
, sponsorTier, uuid
#endif
);

// Try to find back-mounted storage apparatus
if (!_inventory.TryGetSlotEntity(ev.Mob, "back", out var item) ||
Expand Down
17 changes: 16 additions & 1 deletion Content.Server/Traits/TraitSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
using Content.Shared.Psionics;
using Content.Server.Language;
using Content.Shared.Mood;
#if LPP_Sponsors
using Content.Server._LostParadise.Sponsors;
#endif
Comment on lines +17 to +19
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Проверьте необходимость явного указания default!

Зависимость CheckSponsorSystem объявлена как private readonly с явным указанием default!. В системе внедрения зависимостей Robust.Shared это излишне, так как система DI гарантирует инициализацию всех зависимостей.

-    [Dependency] private readonly CheckSponsorSystem _checkSponsor = default!;
+    [Dependency] private readonly CheckSponsorSystem _checkSponsor;

Also applies to: 34-36


namespace Content.Server.Traits;

Expand All @@ -28,6 +31,9 @@ public sealed class TraitSystem : EntitySystem
[Dependency] private readonly PsionicAbilitiesSystem _psionicAbilities = default!;
[Dependency] private readonly IComponentFactory _componentFactory = default!;
[Dependency] private readonly LanguageSystem _languageSystem = default!;
#if LPP_Sponsors
[Dependency] private readonly CheckSponsorSystem _checkSponsor = default!;
#endif

public override void Initialize()
{
Expand All @@ -39,6 +45,11 @@ public override void Initialize()
// When the player is spawned in, add all trait components selected during character creation
private void OnPlayerSpawnComplete(PlayerSpawnCompleteEvent args)
{

#if LPP_Sponsors
var sponsorTier = _checkSponsor.CheckUser(args.Player.UserId).Item2 ?? 0;
var uuid = args.Player.UserId.ToString();
#endif
foreach (var traitId in args.Profile.TraitPreferences)
{
if (!_prototype.TryIndex<TraitPrototype>(traitId, out var traitPrototype))
Expand All @@ -52,7 +63,11 @@ private void OnPlayerSpawnComplete(PlayerSpawnCompleteEvent args)
_prototype.Index<JobPrototype>(args.JobId ?? _prototype.EnumeratePrototypes<JobPrototype>().First().ID),
args.Profile, _playTimeTracking.GetTrackerTimes(args.Player), args.Player.ContentData()?.Whitelisted ?? false, traitPrototype,
EntityManager, _prototype, _configuration,
out _))
out _
#if LPP_Sponsors
, 0, sponsorTier, uuid
#endif
))
SpicyDarkFox marked this conversation as resolved.
Show resolved Hide resolved
continue;

AddTrait(args.Mob, traitPrototype);
Expand Down
24 changes: 20 additions & 4 deletions Content.Shared/Clothing/Loadouts/Systems/LoadoutSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,18 @@ private void OnMapInit(EntityUid uid, LoadoutComponent component, MapInitEvent a


public List<EntityUid> ApplyCharacterLoadout(EntityUid uid, ProtoId<JobPrototype> job, HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes, bool whitelisted)
Dictionary<string, TimeSpan> playTimes, bool whitelisted
#if LPP_Sponsors
, int sponsorTier = 0, string uuid = ""
#endif
)
{
var jobPrototype = _prototype.Index(job);
return ApplyCharacterLoadout(uid, jobPrototype, profile, playTimes, whitelisted);
return ApplyCharacterLoadout(uid, jobPrototype, profile, playTimes, whitelisted
#if LPP_Sponsors
, sponsorTier, uuid
#endif
);
}

/// <summary>
Expand All @@ -56,7 +64,11 @@ public List<EntityUid> ApplyCharacterLoadout(EntityUid uid, ProtoId<JobPrototype
/// <param name="whitelisted">If the player is whitelisted</param>
/// <returns>A list of loadout items that couldn't be equipped but passed checks</returns>
public List<EntityUid> ApplyCharacterLoadout(EntityUid uid, JobPrototype job, HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes, bool whitelisted)
Dictionary<string, TimeSpan> playTimes, bool whitelisted
#if LPP_Sponsors
, int sponsorTier = 0, string uuid = ""
#endif
)
{
var failedLoadouts = new List<EntityUid>();

Expand All @@ -72,7 +84,11 @@ public List<EntityUid> ApplyCharacterLoadout(EntityUid uid, JobPrototype job, Hu
if (!_characterRequirements.CheckRequirementsValid(
loadoutProto.Requirements, job, profile, playTimes, whitelisted, loadoutProto,
EntityManager, _prototype, _configuration,
out _))
out _
#if LPP_Sponsors
, 0, sponsorTier, uuid
#endif
))
SpicyDarkFox marked this conversation as resolved.
Show resolved Hide resolved
continue;


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,14 @@ public bool CheckRequirementValid(CharacterRequirement requirement, JobPrototype
)
{
var validation = false;
#if LPP_Sponsors
validation = requirement.IsValid(job, profile, playTimes, whitelisted, prototype,
entityManager, prototypeManager, configManager,
out reason, depth, sponsorTier, uuid);
#else

validation = requirement.IsValid(job, profile, playTimes, whitelisted, prototype,
entityManager, prototypeManager, configManager,
out reason, depth);
out reason, depth
#if LPP_Sponsors
, sponsorTier, uuid
#endif
);
SpicyDarkFox marked this conversation as resolved.
Show resolved Hide resolved

// Return false if the requirement is invalid and not inverted
// If it's inverted return false when it's valid
Expand All @@ -56,15 +55,15 @@ public bool CheckRequirementsValid(List<CharacterRequirement> requirements, JobP
{
var validation = false;
FormattedMessage? reason;
#if LPP_Sponsors
validation = requirement.IsValid(job, profile, playTimes, whitelisted, prototype,
entityManager, prototypeManager, configManager,
out reason, depth, sponsorTier, uuid);
#else

validation = requirement.IsValid(job, profile, playTimes, whitelisted, prototype,
entityManager, prototypeManager, configManager,
out reason, depth);
out reason, depth
#if LPP_Sponsors
, sponsorTier, uuid
#endif
);

Comment on lines +58 to +66
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Предлагаю убрать лишние пустые строки

Пустые строки до и после вызова requirement.IsValid не улучшают читаемость кода.

-            FormattedMessage? reason;
-
             validation = requirement.IsValid(job, profile, playTimes, whitelisted, prototype,
                 entityManager, prototypeManager, configManager,
                 out reason, depth
#if LPP_Sponsors
                 , sponsorTier, uuid
#endif
                 );
-
             // Set valid to false if the requirement is invalid and not inverted
+            FormattedMessage? reason;
+            validation = requirement.IsValid(job, profile, playTimes, whitelisted, prototype,
+                entityManager, prototypeManager, configManager,
+                out reason, depth
+#if LPP_Sponsors
+                , sponsorTier, uuid
+#endif
+                );
+            // Set valid to false if the requirement is invalid and not inverted

Committable suggestion was skipped due to low confidence.

// Set valid to false if the requirement is invalid and not inverted
// If it's inverted set valid to false when it's valid
if (!validation)
Expand Down
Loading