94 lines
2.5 KiB
C#
94 lines
2.5 KiB
C#
using Godot;
|
|
using SpacetimeDB;
|
|
using SpacetimeDB.Types;
|
|
|
|
public partial class ChatLog : RichTextLabel
|
|
{
|
|
private static readonly Color SystemColor = Colors.Gray;
|
|
|
|
public override void _EnterTree()
|
|
{
|
|
ClearLog();
|
|
}
|
|
|
|
public override void _Ready()
|
|
{
|
|
DbConnection conn = Spacetime.Instance.Connection;
|
|
RegisterSubscriptions(conn);
|
|
}
|
|
|
|
void PushMessage(string name, string message, Color color)
|
|
{
|
|
string entry = $"[color={color.ToHtml()}]{name}:[/color] {message}";
|
|
this.Text += $"{entry}\n";
|
|
}
|
|
|
|
void ClearLog()
|
|
{
|
|
Text = "";
|
|
}
|
|
|
|
void RegisterSubscriptions(DbConnection conn)
|
|
{
|
|
conn.Db.User.OnInsert += User_OnInsert;
|
|
conn.Db.User.OnUpdate += User_OnUpdate;
|
|
|
|
conn.Db.Message.OnInsert += Message_OnInsert;
|
|
}
|
|
|
|
void User_OnInsert(EventContext ctx, User insertedValue)
|
|
{
|
|
if (ctx.Event is Event<Reducer>.SubscribeApplied)
|
|
{
|
|
return;
|
|
}
|
|
PushMessage(
|
|
"System",
|
|
$"{UserUtils.UserNameOrIdentity(insertedValue)} connected",
|
|
SystemColor
|
|
);
|
|
}
|
|
|
|
void User_OnUpdate(EventContext ctx, User oldValue, User newValue)
|
|
{
|
|
if (oldValue.Name != newValue.Name)
|
|
{
|
|
PushMessage(
|
|
"System",
|
|
$"{UserUtils.UserNameOrIdentity(oldValue)} renamed to {UserUtils.UserNameOrIdentity(newValue)}",
|
|
SystemColor
|
|
);
|
|
}
|
|
if (oldValue.Online != newValue.Online)
|
|
{
|
|
if (newValue.Online)
|
|
{
|
|
PushMessage(
|
|
"System",
|
|
$"{UserUtils.UserNameOrIdentity(newValue)} connected",
|
|
SystemColor
|
|
);
|
|
}
|
|
else
|
|
{
|
|
PushMessage(
|
|
"System",
|
|
$"{UserUtils.UserNameOrIdentity(newValue)} disconnected",
|
|
SystemColor
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
void Message_OnInsert(EventContext ctx, Message insertedValue)
|
|
{
|
|
User sender = ctx.Db.User.Identity.Find(insertedValue.Sender);
|
|
Color color = ctx.Identity == sender.Identity ? UserUtils.ParseColor(sender) : Colors.Red;
|
|
if (ctx.Event is Event<Reducer>.SubscribeApplied)
|
|
{
|
|
PushMessage(UserUtils.UserNameOrIdentity(sender), insertedValue.Text, color);
|
|
return;
|
|
}
|
|
PushMessage(UserUtils.UserNameOrIdentity(sender), insertedValue.Text, color);
|
|
}
|
|
}
|