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

Fixing CustomModules #2753

Merged
merged 5 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
52 changes: 45 additions & 7 deletions Exiled.CustomModules/API/Features/CustomModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ namespace Exiled.CustomModules.API.Features
using Exiled.API.Features.Attributes;
using Exiled.API.Features.Core;
using Exiled.API.Features.DynamicEvents;
using Exiled.API.Features.Serialization;
using Exiled.API.Features.Serialization.CustomConverters;
using Exiled.API.Interfaces;
using Exiled.CustomModules.API.Enums;
using Exiled.CustomModules.API.Features.Attributes;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NodeDeserializers;

/// <summary>
/// Represents a marker class for custom modules.
Expand Down Expand Up @@ -209,6 +212,41 @@ internal string PointerPath
}
}

/// <summary>
/// Gets or sets the serializer for custom modules.
/// </summary>
private static ISerializer ModuleSerializer { get; set; } = new SerializerBuilder()
.WithTypeConverter(new VectorsConverter())
.WithTypeConverter(new ColorConverter())
.WithTypeConverter(new AttachmentIdentifiersConverter())
.WithTypeConverter(new EnumClassConverter())
.WithTypeConverter(new PrivateConstructorConverter())
.WithTypeConverter(new CustomModuleSerializer())
.WithEventEmitter(eventEmitter => new TypeAssigningEventEmitter(eventEmitter))
.WithTypeInspector(inner => new CommentGatheringTypeInspector(inner))
.WithEmissionPhaseObjectGraphVisitor(args => new CommentsObjectGraphVisitor(args.InnerVisitor))
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.IgnoreFields()
.DisableAliases()
.Build();

/// <summary>
/// Gets or sets the deserializer for custom modules.
/// </summary>
private static IDeserializer ModuleDeserializer { get; set; } = new DeserializerBuilder()
.WithTypeConverter(new VectorsConverter())
.WithTypeConverter(new ColorConverter())
.WithTypeConverter(new AttachmentIdentifiersConverter())
.WithTypeConverter(new EnumClassConverter())
.WithTypeConverter(new PrivateConstructorConverter())
.WithTypeConverter(new CustomModuleSerializer())
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.WithNodeDeserializer(inner => new ValidatingNodeDeserializer(inner), deserializer => deserializer.InsteadOf<ObjectNodeDeserializer>())
.WithDuplicateKeyChecking()
.IgnoreFields()
.IgnoreUnmatchedProperties()
.Build();

/// <summary>
/// Compares two operands: <see cref="CustomModule"/> and <see cref="object"/>.
/// </summary>
Expand Down Expand Up @@ -424,13 +462,13 @@ public void SerializeModule()

if (File.Exists(FilePath) && File.Exists(PointerPath))
{
File.WriteAllText(FilePath, EConfig.Serializer.Serialize(this));
File.WriteAllText(PointerPath, EConfig.Serializer.Serialize(Config));
File.WriteAllText(FilePath, ModuleSerializer.Serialize(this));
File.WriteAllText(PointerPath, ModuleSerializer.Serialize(Config));
return;
}

File.WriteAllText(FilePath ?? throw new ArgumentNullException(nameof(FilePath)), EConfig.Serializer.Serialize(this));
File.WriteAllText(PointerPath ?? throw new ArgumentNullException(nameof(PointerPath)), EConfig.Serializer.Serialize(Config));
File.WriteAllText(FilePath ?? throw new ArgumentNullException(nameof(FilePath)), ModuleSerializer.Serialize(this));
File.WriteAllText(PointerPath ?? throw new ArgumentNullException(nameof(PointerPath)), ModuleSerializer.Serialize(Config));
}

