using Godot; using SpacetimeDB; using SpacetimeDB.Types; public partial class ChatLog : RichTextLabel { const string SystemColor = "#747474"; public override void _EnterTree() { ClearLog(); } public override void _Ready() { DbConnection conn = Spacetime.Instance.Connection; RegisterSubscriptions(conn); } string UserNameOrIdentity(User user) { return user != null ? user.Name ?? user.Identity.ToString()[..8] : "unknown"; } void PushMessage(string name, string message, string color) { string entry = $"[color={color}]{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.SubscribeApplied) { return; } PushMessage("System", $"{UserNameOrIdentity(insertedValue)} connected", SystemColor); } void User_OnUpdate(EventContext ctx, User oldValue, User newValue) { if (oldValue.Name != newValue.Name) { PushMessage( "System", $"{UserNameOrIdentity(oldValue)} renamed to {UserNameOrIdentity(newValue)}", SystemColor ); } if (oldValue.Online != newValue.Online) { if (newValue.Online) { PushMessage("System", $"{UserNameOrIdentity(newValue)} connected", SystemColor); } else { PushMessage("System", $"{UserNameOrIdentity(newValue)} disconnected", SystemColor); } } } void Message_OnInsert(EventContext ctx, Message insertedValue) { User sender = ctx.Db.User.Identity.Find(insertedValue.Sender); string color = sender.Identity.Equals(Spacetime.Instance.Identity) ? "blue" : "red"; if (ctx.Event is Event.SubscribeApplied) { PushMessage(UserNameOrIdentity(sender), insertedValue.Text, color); return; } PushMessage(UserNameOrIdentity(sender), insertedValue.Text, color); } }