warriordog / ActivityPubSharp

Modular implementation of ActivityPub in C#
https://warriordog.github.io/ActivityPubSharp/
Mozilla Public License 2.0
45 stars 9 forks source link

Get object's type string after deserialization #158

Closed jenniferplusplus closed 7 months ago

jenniferplusplus commented 8 months ago

Is there a way to preserve the json value for the type property, and make it available on the object?

When a federated server receives an object in an inbox, we can be pretty sure it's an Activity, but there's no way to predict which Activity it will be. And in ASP.Net core, it's somewhere between difficult and impossible to recover the raw http request body. This means that it's not feasible to actually get the type from the received object. That's particularly problematic if we should encounter brand new types, because it's not even possible to track what they are.

jenniferplusplus commented 8 months ago

@warriordog fyi

warriordog commented 8 months ago

@jenniferplusplus You can get a version of it through object.TypeMap.ASTypes. That's a live property which always represents the type field as it will be serialized. I used to have it exposed as an alias property on ASType, but it got lost during some refactoring. I can add it back if that would be useful.

There's also TypeMap.AllASTypes, which is a superset that includes duplicates. If neither of those works for you, then I may be able to add a copy of the raw value. That will take some thinking though.

warriordog commented 7 months ago

@jenniferplusplus I pushed a commit to expose Type and JsonLDContext as properties on ASType. This should support your use case. You can also do this, which may be cleaner in some scenarios:

public void Test(ASType asType)
{
    if (asType.Is<ASActivity>(out var activity))
    {
        Console.WriteLine("Is an activity:");
        Console.WriteLine($"Object = {activity.Object?.Id}");
        Console.WriteLine($"Target = {activity.Target?.Id}");
    }
    else
    {
        Console.WriteLine("Not an activity.");
    }
}