/// <summary>
Expand All @@ -454,7 +492,7 @@ public void DeserializeModule()
{
try
{
Config = EConfig.Deserializer.Deserialize<ModulePointer>(File.ReadAllText(PointerPath));
Config = ModuleDeserializer.Deserialize<ModulePointer>(File.ReadAllText(PointerPath));
}
catch
{
Expand All @@ -470,7 +508,7 @@ public void DeserializeModule()
return;
}

CustomModule deserializedModule = EConfig.Deserializer.Deserialize(File.ReadAllText(FilePath), GetType()) as CustomModule;
CustomModule deserializedModule = ModuleDeserializer.Deserialize(File.ReadAllText(FilePath), GetType()) as CustomModule;
CopyProperties(deserializedModule);

foreach (string file in Directory.GetFiles(ChildPath))
Expand All @@ -480,7 +518,7 @@ public void DeserializeModule()

try
{
Config = EConfig.Deserializer.Deserialize<ModulePointer>(File.ReadAllText(file));
Config = ModuleDeserializer.Deserialize<ModulePointer>(File.ReadAllText(file));
}
catch
{
Expand Down
113 changes: 113 additions & 0 deletions Exiled.CustomModules/API/Features/CustomModuleSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// -----------------------------------------------------------------------
// <copyright file="CustomModuleSerializer.cs" company="Exiled Team">
// Copyright (c) Exiled Team. All rights reserved.
// Licensed under the CC BY-SA 3.0 license.
// </copyright>
// -----------------------------------------------------------------------

namespace Exiled.CustomModules.API.Features
{
using System;
using System.Reflection;

using Attributes;
using Generic;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

/// <summary>
/// A IYamlTypeConverter for custom modules.
/// </summary>
public class CustomModuleSerializer : IYamlTypeConverter
{
/// <inheritdoc />
public bool Accepts(Type type)
{
return type == typeof(ModulePointer) || type == typeof(ModulePointer<>);
}

/// <inheritdoc />
public object ReadYaml(IParser parser, Type type)
{
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(ModulePointer<>))
throw new InvalidOperationException($"Unsupported type: {type.FullName}");
Type genericArgument = type.GetGenericArguments()[0];
MethodInfo method = GetType().GetMethod(nameof(ReadYamlGeneric), BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo genericMethod = method?.MakeGenericMethod(genericArgument);
return genericMethod?.Invoke(this, new object[] { parser });
}

/// <inheritdoc />
public void WriteYaml(IEmitter emitter, object value, Type type)
{
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(ModulePointer<>))
throw new ArgumentException("The type must be the generic ModulePointer.");
Type genericArgument = type.GetGenericArguments()[0];
MethodInfo method = GetType().GetMethod(nameof(WriteYamlGeneric), BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo genericMethod = method?.MakeGenericMethod(genericArgument);
genericMethod?.Invoke(this, new[] { emitter, value });
}

private void WriteYamlGeneric<TType>(IEmitter emitter, object value)
where TType : CustomModule
{
if (value is not ModulePointer<TType> pointer)
{
throw new ArgumentNullException(nameof(pointer), @"Value is not a valid ModulePointer.");
}

emitter.Emit(new MappingStart(null, null, false, MappingStyle.Block));

emitter.Emit(new Scalar(null, "id"));
emitter.Emit(new Scalar(null, pointer.Id.ToString()));

emitter.Emit(new Scalar(null, "module"));
emitter.Emit(new Scalar(null, typeof(TType).Name));

emitter.Emit(new Scalar(null, "assembly"));
emitter.Emit(new Scalar(null, pointer.GetType().Assembly.FullName));

emitter.Emit(new MappingEnd());
}

private object ReadYamlGeneric<TType>(IParser parser)
where TType : CustomModule
{
parser.Consume<MappingStart>();

parser.Consume<Scalar>(); // id key
string id = parser.Consume<Scalar>().Value;

parser.Consume<Scalar>(); // module key
string module = parser.Consume<Scalar>().Value;

parser.Consume<Scalar>(); // assembly key
string assemblyName = parser.Consume<Scalar>().Value;

parser.Consume<MappingEnd>();

// Load the specified assembly
Assembly assembly = Assembly.Load(assemblyName);
if (assembly == null)
{
throw new InvalidOperationException($"Assembly '{assemblyName}' could not be loaded.");
}

// Create an instance of the appropriate ModulePointer<TType> subclass
foreach (Type t in assembly.GetTypes())
{
ModuleIdentifierAttribute moduleIdentifier = t.GetCustomAttribute<ModuleIdentifierAttribute>();
if (moduleIdentifier == null || moduleIdentifier.Id != uint.Parse(id) || !typeof(ModulePointer<TType>).IsAssignableFrom(t))
continue;
ModulePointer<TType> instance = Activator.CreateInstance(t) as ModulePointer<TType>;
if (instance == null)
continue;
instance.Id = Convert.ToUInt32(id);
return instance;
}

throw new InvalidOperationException($"Could not find a suitable ModulePointer<{typeof(TType).Name}> type for id {id}");
}
}
}
Loading