AP.NET/ObjectStore.cs

93 lines
2.8 KiB
C#
Raw Permalink Normal View History

using ActivityPub.Controllers;
using ActivityPub.Utils;
using Microsoft.AspNetCore.Mvc;
using KristofferStrube.ActivityStreams;
using Object = KristofferStrube.ActivityStreams.Object;
namespace ActivityPub;
/// <summary>
/// A Data layer to store objects
/// </summary>
public class ObjectStore {
private static Dictionary<string, Dictionary<string, Object>> _objects = new();
private IUrlHelper Url { get; set; }
/// <summary>
/// Default Constructor
/// </summary>
/// <param name="url">A url helper to construct id urls</param>
public ObjectStore(IUrlHelper url) {
this.Url = url;
}
/// <summary>
/// Gets a new Id for an Object
/// </summary>
public static string NewId {
get {
long idTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//while (_objects.ContainsKey(Base36.ToString(idTime))) idTime++;
return Base36.ToString(idTime);
}
}
/// <summary>
/// Inserts a new object into the data store
/// </summary>
/// <param name="newObject">The object to store</param>
/// <returns>
/// The new Object to be stored
/// (with updated properties such as Id, Bto and Bcc removed, etc.)
/// </returns>
public Object InsertObject(Object newObject) {
if (newObject.Type == null) throw new ArgumentException("Object must have Type");
string id = NewId;
newObject.Id = this.Url.AbsoluteContent($"~/{newObject.Type.First()}/{id}");
newObject.Bto = newObject.Bcc = null;
string objectType = newObject.Type.First();
if (!ObjectController._objects.ContainsKey(objectType)) ObjectController._objects[objectType] = new();
ObjectController._objects[objectType][id] = newObject;
return newObject;
}
/// <summary>
/// Gets an object just by Id
/// </summary>
/// <param name="id">The Id to find</param>
/// <returns>The object with the corresponding id, or null if not found</returns>
public Object? GetObjectById(string id) {
foreach (Dictionary<string, Object> list in _objects.Values) {
foreach (KeyValuePair<string, Object> kvp in list) {
if (kvp.Key == id) return kvp.Value;
}
}
return null;
}
/// <summary>
/// Gets an object by type and id
/// </summary>
/// <param name="type">The type</param>
/// <param name="id"></param>
/// <returns></returns>
public Object? GetObjectByTypeAndId(string type, string id) {
type = Types.Normalize(type);
return _objects[type]?[id];
}
/// <summary>
/// Gets a list of all Objects by Type
/// </summary>
/// <param name="type">The type of object to retrieve</param>
/// <returns>A list of objects of the specified type</returns>
public List<Object> GetObjectsByType(string type) {
type = Types.Normalize(type);
return _objects[type]?.Values.ToList() ?? new List<Object>();
}
}