sharp-chat/SharpChatCommon/EventStorage/VirtualEventStorage.cs

95 lines
3.3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace SharpChat.EventStorage {
public class VirtualEventStorage : IEventStorage {
private readonly Dictionary<long, StoredEventInfo> Events = new();
public void AddEvent(
long id, string type,
2024-05-10 19:18:55 +00:00
object? data = null,
StoredEventFlags flags = StoredEventFlags.None
) {
AddEvent(id, type, null, 0, null, Colour.None, 0, null, 0, data, flags);
}
public void AddEvent(
long id, string type,
2024-05-10 19:18:55 +00:00
string? channelName,
object? data = null,
StoredEventFlags flags = StoredEventFlags.None
) {
AddEvent(id, type, channelName, 0, null, Colour.None, 0, null, 0, data, flags);
}
public void AddEvent(
long id, string type,
long senderId, string? senderName, Colour senderColour, int senderRank, string? senderNick, UserPermissions senderPerms,
2024-05-10 19:18:55 +00:00
object? data = null,
StoredEventFlags flags = StoredEventFlags.None
) {
AddEvent(id, type, null, senderId, senderName, senderColour, senderRank, senderNick, senderPerms, data, flags);
}
public void AddEvent(
long id, string type,
2024-05-10 19:18:55 +00:00
string? channelName,
long senderId, string? senderName, Colour senderColour, int senderRank, string? senderNick, UserPermissions senderPerms,
2024-05-10 19:18:55 +00:00
object? data = null,
StoredEventFlags flags = StoredEventFlags.None
) {
// VES is meant as an emergency fallback but this is something else
JsonDocument hack = JsonDocument.Parse(data == null ? "{}" : JsonSerializer.Serialize(data));
Events.Add(id, new(id, type, senderId < 1 ? null : new UserInfo(
senderId,
senderName ?? string.Empty,
senderColour,
senderRank,
senderPerms,
senderNick
), DateTimeOffset.Now, null, channelName, hack, flags));
}
public long AddEvent(string type, UserInfo user, ChannelInfo channel, object? data = null, StoredEventFlags flags = StoredEventFlags.None) {
long id = SharpId.Next();
AddEvent(
id, type,
channel?.Name,
user?.UserId ?? 0,
user?.UserName,
user?.Colour ?? Colour.None,
user?.Rank ?? 0,
user?.NickName,
user?.Permissions ?? 0,
data,
flags
);
return id;
}
2024-05-10 19:18:55 +00:00
public StoredEventInfo? GetEvent(long seqId) {
return Events.TryGetValue(seqId, out StoredEventInfo? evt) ? evt : null;
}
public void RemoveEvent(StoredEventInfo evt) {
Events.Remove(evt.Id);
}
public IEnumerable<StoredEventInfo> GetChannelEventLog(string channelName, int amount = 20, int offset = 0) {
IEnumerable<StoredEventInfo> subset = Events.Values.Where(ev => ev.ChannelName == channelName);
int start = subset.Count() - offset - amount;
if(start < 0) {
amount += start;
start = 0;
}
return subset.Skip(start).Take(amount).ToArray();
}
}
}