1
0

AdminLogManager.Json.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Linq;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. using Content.Server.Administration.Logs.Converters;
  5. using Robust.Server.GameObjects;
  6. using Robust.Shared.Map;
  7. using Robust.Shared.Player;
  8. namespace Content.Server.Administration.Logs;
  9. public sealed partial class AdminLogManager
  10. {
  11. private static readonly JsonNamingPolicy NamingPolicy = JsonNamingPolicy.CamelCase;
  12. // Init only
  13. private JsonSerializerOptions _jsonOptions = default!;
  14. private void InitializeJson()
  15. {
  16. _jsonOptions = new JsonSerializerOptions
  17. {
  18. PropertyNamingPolicy = NamingPolicy
  19. };
  20. foreach (var converter in _reflection.FindTypesWithAttribute<AdminLogConverterAttribute>())
  21. {
  22. var instance = _typeFactory.CreateInstance<JsonConverter>(converter);
  23. (instance as IAdminLogConverter)?.Init(_dependencies);
  24. _jsonOptions.Converters.Add(instance);
  25. }
  26. var converterNames = _jsonOptions.Converters.Select(converter => converter.GetType().Name);
  27. _sawmill.Debug($"Admin log converters found: {string.Join(" ", converterNames)}");
  28. }
  29. private (JsonDocument Json, HashSet<Guid> Players) ToJson(
  30. Dictionary<string, object?> properties)
  31. {
  32. var players = new HashSet<Guid>();
  33. var parsed = new Dictionary<string, object?>();
  34. foreach (var key in properties.Keys)
  35. {
  36. var value = properties[key];
  37. value = value switch
  38. {
  39. ICommonSession player => new SerializablePlayer(player),
  40. EntityCoordinates entityCoordinates => new SerializableEntityCoordinates(_entityManager, entityCoordinates),
  41. _ => value
  42. };
  43. var parsedKey = NamingPolicy.ConvertName(key);
  44. parsed.Add(parsedKey, value);
  45. var entityId = properties[key] switch
  46. {
  47. EntityUid id => id,
  48. EntityStringRepresentation rep => rep.Uid,
  49. ICommonSession {AttachedEntity: {Valid: true}} session => session.AttachedEntity,
  50. IComponent component => component.Owner,
  51. _ => null
  52. };
  53. if (_entityManager.TryGetComponent(entityId, out ActorComponent? actor))
  54. {
  55. players.Add(actor.PlayerSession.UserId.UserId);
  56. }
  57. else if (value is SerializablePlayer player)
  58. {
  59. players.Add(player.Player.UserId.UserId);
  60. }
  61. }
  62. return (JsonSerializer.SerializeToDocument(parsed, _jsonOptions), players);
  63. }
  64. }