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