Skip to content

Commit

Permalink
[OneBot] Some classes cannot be successfully deserialized from Bson (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkRRb authored Oct 28, 2024
1 parent 64d4481 commit 94b6390
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
7 changes: 6 additions & 1 deletion Lagrange.OneBot/LagrangeAppBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Diagnostics;
using Lagrange.Core.Common;
using Lagrange.Core.Common.Interface;
using Lagrange.Core.Utility.Sign;
Expand Down Expand Up @@ -119,6 +118,12 @@ public LagrangeAppBuilder ConfigureOneBot()
BsonMapper.Global.TrimWhitespace = false;
BsonMapper.Global.EmptyStringToNull = false;
// Specify ctor for some classes
BsonMapper.Global.RegisterType(
LiteDbUtility.IMessageEntitySerialize,
LiteDbUtility.IMessageEntityDeserialize
);
string path = Configuration["ConfigPath:Database"] ?? $"lagrange-{Configuration["Account:Uin"]}.db";
bool isFirstCreate = false;
Expand Down
49 changes: 49 additions & 0 deletions Lagrange.OneBot/Utility/LiteDbUtility.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using Lagrange.Core.Message;
using Lagrange.Core.Message.Entity;
using LiteDB;

namespace Lagrange.OneBot.Utility;

public static class LiteDbUtility
{
public static BsonValue IMessageEntitySerialize(IMessageEntity entity)
{
var type = entity.GetType();
var result = BsonMapper.Global.Serialize(type, entity);
result["_type"] = new BsonValue(DefaultTypeNameBinder.Instance.GetName(type));
return result;
}

public static IMessageEntity IMessageEntityDeserialize(BsonValue bson)
{
if (!bson.IsDocument) throw new Exception("bson not BsonDocument");

var doc = bson.AsDocument;
if (!doc.TryGetValue("_type", out var typeBson) || !typeBson.IsString)
{
throw new Exception("no `_type` or `_type` not string");
}

var type = DefaultTypeNameBinder.Instance.GetType(typeBson.AsString);

if (type == typeof(MarkdownEntity)) return MarkdownEntityDeserialize(doc);

return (IMessageEntity)BsonMapper.Global.Deserialize(type, bson);
}

private static MarkdownEntity MarkdownEntityDeserialize(BsonDocument doc)
{
if (!doc.TryGetValue("Data", out var dataBson) || !dataBson.IsDocument)
{
throw new Exception("no `Data` or `Data` not document");
}

var dataDocument = dataBson.AsDocument;
if (!dataDocument.TryGetValue("Content", out var contentBson) || !contentBson.IsString)
{
throw new InvalidCastException("no `Data.Content` or `Data.Content` not string");
}

return new(new MarkdownData() { Content = contentBson.AsString });
}
}

0 comments on commit 94b6390

Please sign in to comment.