-
Notifications
You must be signed in to change notification settings - Fork 154
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
[Port] Universal Upgrader #950
base: master
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,21 @@ | ||||||||||||||||||||||
|
||||||||||||||||||||||
namespace Content.Server._Special.UniversalUpgrader.Components; | ||||||||||||||||||||||
|
||||||||||||||||||||||
[RegisterComponent] | ||||||||||||||||||||||
public sealed partial class UPComponent : Component | ||||||||||||||||||||||
{ | ||||||||||||||||||||||
[DataField, ViewVariables(VVAccess.ReadWrite)] | ||||||||||||||||||||||
public string upgradeName; | ||||||||||||||||||||||
|
||||||||||||||||||||||
[DataField, ViewVariables(VVAccess.ReadWrite)] | ||||||||||||||||||||||
public string componentName; | ||||||||||||||||||||||
|
||||||||||||||||||||||
[DataField, ViewVariables(VVAccess.ReadWrite)] | ||||||||||||||||||||||
public float upgradeValue; | ||||||||||||||||||||||
|
||||||||||||||||||||||
[DataField, ViewVariables(VVAccess.ReadWrite)] | ||||||||||||||||||||||
public string ProtoWhitelist; | ||||||||||||||||||||||
|
||||||||||||||||||||||
Comment on lines
+16
to
+18
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Исправьте именование и добавьте документацию для ProtoWhitelist Поле Предлагаемые изменения: - public string ProtoWhitelist;
+ /// <summary>
+ /// Список разрешенных прототипов для улучшения.
+ /// </summary>
+ [DataField]
+ [ViewVariables(VVAccess.ReadWrite)]
+ public string? protoWhitelist;
|
||||||||||||||||||||||
[DataField, ViewVariables(VVAccess.ReadWrite)] | ||||||||||||||||||||||
public int usable = 0; | ||||||||||||||||||||||
} | ||||||||||||||||||||||
Comment on lines
+19
to
+21
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Добавьте проверку значения usable Поле Рекомендуемые изменения: - public int usable = 0;
+ /// <summary>
+ /// Количество оставшихся использований улучшения.
+ /// </summary>
+ [DataField]
+ [ViewVariables(VVAccess.ReadWrite)]
+ public int usable = 1; 📝 Committable suggestion
Suggested change
|
Original file line number | Diff line number | Diff line change | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,48 @@ | ||||||||||||||||||
|
||||||||||||||||||
using Content.Server._Special.UniversalUpgrader.Components; | ||||||||||||||||||
using Content.Shared.Interaction; | ||||||||||||||||||
|
||||||||||||||||||
namespace Content.Server._Special.UniversalUpgrader.Systems; | ||||||||||||||||||
|
||||||||||||||||||
public sealed class UPSystem : EntitySystem | ||||||||||||||||||
{ | ||||||||||||||||||
|
||||||||||||||||||
[Dependency] private readonly EntityManager _ent = default!; | ||||||||||||||||||
public override void Initialize() | ||||||||||||||||||
{ | ||||||||||||||||||
base.Initialize(); | ||||||||||||||||||
SubscribeLocalEvent<UPComponent, AfterInteractEvent>(OnInteract); | ||||||||||||||||||
} | ||||||||||||||||||
|
||||||||||||||||||
private void OnInteract(Entity<UPComponent> entity, ref AfterInteractEvent args) | ||||||||||||||||||
{ | ||||||||||||||||||
if (!args.CanReach || args.Target is not { Valid: true } target) | ||||||||||||||||||
return; | ||||||||||||||||||
if (entity.Comp.ProtoWhitelist != null && HasComp<MetaDataComponent>(target)) | ||||||||||||||||||
{ | ||||||||||||||||||
var z = _ent.GetComponent<MetaDataComponent>(target); | ||||||||||||||||||
if (z.EntityPrototype!.ID != entity.Comp.ProtoWhitelist) | ||||||||||||||||||
return; | ||||||||||||||||||
} | ||||||||||||||||||
|
||||||||||||||||||
Type? g = Type.GetType(entity.Comp.componentName); | ||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WTF? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
GetType переводит строку в объект с которым можно работать, пример из видео:
|
||||||||||||||||||
|
||||||||||||||||||
if (g != null && _ent.TryGetComponent(target, g, out var comp)) | ||||||||||||||||||
{ | ||||||||||||||||||
|
||||||||||||||||||
var h = comp.GetType().GetField(entity.Comp.upgradeName); | ||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WTF? |
||||||||||||||||||
|
||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Небезопасное использование рефлексии Прямое использование Type.GetType и GetField без валидации может привести к уязвимостям безопасности. Необходимо:
Пример безопасной реализации: - Type? g = Type.GetType(entity.Comp.componentName);
+ if (!ValidateComponentName(entity.Comp.componentName))
+ return;
+ Type? g = Type.GetType($"Content.Server.{entity.Comp.componentName}");
|
||||||||||||||||||
if (h != null) | ||||||||||||||||||
{ | ||||||||||||||||||
|
||||||||||||||||||
if (h.FieldType == typeof(int)) h.SetValue(comp,(int) entity.Comp.upgradeValue); | ||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WTF? |
||||||||||||||||||
if (h.FieldType == typeof(float)) h.SetValue(comp,(int) entity.Comp.upgradeValue); | ||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Небезопасное приведение типов Текущая реализация может привести к потере данных при конвертации:
Предлагаемое исправление: - if (h.FieldType == typeof(int)) h.SetValue(comp,(int) entity.Comp.upgradeValue);
- if (h.FieldType == typeof(float)) h.SetValue(comp,(int) entity.Comp.upgradeValue);
+ if (h.FieldType == typeof(int))
+ h.SetValue(comp, Convert.ToInt32(entity.Comp.upgradeValue));
+ else if (h.FieldType == typeof(float))
+ h.SetValue(comp, Convert.ToSingle(entity.Comp.upgradeValue));
+ else
+ Logger.Warning($"Unsupported field type {h.FieldType}"); 📝 Committable suggestion
Suggested change
|
||||||||||||||||||
|
||||||||||||||||||
} | ||||||||||||||||||
entity.Comp.usable -= 1; | ||||||||||||||||||
if (entity.Comp.usable < 0) _ent.QueueDeleteEntity(entity); | ||||||||||||||||||
|
||||||||||||||||||
} | ||||||||||||||||||
} | ||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Оптимизация производительности и обработка ошибок Текущая реализация использует рефлексию при каждом взаимодействии, что может негативно влиять на производительность. Также отсутствует обработка исключений. Рекомендации:
Пример реализации: + private readonly Dictionary<string, (Type type, FieldInfo field)> _componentCache = new();
+ private bool TryGetComponentInfo(string componentName, string fieldName,
+ out (Type type, FieldInfo field) info)
+ {
+ var key = $"{componentName}.{fieldName}";
+ if (_componentCache.TryGetValue(key, out info))
+ return true;
+
+ try
+ {
+ // ... кэширование информации о компоненте
+ return true;
+ }
+ catch (Exception e)
+ {
+ Logger.Error($"Failed to get component info: {e}");
+ info = default;
+ return false;
+ }
+ }
|
||||||||||||||||||
|
||||||||||||||||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Требуется валидация полей и улучшение типобезопасности
Поля
upgradeName
,componentName
иupgradeValue
не имеют проверок на null и отрицательные значения.Рекомендуемые изменения:
📝 Committable suggestion