Skip to content

Commit

Permalink
Refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
openbullet committed Dec 15, 2024
1 parent 85bec99 commit a05515b
Show file tree
Hide file tree
Showing 27 changed files with 839 additions and 633 deletions.
8 changes: 4 additions & 4 deletions OpenBullet2.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
builder.Services.AddScoped<IGuestRepository, DbGuestRepository>();
builder.Services.AddScoped<IRecordRepository, DbRecordRepository>();
builder.Services.AddScoped<IWordlistRepository>(service =>
new HybridWordlistRepository(service.GetService<ApplicationDbContext>(),
new HybridWordlistRepository(service.GetRequiredService<ApplicationDbContext>(),
$"{Globals.UserDataFolder}/Wordlists"));

builder.Services.AddScoped<DataPoolFactoryService>();
Expand All @@ -143,7 +143,7 @@
builder.Services.AddSingleton<IUpdateService, UpdateService>();
builder.Services.AddSingleton<PerformanceMonitorService>();
builder.Services.AddSingleton<IConfigRepository>(service =>
new DiskConfigRepository(service.GetService<RuriLibSettingsService>(),
new DiskConfigRepository(service.GetRequiredService<RuriLibSettingsService>(),
$"{Globals.UserDataFolder}/Configs"));
builder.Services.AddSingleton<ConfigService>();
builder.Services.AddSingleton(service =>
Expand All @@ -155,7 +155,7 @@
builder.Services.AddSingleton<ProxyCheckOutputFactory>();
builder.Services.AddSingleton<JobManagerService>();
builder.Services.AddSingleton(service =>
new JobMonitorService(service.GetService<JobManagerService>(),
new JobMonitorService(service.GetRequiredService<JobManagerService>(),
$"{Globals.UserDataFolder}/triggeredActions.json", false));
builder.Services.AddSingleton<HitStorageService>();
builder.Services.AddSingleton(_ => new RuriLibSettingsService(Globals.UserDataFolder));
Expand All @@ -166,7 +166,7 @@
_ => new IntoliRandomUAProvider("user-agents.json"));
builder.Services.AddSingleton<IRNGProvider, DefaultRNGProvider>();
builder.Services.AddSingleton<IJobLogger>(service =>
new FileJobLogger(service.GetService<RuriLibSettingsService>(),
new FileJobLogger(service.GetRequiredService<RuriLibSettingsService>(),
$"{Globals.UserDataFolder}/Logs/Jobs"));
builder.Services.AddSingleton<ConfigDebuggerService>();
builder.Services.AddSingleton<ProxyCheckJobService>();
Expand Down
42 changes: 24 additions & 18 deletions OpenBullet2.Web/Utils/BlockMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@
using RuriLib.Models.Blocks.Settings;
using RuriLib.Models.Blocks.Settings.Interpolated;
using System.Text.Json;
using OpenBullet2.Web.Exceptions;

namespace OpenBullet2.Web.Utils;

static internal class BlockMapper
internal static class BlockMapper
{
// Here I did the dto -> block mappings manually while I find
// a way to make automapper work properly on BlockSetting...
static internal List<BlockInstance> MapStack(
internal static List<BlockInstance> MapStack(
this List<JsonElement> jsonElements, IMapper mapper)
{
var stack = new List<BlockInstance>();
Expand All @@ -28,6 +29,11 @@ static internal List<BlockInstance> MapStack(
var id = jsonElement.GetProperty("id").GetString();
BlockInstance block;

if (id is null)
{
throw new MappingException("Block id not found");
}

switch (id)
{
case "HttpRequest":
Expand Down Expand Up @@ -212,7 +218,7 @@ private static void MapMultipartSettings(MultipartRequestParamsDto dto,
foreach (var c in dto.Contents)
{
var contentDto = PolyMapper.ConvertPolyDto<HttpContentSettingsGroupDto>(
(JsonElement)c!);
(JsonElement)c);

HttpContentSettingsGroup content;

Expand Down Expand Up @@ -269,44 +275,44 @@ private static void MapSetting(BlockSettingDto? dto, BlockSetting setting)
}

setting.InputMode = dto.InputMode;
setting.InputVariableName = dto.InputVariableName;
setting.InputVariableName = dto.InputVariableName ?? string.Empty;
var value = (JsonElement)dto.Value!;

switch (dto.Type)
{
case BlockSettingType.String:
((StringSetting)setting.FixedSetting).Value = value.GetString();
((InterpolatedStringSetting)setting.InterpolatedSetting).Value = value.GetString();
((StringSetting)setting.FixedSetting!).Value = value.GetString();
((InterpolatedStringSetting)setting.InterpolatedSetting!).Value = value.GetString();
break;

case BlockSettingType.Int:
((IntSetting)setting.FixedSetting).Value = value.GetInt32();
((IntSetting)setting.FixedSetting!).Value = value.GetInt32();
break;

case BlockSettingType.Float:
((FloatSetting)setting.FixedSetting).Value = value.GetSingle();
((FloatSetting)setting.FixedSetting!).Value = value.GetSingle();
break;

case BlockSettingType.Bool:
((BoolSetting)setting.FixedSetting).Value = value.GetBoolean();
((BoolSetting)setting.FixedSetting!).Value = value.GetBoolean();
break;

case BlockSettingType.ByteArray:
((ByteArraySetting)setting.FixedSetting).Value = value.GetBytesFromBase64();
((ByteArraySetting)setting.FixedSetting!).Value = value.GetBytesFromBase64();
break;

case BlockSettingType.ListOfStrings:
((ListOfStringsSetting)setting.FixedSetting).Value = value
.Deserialize<List<string>>(Globals.JsonOptions);
((InterpolatedListOfStringsSetting)setting.InterpolatedSetting).Value = value
.Deserialize<List<string>>(Globals.JsonOptions);
((ListOfStringsSetting)setting.FixedSetting!).Value = value
.Deserialize<List<string>>(Globals.JsonOptions)!;
((InterpolatedListOfStringsSetting)setting.InterpolatedSetting!).Value = value
.Deserialize<List<string>>(Globals.JsonOptions)!;
break;

case BlockSettingType.DictionaryOfStrings:
((DictionaryOfStringsSetting)setting.FixedSetting).Value = value
.Deserialize<Dictionary<string, string>>(Globals.JsonOptions);
((InterpolatedDictionaryOfStringsSetting)setting.InterpolatedSetting).Value = value
.Deserialize<Dictionary<string, string>>(Globals.JsonOptions);
((DictionaryOfStringsSetting)setting.FixedSetting!).Value = value
.Deserialize<Dictionary<string, string>>(Globals.JsonOptions)!;
((InterpolatedDictionaryOfStringsSetting)setting.InterpolatedSetting!).Value = value
.Deserialize<Dictionary<string, string>>(Globals.JsonOptions)!;
break;

case BlockSettingType.Enum:
Expand Down
143 changes: 67 additions & 76 deletions RuriLib/Helpers/Blocks/DescriptorsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ namespace RuriLib.Helpers.Blocks
/// </summary>
public class DescriptorsRepository
{
private static readonly Dictionary<Type, VariableType?> _variableTypes = new()
{
[ typeof(void) ] = null,
[ typeof(string) ] = VariableType.String,
[ typeof(int) ] = VariableType.Int,
[ typeof(float) ] = VariableType.Float,
[ typeof(bool) ] = VariableType.Bool,
[ typeof(List<string>) ] = VariableType.ListOfStrings,
[ typeof(Dictionary<string, string>) ] = VariableType.DictionaryOfStrings,
[ typeof(byte[]) ] = VariableType.ByteArray,
[ typeof(Task) ] = null,
[ typeof(Task<string>) ] = VariableType.String,
[ typeof(Task<int>) ] = VariableType.Int,
[ typeof(Task<float>) ] = VariableType.Float,
[ typeof(Task<bool>) ] = VariableType.Bool,
[ typeof(Task<List<string>>) ] = VariableType.ListOfStrings,
[ typeof(Task<Dictionary<string, string>>) ] = VariableType.DictionaryOfStrings,
[ typeof(Task<byte[]>) ] = VariableType.ByteArray
};

public Dictionary<string, BlockDescriptor> Descriptors { get; set; } = new Dictionary<string, BlockDescriptor>();

/// <summary>
Expand Down Expand Up @@ -173,45 +193,13 @@ private static BlockParameter BuildBlockParameter(ParameterInfo info)

/// <summary>
/// Converts the return <paramref name="type"/> of a method to a <see cref="VariableType"/>.
/// Returns null if the method returns <see cref="void"/> or <see cref="Task"/>.
/// Returns null if the method returns void or Task.
/// </summary>
public static VariableType? ToVariableType(Type type)
{
if (type == typeof(void))
return null;

var dict = new Dictionary<Type, VariableType>
{
{ typeof(string), VariableType.String },
{ typeof(int), VariableType.Int },
{ typeof(float), VariableType.Float },
{ typeof(bool), VariableType.Bool },
{ typeof(List<string>), VariableType.ListOfStrings },
{ typeof(Dictionary<string, string>), VariableType.DictionaryOfStrings },
{ typeof(byte[]), VariableType.ByteArray }
};

if (dict.ContainsKey(type))
return dict[type];

if (type == typeof(Task))
return null;

var taskDict = new Dictionary<Type, VariableType>
{
{ typeof(Task<string>), VariableType.String },
{ typeof(Task<int>), VariableType.Int },
{ typeof(Task<float>), VariableType.Float },
{ typeof(Task<bool>), VariableType.Bool },
{ typeof(Task<List<string>>), VariableType.ListOfStrings },
{ typeof(Task<Dictionary<string, string>>), VariableType.DictionaryOfStrings },
{ typeof(Task<byte[]>), VariableType.ByteArray }
};

if (taskDict.ContainsKey(type))
return taskDict[type];

throw new InvalidCastException($"The type {type} could not be casted to VariableType");
_variableTypes.TryGetValue(type, out var value);
return value ?? throw new InvalidCastException(
$"The type {type} could not be casted to VariableType");
}

/// <summary>
Expand All @@ -223,7 +211,10 @@ public static Variable ToVariable(string name, Type type, dynamic value)
var t = ToVariableType(type);

if (!t.HasValue)
throw new InvalidCastException($"Cannot cast type {type} to a variable");
{
throw new InvalidCastException(
$"Cannot cast type {type} to a variable");
}

Variable variable = t switch
{
Expand All @@ -244,58 +235,56 @@ public static Variable ToVariable(string name, Type type, dynamic value)

private static BlockParameter ToBlockParameter(ParameterInfo parameter)
{
var dict = new Dictionary<Type, Func<BlockParameter>>
var creators = new Dictionary<Type, Func<BlockParameter>>
{
{ typeof(string), () => new StringParameter
{ typeof(string), () => new StringParameter(parameter.Name!)
{
DefaultValue = parameter.HasDefaultValue ? (string)parameter.DefaultValue : "",
DefaultValue = parameter.HasDefaultValue ? (string)parameter.DefaultValue! : "",
MultiLine = parameter.GetCustomAttribute<Attributes.MultiLine>() != null
}
},

{ typeof(int), () => new IntParameter
{ DefaultValue = parameter.HasDefaultValue ? (int)parameter.DefaultValue : 0 } },
{ typeof(int), () => new IntParameter(parameter.Name!)
{ DefaultValue = parameter.HasDefaultValue ? (int)parameter.DefaultValue! : 0 } },

{ typeof(float), () => new FloatParameter
{ DefaultValue = parameter.HasDefaultValue ? (float)parameter.DefaultValue : 0.0f } },
{ typeof(float), () => new FloatParameter(parameter.Name!)
{ DefaultValue = parameter.HasDefaultValue ? (float)parameter.DefaultValue! : 0.0f } },

{ typeof(bool), () => new BoolParameter
{ DefaultValue = parameter.HasDefaultValue ? (bool)parameter.DefaultValue : false } },
{ typeof(bool), () => new BoolParameter(parameter.Name!)
{ DefaultValue = parameter.HasDefaultValue && (bool)parameter.DefaultValue! } },

// TODO: Add defaults for these through parameter attributes
{ typeof(List<string>), () => new ListOfStringsParameter() },
{ typeof(Dictionary<string, string>), () => new DictionaryOfStringsParameter() },
{ typeof(byte[]), () => new ByteArrayParameter() }
{ typeof(List<string>), () => new ListOfStringsParameter(parameter.Name!) },
{ typeof(Dictionary<string, string>), () => new DictionaryOfStringsParameter(parameter.Name!) },
{ typeof(byte[]), () => new ByteArrayParameter(parameter.Name!) }
};

var blockParamAttribute = parameter.GetCustomAttribute<Attributes.BlockParam>();

// If it's one of the standard types
if (dict.ContainsKey(parameter.ParameterType))
if (creators.TryGetValue(parameter.ParameterType, out var creator))
{
var blockParam = dict[parameter.ParameterType].Invoke();
var blockParam = creator.Invoke();

if (blockParamAttribute != null)
{
blockParam.AssignedName = blockParamAttribute.name;
blockParam.Description = blockParamAttribute.description;
}

blockParam.Name = parameter.Name;
blockParam.Name = parameter.Name!;
return blockParam;
}

// If it's an enum type
if (parameter.ParameterType.IsEnum)
{
var blockParam = new EnumParameter
{
Name = parameter.Name,
EnumType = parameter.ParameterType,
DefaultValue = parameter.HasDefaultValue
? parameter.DefaultValue.ToString()
: Enum.GetNames(parameter.ParameterType).First()
};
var blockParam = new EnumParameter(
parameter.Name!,
parameter.ParameterType,
parameter.HasDefaultValue
? parameter.DefaultValue!.ToString()!
: Enum.GetNames(parameter.ParameterType).First());

if (blockParamAttribute != null)
{
Expand Down Expand Up @@ -336,34 +325,36 @@ private void PushLeaves(CategoryTreeNode node, int level)
var split = d.Category.Path.Split('.'); // Example: RuriLib.Blocks.Http

// If a descriptor's category has a namespace which (split) is longer than the current tree level
if (split.Length > level)
// then it means that it has subcategories, otherwise it's a leaf
if (split.Length <= level)
{
var subCat = split[level]; // Example: level 0 => RuriLib, level 1 => Http

// Try to get an existing subcategory node
var subCatNode = node.SubCategories.FirstOrDefault(s => s.Name == subCat);
continue;
}

var subCat = split[level]; // Example: level 0 => RuriLib, level 1 => Http

// Create the subcategory node if it doesn't exist
if (subCatNode == null)
{
subCatNode = new CategoryTreeNode { Parent = node, Name = subCat };
node.SubCategories.Add(subCatNode);
}
// Try to get an existing subcategory node
var subCatNode = node.SubCategories.FirstOrDefault(s => s.Name == subCat);

subCatNode.Descriptors.Add(d);
node.Descriptors.RemoveAt(i);
i--;
// Create the subcategory node if it doesn't exist
if (subCatNode == null)
{
subCatNode = new CategoryTreeNode { Parent = node, Name = subCat };
node.SubCategories.Add(subCatNode);
}

subCatNode.Descriptors.Add(d);
node.Descriptors.RemoveAt(i);
i--;
}

// Order them alphabetically
node.SubCategories = node.SubCategories.OrderBy(s => s.Name).ToList();
node.Descriptors = node.Descriptors.OrderBy(d => d.Name).ToList();

// Push leaves of subcategories recursively
for (var i = 0; i < node.SubCategories.Count; i++)
foreach (var s in node.SubCategories)
{
var s = node.SubCategories[i];
PushLeaves(s, level + 1);
}
}
Expand Down
Loading

0 comments on commit a05515b

Please sign in to comment.