102 lines
2.7 KiB
C#
102 lines
2.7 KiB
C#
using System;
|
|
using System.Text.RegularExpressions;
|
|
using Godot;
|
|
using SpacetimeDB;
|
|
using SpacetimeDB.Types;
|
|
|
|
public class Spacetime
|
|
{
|
|
/// The URI of the SpacetimeDB instance hosting our chat database and module.
|
|
const string HOST = "http://localhost:3000";
|
|
|
|
/// The database name we chose when we published our module.
|
|
const string DB_NAME = "massive";
|
|
|
|
public static Spacetime Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = new Spacetime(HOST, DB_NAME);
|
|
}
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
// our local client SpacetimeDB identity
|
|
public Identity Identity { get; private set; }
|
|
public DbConnection Connection { get; private set; }
|
|
public User Me
|
|
{
|
|
get => Connection.Db.User.Identity.Find(Identity);
|
|
}
|
|
|
|
private static Spacetime _instance;
|
|
|
|
string GetClientArg()
|
|
{
|
|
foreach (string arg in OS.GetCmdlineUserArgs())
|
|
{
|
|
GD.Print(arg);
|
|
if (new Regex("--client=.+").IsMatch(arg))
|
|
{
|
|
return arg.Split("=")[1];
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public Spacetime(string host, string dbName)
|
|
{
|
|
string client = GetClientArg() ?? "massive";
|
|
|
|
// Initialize the `AuthToken` module
|
|
AuthToken.Init($".spacetime/{client}");
|
|
|
|
Connection = DbConnection
|
|
.Builder()
|
|
.WithUri(host)
|
|
.WithModuleName(dbName)
|
|
.WithToken(AuthToken.Token)
|
|
.OnConnect(OnConnected)
|
|
.OnConnectError(OnConnectError)
|
|
.OnDisconnect(OnDisconnected)
|
|
.Build();
|
|
}
|
|
|
|
/// Our `OnConnected` callback: save our credentials to a file.
|
|
void OnConnected(DbConnection conn, Identity identity, string authToken)
|
|
{
|
|
Identity = identity;
|
|
AuthToken.SaveToken(authToken);
|
|
|
|
conn.SubscriptionBuilder().OnApplied(OnSubscriptionApplied).SubscribeToAllTables();
|
|
}
|
|
|
|
/// Our `OnSubscriptionApplied` callback:
|
|
/// sort all past messages and print them in timestamp order.
|
|
void OnSubscriptionApplied(SubscriptionEventContext ctx)
|
|
{
|
|
GD.Print("Connected");
|
|
}
|
|
|
|
/// Our `OnConnectError` callback: print the error, then exit the process.
|
|
void OnConnectError(Exception e)
|
|
{
|
|
GD.PrintErr($"Error while connecting: {e}");
|
|
}
|
|
|
|
/// Our `OnDisconnect` callback: print a note, then exit the process.
|
|
void OnDisconnected(DbConnection conn, Exception? e)
|
|
{
|
|
if (e != null)
|
|
{
|
|
GD.PrintErr($"Disconnected abnormally: {e}");
|
|
}
|
|
else
|
|
{
|
|
GD.Print($"Disconnected normally.");
|
|
}
|
|
}
|
|
}
|